Web程式設計學習四: 使用Jersey來建立RESTful WebService
RESTful Web Service是輕量級的service,可以通過HTTP的方式來實現對後臺資料庫的CRUD,
在Web開發和移動開發時使用的比較廣泛,非常方便。
在Java世界裡, JAX-RS規範定義了對RESTful Web Service的實現。
Oracle的Jersey框架則是對JAX-RS的一個實現。
下面我們學習如何使用Jersey來建立RESTful WebService。
我的開發環境:
Eclipse Juno, Java 1.6, Tomcat 7.0, Jersey 1.18
1. 建立第一個RESTful web service
1.1建立一個叫jersey1的Dynamic Web Project.
1.2在WEB-INF/lib資料夾中匯入jersey的包。
1.3建立web.xml,定義Jersey的使用。
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>sample</display-name> <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>sample</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey REST Service</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping> </web-app>
1.4建立Java class
package sample; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; //Sets the path to base URL + /hello @Path("/hello") public class Hello { // This method is called if TEXT_PLAIN is request @GET @Produces(MediaType.TEXT_PLAIN) public String sayPlainTextHello() { return "Hello Jersey"; } // This method is called if XML is request @GET @Produces(MediaType.TEXT_XML) public String sayXMLHello() { return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>"; } // This method is called if HTML is request @GET @Produces(MediaType.TEXT_HTML) public String sayHtmlHello() { return "<html> " + "<title>" + "Hello Jersey" + "</title>" + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> "; } }
1.5.建立測試應用
package sample;
import java.net.URI;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
public class Test {
public static void main(String[] args) {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource service = client.resource(getBaseURI());
// Fluent interfaces
System.out.println(service.path("rest").path("hello")
.accept(MediaType.TEXT_PLAIN).get(ClientResponse.class)
.toString());
// Get plain text
System.out.println(service.path("rest").path("hello")
.accept(MediaType.TEXT_PLAIN).get(String.class));
// Get XML
System.out.println(service.path("rest").path("hello")
.accept(MediaType.TEXT_XML).get(String.class));
// The HTML
System.out.println(service.path("rest").path("hello")
.accept(MediaType.TEXT_HTML).get(String.class));
}
private static URI getBaseURI() {
return UriBuilder.fromUri(
"http://localhost:8080/jersey1").build();
}
}
1.6. 部署專案到tomcat後,執行Test程式:
2.然後來結合JAXB來建立RESTful web service.
JAX-RS可以直接通過JAXB來建立XML和JSON的輸出。
JAXB是Java對xml的實現。
2.1 建立叫jersey2的Dynamic Web Project,匯入jersey庫。
2.2 建立一個物件,這裡注意下,加上@XmlRootElement就可以了。
package sample;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Todo {
private String summary;
private String description;
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
2.3 建立一個class來呼叫jersey
package sample;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/todo")
public class TodoResource {
// This method is called if XMLis request
@GET
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Todo getXML() {
Todo todo = new Todo();
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
return todo;
}
// This can be used to test the integration with the browser
@GET
@Produces({ MediaType.TEXT_XML })
public Todo getHTML() {
Todo todo = new Todo();
todo.setSummary("This is my first todo");
todo.setDescription("This is my first todo");
return todo;
}
}
2.4 web.xml檔案
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>sample</display-name>
<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>sample</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
</web-app>
2.5 部署專案,然後通過瀏覽器來測試
輸入url: http://localhost:8080/jersey2/rest/todo
可以看到RESTful web service的輸出:
為了更清楚一點,我用Chrome瀏覽器的Postman來測試一下,這是一個RESTful的客戶端。
小結:
可以看到在Java中,可以通過JAX-RS+JAXB非常方便的實現RESTful web service。
直接在物件中定義url以及get,post,put,delete等方法就行了。