使用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的使用。

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <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">  
  3.   <display-name>sample</display-name>  
  4.   <servlet>  
  5.     <servlet-name>Jersey REST Service</servlet-name>  
  6.     <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>  
  7.     <init-param>  
  8.       <param-name>com.sun.jersey.config.property.packages</param-name>  
  9.       <param-value>sample</param-value>  
  10.     </init-param>  
  11.     <load-on-startup>1</load-on-startup>  
  12.   </servlet>  
  13.   <servlet-mapping>  
  14.     <servlet-name>Jersey REST Service</servlet-name>  
  15.     <url-pattern>/rest/*</url-pattern>  
  16.   </servlet-mapping>  
  17. </web-app>   


1.4创建Java class


[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package sample;  
  2.   
  3. import javax.ws.rs.GET;  
  4. import javax.ws.rs.Path;  
  5. import javax.ws.rs.Produces;  
  6. import javax.ws.rs.core.MediaType;  
  7.   
  8. //Sets the path to base URL + /hello  
  9. @Path("/hello")  
  10. public class Hello {  
  11.   
  12.     // This method is called if TEXT_PLAIN is request  
  13.     @GET  
  14.     @Produces(MediaType.TEXT_PLAIN)  
  15.     public String sayPlainTextHello() {  
  16.         return "Hello Jersey";  
  17.     }  
  18.   
  19.     // This method is called if XML is request  
  20.     @GET  
  21.     @Produces(MediaType.TEXT_XML)  
  22.     public String sayXMLHello() {  
  23.         return "<?xml version=\"1.0\"?>" + "<hello> Hello Jersey" + "</hello>";  
  24.     }  
  25.   
  26.     // This method is called if HTML is request  
  27.     @GET  
  28.     @Produces(MediaType.TEXT_HTML)  
  29.     public String sayHtmlHello() {  
  30.         return "<html> " + "<title>" + "Hello Jersey" + "</title>"  
  31.                 + "<body><h1>" + "Hello Jersey" + "</body></h1>" + "</html> ";  
  32.     }  
  33.   
  34. }  


1.5.创建测试应用

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package sample;  
  2.   
  3. import java.net.URI;  
  4.   
  5. import javax.ws.rs.core.MediaType;  
  6. import javax.ws.rs.core.UriBuilder;  
  7.   
  8. import com.sun.jersey.api.client.Client;  
  9. import com.sun.jersey.api.client.ClientResponse;  
  10. import com.sun.jersey.api.client.WebResource;  
  11. import com.sun.jersey.api.client.config.ClientConfig;  
  12. import com.sun.jersey.api.client.config.DefaultClientConfig;  
  13.   
  14. public class Test {  
  15.     public static void main(String[] args) {  
  16.         ClientConfig config = new DefaultClientConfig();  
  17.         Client client = Client.create(config);  
  18.         WebResource service = client.resource(getBaseURI());  
  19.         // Fluent interfaces  
  20.         System.out.println(service.path("rest").path("hello")  
  21.                 .accept(MediaType.TEXT_PLAIN).get(ClientResponse.class)  
  22.                 .toString());  
  23.         // Get plain text  
  24.         System.out.println(service.path("rest").path("hello")  
  25.                 .accept(MediaType.TEXT_PLAIN).get(String.class));  
  26.         // Get XML  
  27.         System.out.println(service.path("rest").path("hello")  
  28.                 .accept(MediaType.TEXT_XML).get(String.class));  
  29.         // The HTML  
  30.         System.out.println(service.path("rest").path("hello")  
  31.                 .accept(MediaType.TEXT_HTML).get(String.class));  
  32.   
  33.     }  
  34.   
  35.     private static URI getBaseURI() {  
  36.         return UriBuilder.fromUri(  
  37.                 "http://localhost:8080/jersey1").build();  
  38.     }  
  39.   
  40. }  

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就可以了。

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package sample;  
  2.   
  3. import javax.xml.bind.annotation.XmlRootElement;  
  4.   
  5. @XmlRootElement  
  6.   
  7. public class Todo {  
  8.     private String summary;  
  9.     private String description;  
  10.   
  11.     public String getSummary() {  
  12.         return summary;  
  13.     }  
  14.   
  15.     public void setSummary(String summary) {  
  16.         this.summary = summary;  
  17.     }  
  18.   
  19.     public String getDescription() {  
  20.         return description;  
  21.     }  
  22.   
  23.     public void setDescription(String description) {  
  24.         this.description = description;  
  25.     }  
  26.   
  27. }  


2.3 创建一个class来调用jersey

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package sample;  
  2.   
  3. import javax.ws.rs.GET;  
  4. import javax.ws.rs.Path;  
  5. import javax.ws.rs.Produces;  
  6. import javax.ws.rs.core.MediaType;  
  7.   
  8.   
  9. @Path("/todo")  
  10. public class TodoResource {  
  11.     // This method is called if XMLis request  
  12.     @GET  
  13.     @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })  
  14.     public Todo getXML() {  
  15.         Todo todo = new Todo();  
  16.         todo.setSummary("This is my first todo");  
  17.         todo.setDescription("This is my first todo");  
  18.         return todo;  
  19.     }  
  20.   
  21.     // This can be used to test the integration with the browser  
  22.     @GET  
  23.     @Produces({ MediaType.TEXT_XML })  
  24.     public Todo getHTML() {  
  25.         Todo todo = new Todo();  
  26.         todo.setSummary("This is my first todo");  
  27.         todo.setDescription("This is my first todo");  
  28.         return todo;  
  29.     }  
  30.   
  31. }  


2.4 web.xml文件

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  5.     id="WebApp_ID" version="2.5">  
  6.     <display-name>sample</display-name>  
  7.     <servlet>  
  8.         <servlet-name>Jersey REST Service</servlet-name>  
  9.         <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>  
  10.         <init-param>  
  11.             <param-name>com.sun.jersey.config.property.packages</param-name>  
  12.             <param-value>sample</param-value>  
  13.         </init-param>  
  14.         <load-on-startup>1</load-on-startup>  
  15.     </servlet>  
  16.     <servlet-mapping>  
  17.         <servlet-name>Jersey REST Service</servlet-name>  
  18.         <url-pattern>/rest/*</url-pattern>  
  19.     </servlet-mapping>  
  20. </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等方法就行了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值