RESTful webService 初使用

RESTFul webservices 比 SOAP webservice 輕量,簡單,易用。可是相對來講沒有SOAP那麼安全。html


A RESTFul webservices are based on the HTTP methods and the concept of REST. A RESTFul webservice typically defines the base URI for the services, the supported MIME-types (XML, Text, JSON, user-defined,..) and the set of operations (POST, GET, PUT, DELETE) which are supported.java

【摘自: http://www.vogella.com/articles/REST/article.html
web


簡要說明建立步驟:spring


建立web工程添加所需jar:api

asm-3.1.jar安全

jersey-client-1.2.jarapp

jersey-core-1.2.jaride

jersey-server-1.2.jar測試

jersey-spring-1.2.jarurl

jsr311-api-1.1.1.jar



web.xml 配置:

<servlet>

<servlet-name>Jersey REST Service</servlet-name>

<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>

<init-param>

<param-name>com.sun.jersey.config.property.packages</param-name>

<param-value>com.test.rest</param-value>  

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>Jersey REST Service</servlet-name>

<url-pattern>/rs/*</url-pattern>

</servlet-mapping>



txt/plain 測試:

package com.test.rest;


import javax.ws.rs.GET;

import javax.ws.rs.Path;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;


@Path("/hello")

public class HelloResource {

@GET

@Produces(MediaType.TEXT_PLAIN)

public String sayHello() {

return "Hello Jersey";

}

}


訪問 : http://localhost:8080/Rest/rs/hello

效果 :


html 測試:

package com.test.rest;


import javax.ws.rs.GET;

import javax.ws.rs.Path;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;


@Path("/html")

public class HtmlTest {


@GET

@Produces(MediaType.TEXT_HTML)

public String getHtml() {

return "\n<font color='red'>" + "Thisisaneasyresource(ashtmltext).\n"

+ "</font>";

}

}


訪問 : http://localhost:8080/Rest/rs/html

效果 :



xml  測試:

package com.test.rest;


import javax.ws.rs.GET;

import javax.ws.rs.Path;

import javax.ws.rs.Produces;

import javax.ws.rs.core.MediaType;


@Path("/xml")

public class XmlTest {


// @GET

// @Produces(MediaType.TEXT_XML)

// public String getXml() {

// return "<a>" + "Thisisaneasyresource(ashtmltext)." + "</a>";

// }


@GET

@Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })

public Test listPageByPropertiesWithSort() {

Test map = new Test("1", "111");

return map;

}

}


訪問 : http://localhost:8080/Rest/rs/xml

效果 :



客戶端調用 :

public static void main(String[] args) {

Client c = Client.create();

WebResource wr = c.resource("http://localhost:8080/Rest/rs/xml");

String txtRes = wr.accept(MediaType.APPLICATION_XML).get(String.class);

System.out.println("" + txtRes);

}

輸出:<?xml version="1.0" encoding="UTF-8" standalone="yes"?><test><id>1</id><name>111</name></test>

相關文章
相關標籤/搜索