Jersey to create Restful webservice
1、Jersey是什么 ?
Jersey是Oracle公司推出的restful框架属于glassfish项目。可以集成至tomcat、jetty使用,支持Servlet和Spring的整合,支持jsr311的1.1和1.0版本。官方网站: http://jersey.com/,要开发restful方式的webservice需要下载相应的工具包,具体地址如下: https://maven.java.net/content/repositories/releases/com/sun/jersey/要运行例子需要同时下载server和client;当然不想找那么多,可以直接下这个zip包, https://maven.java.net/service/local/artifact/maven/redirect?r=releases&g=com.sun.jersey&a=jersey-archive&v=1.10&e=zip 2、什么是Rest访问 REST (REpresentational State Transfer) 描述了一个架构样式的网络系统,比如 web 应用程序。它首次出现在 2000 年 Roy Fielding 的博士论文中,他是 HTTP 规范的主要编写者之一。REST 指的是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就是 RESTful。Web 应用程序最重要的 REST 原则是,客户端和服务器之间的交互在请求之间是无状态的。从客户端到服务器的每个请求都必须包含理解请求所必需的信息。如果服务器在请求之间的任何时间点重启,客户端不会得到通知。此外,无状态请求可以由任何可用服务器回答,这十分适合云计算之类的环境。客户端可以缓存数据以改进性能。在服务器端,应用程序状态和功能可以分为各种资源。资源是一个有趣的概念实体,它向客户端公开。资源的例子有:应用程序对象、数据库记录、算法等等。每个资源都使用 URI (Universal Resource Identifier) 得到一个惟一的地址。所有资源都共享统一的界面,以便在客户端和服务器之间传输状态。使用的是标准的 HTTP 方法,比如 GET、PUT、POST 和 DELETE。Hypermedia 是应用程序状态的引擎,资源表示通过超链接互联。 论文中文下载地址: REST_cn架构风格与基于网络的软件架构设计.pdf RESTful Web 服务示例 方法/资源资源集合,URI 如:http://host/<appctx>/resources 成员资源,URI 如:http://host/<appctx>/resources/1234 HTTP?方法映射到资源的?CRUD(创建、读取、更新和删除)操作。尽管您可以做一些小修改,比如让?PUT?方法变成创建或更新,但基本的模式如下: HTTP?GET:获取列出检索单个资源或资源集合。如检索标识为1234 的资源的表示形式。
HTTP?POST:新建资源。?在集合中创建数字资源,其ID是自动分配的,在下面创建一个子资源。
HTTP?PUT:更新现有资源或资源集合。如更新标记为1234的数字资源。
HTTP?DELETE:删除资源或资源集合。如删除标记为1234的数字资源。 3、Jersey常用注解 Jersey的配置全部基于注解,实体类与XML、JSON之间的转换,rest服务的发布,相关参数的配置等都可以基于注解完成,下面简要介绍使用到的注解:注解(Annotation):在 javax.ws.rs.* 中定义,是 JAX-RS (JSR 311) 规范的一部分。 >解决对象不能格式化成JSON问题:http://stackoverflow.com/questions/12179737/jersey-json-media-type-application-json-was-not-found。 需要在对象类上面加上@XmlRootElement注解就行,如: package com.boonya.restful.jersey; import java.io.Serializable; import javax.xml.bind.annotation.XmlRootElement; import org.springframework.stereotype.Component; @XmlRootElement @Component("user") public class User implements Serializable{ ?? ?private static final long serialVersionUID = -5656002284629831603L; ?? ?private int id; ?? ?private String userName; ?? ?private String password; ?? ?private String email; ?? ?//getters /setters ??????? //.............. } 5、Jersey请求响应数据媒体类型MediaType 参考: http://jackson.codehaus.org/javadoc/jax-rs/1.0/javax/ws/rs/core/MediaType.html?is-external=true ?static java.lang.String ?? ?APPLICATION_ATOM_XML?????????????????? "application/atom+xml" static MediaType ?? ? APPLICATION_ATOM_XML_TYPE????????????????? "application/atom+xml" static java.lang.String ?? ? APPLICATION_FORM_URLENCODED?????? "application/x-www-form-urlencoded" static MediaType ?? ?APPLICATION_FORM_URLENCODED_TYPE???? "application/x-www-form-urlencoded" static java.lang.String ?? ?APPLICATION_JSON???????? ????????????????? ? "application/json" static MediaType ?? ?APPLICATION_JSON_TYPE?????????????????????????? "application/json" static java.lang.String ?? ?APPLICATION_OCTET_STREAM???????? ?? "application/octet-stream" static MediaType ?? ? APPLICATION_OCTET_STREAM_TYPE????????? "application/octet-stream" static java.lang.String ?? ? APPLICATION_SVG_XML???????? ? ? ? ? ? ?? "application/svg+xml" static MediaType ?? ? APPLICATION_SVG_XML_TYPE???????? ? ? ? ? ?? "application/svg+xml" static java.lang.String ?? ? APPLICATION_XHTML_XML??????? ? ? ? ??? "application/xhtml+xml" static MediaType ?? ?APPLICATION_XHTML_XML_TYPE???????? ? ? ?? "application/xhtml+xml" static java.lang.String ?? ?APPLICATION_XML???????? ? ? ? ? ? ? ? ? ? ?? "application/xml" static MediaType ?? ? APPLICATION_XML_TYPE??????? ? ? ? ? ? ? ? ? ? ? "application/xml" static java.lang.String ?? ?MEDIA_TYPE_WILDCARD???????? ? ? ? ? ? ? The value of a type or subtype wildcard: "*" static java.lang.String ?? ?MULTIPART_FORM_DATA???????? ? ? ? ? ?? "multipart/form-data" static MediaType ?? ?MULTIPART_FORM_DATA_TYPE???????? ? ? ? ?? "multipart/form-data" static java.lang.String ?? ? TEXT_HTML???????? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "text/html" static MediaType ?? ? TEXT_HTML_TYPE???????????????????????????????????? "text/html" static java.lang.String ?? ?TEXT_PLAIN????? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? "text/plain" static MediaType ?? ? TEXT_PLAIN_TYPE??????? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? "text/plain" static java.lang.String ?? ?TEXT_XML ? ? ??????? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "text/xml" static MediaType ?? ?TEXT_XML_TYPE ? ??????? ? ? ? ? ? ? ? ? ? ? ? ? ? ? "text/xml" static java.lang.String ?? ?WILDCARD ?? ?????? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?? "*/*" static MediaType ?? ?WILDCARD_TYPE? ?????????????????????? "*/*" 使用方法:在方法名上加注解@Produces(MediaType.APPLICATION_JSON),表示回调函数响应数据为JSON格式。 6、Jersey实例开发 6-1、创建项目导入需要的Jar包
6-2、添加Jersey的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>restful</display-name> <!-- spring Configuration --> <!-- <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> --> <!-- Jersey Configuration --> <servlet> <servlet-name>Jersey Web Application</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.boonya.restful.jersey</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Jersey Web Application</servlet-name> <url-pattern>/services/*</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>6-3、编写服务代码 package com.boonya.restful.jersey; import javax.annotation.Resource; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; @Path(value = "/userservice") public class UserService { @Resource(name="user") User user; @GET @Produces(MediaType.TEXT_PLAIN) public String sayHello() { return "Hello Jersey"; } @GET @Produces(MediaType.TEXT_PLAIN) @Path("user/login/{username}/{password}") public String getUserEmail(@PathParam("username")String userName,@PathParam("password") String password) { if (userName.equals("boonya") && password.equals("123456")) { return "Hello boonya,you logined success! Your email is boonya@sina.com"; } return "Sorry,we didn't find this user's Account!"; } @GET @Produces(MediaType.APPLICATION_XML) @Path("user/info/xml") public User getUserInfoByxml(){ User user=new User(); user.setId(10000); user.setUserName("boonya"); user.setPassword("asdfg"); user.setEmail("boonya@sina.com"); return user; } @GET @Produces(MediaType.APPLICATION_JSON) @Path("user/info/json") public User getUserInfoByjson(){ User user=new User(); user.setId(10000); user.setUserName("boonya"); user.setPassword("asdfg"); user.setEmail("boonya@sina.com"); return user; } @POST @Produces(MediaType.TEXT_HTML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Path("user/add") public void addUser(@FormParam("username")String userName,@FormParam("password") String password){ user.setId(10001); user.setUserName(userName); user.setPassword(password); System.out.println(user!=null); } @PUT @Produces(MediaType.TEXT_HTML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Path("user/update/{id}") public void updateUser(@PathParam("id") int id,@PathParam("email")String email){ if(id==user.getId()){ user.setEmail(email); System.out.println("Update user success! "+user.getEmail()); } } @DELETE @Produces(MediaType.TEXT_HTML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Path("user/delete/{id}") public void addUser(@PathParam("id") int id){ if(id==user.getId()){ user=null; System.out.println("Delete user success!"); } } }7、Jersey客户端测试 package com.boonya.restful.jersey; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.core.header.MediaTypes; import com.sun.jersey.test.framework.JerseyTest; /** * 必须先部署项目并启动TOMCAT再进行客户端测试 */ public class ClientTest extends JerseyTest { public ClientTest()throws Exception { super("com.sun.jersey.samples.services.userservice.resources"); } /** * 获取用户JSON格式字符串信息 */ public void getUserInfoByJson() { WebResource webResource =super.client().resource("http://localhost:8080/restful/services/userservice/user/info/json"); String responseMsg = webResource.get(String.class); System.out.println(responseMsg); } /** * 获取用户XML格式字符串信息 */ public void getUserInfoByXml() { WebResource webResource =super.client().resource("http://localhost:8080/restful/services/userservice/user/info/xml"); String responseMsg = webResource.get(String.class); System.out.println(responseMsg); } /** * Test if a WADL document is available at the relative path * "application.wadl". */ public void testApplicationWadl() { WebResource webResource = resource(); String serviceWadl = webResource.path("application.wadl").accept(MediaTypes.WADL).get(String.class); System.out.println(serviceWadl.length() > 0); } public static void main(String[] args) throws Exception { ClientTest test=new ClientTest(); System.out.println("-------Json----"); test.getUserInfoByJson(); System.out.println("-------Xml----"); test.getUserInfoByXml(); } } 8、项目测试截图 8-1、GET访问
8-2、JSON访问数据
8-3、XML访问数据
8-4、客户端测试结果
9、参考资料 http://wenku.baidu.com/view/a8bd4e86ec3a87c24028c4b6.html http://wenku.baidu.com/view/39a69f2758fb770bf78a55ee.html http://www.techferry.com/articles/RESTful-web-services-JAX-RS-annotations.html http://www.ishang123.com/jishubowen/java/2012-08-01/126.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |