jersey的使用总结

转:http://blog.segmentfault.com/lenbo_ma/1190000000495321 ,谢谢原文作者的分享,这给我们信任提供了这么好的环境!再次感谢大神前辈们的分享。

前言

在短信平台一期工作中,为便于移动平台的开发,使用了Java Jersey框架开发RESTFul风格的Web Service接口。在使用的过程中发现了一些问题并积累了一些项目经验,做了一下总结,便于个人成长,同时也希望对有需要的同仁有好的借鉴和帮助。

简介

Jersey是JAX-RS(JSR311)开源参考实现用于构建 RESTful Web service,它包含三个部分:

  • 核心服务器(Core Server) :通过提供JSR 311中标准化的注释和API标准化,可以用直观的方式开发RESTful Web服务。

  • 核心客户端(Core Client) :Jersey客户端API能够帮助开发者与RESTful服务轻松通信;

  • 集成(Integration) :Jersey还提供可以轻松继承spring、Guice、Apache Abdera的库。

在本次开发中使用Jersey2.0,并且仅使用了核心服务器。

设置Jersey环境

Maven

 
  1. <!--jersey-->

  2. <dependency>

  3. <groupId>org.glassfish.jersey.containers</groupId>

  4. <artifactId>jersey-container-servlet-core</artifactId>

  5. <version>2.0</version>

  6. </dependency>

  7.  
  8. <!--JAXB API-->

  9. <dependency>

  10. <groupId>javax.xml.ws</groupId>

  11. <artifactId>jaxws-api</artifactId>

  12. <version>2.1</version>

  13. </dependency>

  14.  
  15. <!-- Json支持 -->

  16. <dependency>

  17. <groupId>org.codehaus.jackson</groupId>

  18. <artifactId>jackson-core-asl</artifactId>

  19. <version>1.9.12</version>

  20. </dependency>

  21. <dependency>

  22. <groupId>org.codehaus.jackson</groupId>

  23. <artifactId>jackson-mapper-asl</artifactId>

  24. <version>1.9.12</version>

  25. </dependency>

  26. <dependency>

  27. <groupId>org.codehaus.jackson</groupId>

  28. <artifactId>jackson-jaxrs</artifactId>

  29. <version>1.9.12</version>

  30. </dependency>

  31.  

引入Jar文件方式

从Jersey开发包中将以下库复制的WEB-INF下的库目录:

  • 服务器:jersey-server.jar 、jersey-Container-servlet-core.jar、jersey-container-servlet.jar、javax.ws.rs-api-2.0.jar

  • 客户端:jersey-client.jar

  • common:jersey-common.jar

  • json支持:在Jersey2.0中需要使用 Jackson1.9 才能支持json。

Hello World

以下将展示一个Hello World

第一步: 编写一个名为HelloResource的资源,它接受Http Get请求并响应“Hello Jersey”

 
  1. @Path("/hello")

  2. public class HelloResource {

  3. @GET

  4. @Produces(MediaType.TEXT_PLAIN)

  5. public String sayHello() {

  6. return "Hello Jersey";

  7. }

  8. }

第二步: 编写JAX-RS application

 
  1. public class APIApplication extends ResourceConfig {

  2. public APIApplication() {

  3. //加载Resource

  4. register(HelloResource.class);

  5.  
  6. //注册数据转换器

  7. register(JacksonJsonProvider.class);

  8.  
  9. // Logging.

  10. register(LoggingFilter.class);

  11. }

  12. }

  13.  

实际项目中,一个个register(HelloResource.class)这样写会很麻烦,可以整体注册某一个包下面的所有类:

 

 
  1. package com.creditcloud.creditmanager;

  2.  
  3. import com.creditcloud.creditmanager.web.FeatureFilter;

  4. import com.creditcloud.creditmanager.web.AuthenticationFilter;

  5. import org.glassfish.jersey.jackson.JacksonFeature;

  6. import org.glassfish.jersey.media.multipart.MultiPartFeature;

  7. import org.glassfish.jersey.server.ResourceConfig;

  8. import org.glassfish.jersey.server.mvc.jsp.JspMvcFeature;

  9.  
  10. public class CreditManagerApplication extends ResourceConfig {

  11.  
  12. public CreditManagerApplication() {

  13. packages("com.creditcloud.creditmanager.resources");

  14. register(JspMvcFeature.class);

  15. register(AuthenticationFilter.class);

  16. register(FeatureFilter.class);

  17. register(JacksonFeature.class);

  18. register(MultiPartFeature.class);

  19. }

  20. }

 

ResourceConfig类中定义了一个方法:packages(),用于注册整个包下面的Resource类。

第三步: 在web.xml文件中定义servelt调度程序,目的是将所有REST请求发送到Jersey容器。除了声明Jersey Servlet外,还需定义一个初始化参数,指定JAX-RS application。

 
  1. <!--用于定义 RESTful Web Service 接口-->

  2. <servlet>

  3. <servlet-name>JerseyServlet</servlet-name>

  4. <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

  5. <init-param>

  6. <param-name>javax.ws.rs.Application</param-name>

  7. <param-value>cn.com.mink.resource.APIApplication</param-value>

  8. </init-param>

  9.  
  10. <load-on-startup>1</load-on-startup>

  11. </servlet>

  12. <servlet-mapping>

  13. <servlet-name>JerseyServlet</servlet-name>

  14. <url-pattern>/services/*</url-pattern>

  15. </servlet-mapping>

  16.  

第四步: 测试程序

在命令终端中输入以下命令,将会看到“Hello Jersey”。

 

curl http://host:port/services/hello

 

或者在浏览器中输入以下URL,将会看到“Hello Jersey”

 

http://host:port/services/hello

 

使用

资源

Root Resource And Sub-Resource

资源是组成RESTful服务的关键部分,可以使用HTTP方法(如:GET、POST、PUT和DELETE)操作资源。在JAX-RX中,资源通过POJO实现,使用 @Path 注释组成其标识符。资源可以有子资源,父资源是资源集合,子资源是成员资源。

在以下样例代码中,

Resources是"/services" URI组成是集合资源,UserResource是“/services/user” URI组成的成员资源;

 
  1. @Path("/services")

  2. public class Resources {

  3.  
  4. @Path("/user")

  5. public UserResource getUserResource() {

  6. ...

  7. }

  8.  
  9. @Path("/book")

  10. public BookResource getBookResource() {

  11. ...

  12. }

  13. }

  14.  

UserResource是“/user” URI组成的集合资源,getUser是“/user/{username}” URI组成的资源方法

 
  1. @Path("/user")

  2. public class UserResource {

  3. @GET

  4. @Path("{username"})

  5. @Produces("application/json")

  6. public User getUser(@PathParam("username") String userName) {

  7. ...

  8. }

  9. }

  10.  

HTTP Methods

HTTP方法映射到资源的CRUD(创建、读取、更新和删除)操作,基本模式如下:

  • HTTP GET :读取/列出/检索单个或资源集合。
  • HTTP POST :新建资源。
  • HTTP PUT :更新现有资源或资源集合。
  • HTTP DELETE :删除资源或资源集合。

@Produces

@Produces 注释用来指定将要返回给client端的数据标识类型(MIME)。@Produces 可以作为class注释,也可以作为方法注释,方法的 @Produces 注释将会覆盖class的注释。

  • 指定一个MIME类型

     

    @Produces("application/json")

     

  • 指定多个MIME类型

     

    @Produces({"application/json","application/xml"})

     

@Consumes

@Consumes 与 @Produces 相反,用来指定可以接受client发送过来的MIME类型,同样可以用于class或者method,也可以指定多个MIME类型,一般用于 @PUT ,@POST 。

参数(Parameter Annotations)

Parameter Annotations用于获取client发送的数据。本文只介绍常用的注解,更多详见 Jersey用户手册

@PathParam

使用 @PathParam 可以获取URI中指定规则的参数,比如:

 
  1. @GET

  2. @Path("{username"})

  3. @Produces(MediaType.APPLICATION_JSON)

  4. public User getUser(@PathParam("username") String userName) {

  5. ...

  6. }

  7.  

当浏览器请求 http://localhost/user/jack 时,userName值为jack。

@QueryParam

@QueryParam 用于获取GET请求中的查询参数,如:

 
  1. @GET

  2. @Path("/user")

  3. @Produces("text/plain")

  4. public User getUser(@QueryParam("name") String name,

  5. @QueryParam("age") int age) {

  6. ...

  7. }

  8.  

当浏览器请求 http://host:port/user?name=rose&age=25 时,name值为rose,age值为25。如果需要为参数设置默认值,可以使用 @DefaultValue ,如:

 
  1. @GET

  2. @Path("/user")

  3. @Produces("text/plain")

  4. public User getUser(@QueryParam("name") String name,

  5. @DefaultValue("26") @QueryParam("age") int age) {

  6. ...

  7. }

  8.  

当浏览器请求 http://host:port/user?name=rose 时,name值为rose,age值为26。

@FormParam

@FormParam ,顾名思义,从POST请求的表单参数中获取数据。如:

 
  1. @POST

  2. @Consumes("application/x-www-form-urlencoded")

  3. public void post(@FormParam("name") String name) {

  4. // Store the message

  5. }

  6.  

@BeanParam

当请求参数很多时,比如客户端提交一个修改用户的PUT请求,请求中包含很多项用户信息。这时可以用 @BeanParam 。

 
  1. @POST

  2. @Consumes("application/x-www-form-urlencoded")

  3. public void update(@BeanParam User user) {

  4. // Store the user data

  5. }

  6.  

User Bean定义如下:

 
  1. @XmlRootElement(name = "user")

  2. public class User {

  3. @PathParam("userName)

  4. private String userName;

  5.  
  6. @FormParam("name")

  7. private String name;

  8.  
  9. @FormParam("telephone")

  10. private String telephone;

  11.  
  12. @FormParam("email")

  13. private String email;

  14.  
  15. public String getUserName() {

  16. return userName;

  17. }

  18.  
  19. public void setUserName(String userName) {

  20. this.userName = userName;

  21. }

  22. ...

  23. }

  24.  

使用Map

在一个大型的server中,因为参数的多变,参数结构的调整都会因为以上几种方式而遇到问题,这时可以考虑使用 @Context 注释,并获取UriInfo实例,如下:

 
  1. @GET

  2. public String get(@Context UriInfo ui) {

  3. MultivaluedMap<String, String> queryParams = ui.getQueryParameters();

  4. MultivaluedMap<String, String> pathParams = ui.getPathParameters();

  5. }

  6.  

同样还可以通过 @Context 注释获取 ServletConfig 、 ServletContext 、HttpServletRequest 、 HttpServletResponse 和 HttpHeaders 等,如下:

 
  1. @Path("/")

  2. public class Resource {

  3.  
  4. @Context

  5. HttpServletRequest req;

  6.  
  7. @Context

  8. ServletConfig servletConfig;

  9.  
  10. @Context

  11. ServletContext servletContext;

  12.  
  13. @GET

  14. public String get(@Context HttpHeaders hh) {

  15. MultivaluedMap<String, String> headerParams = hh.getRequestHeaders();

  16. Map<String, Cookie> pathParams = hh.getCookies();

  17. }

  18. }

  19.  

Jersey返回Json和Xml

JAX-RS支持使用JAXB(Java API for XML Binding)将JavaBean绑定到XML或JSON,反之亦然。JavaBean必须使用 @XmlRootElement 标注,没有@XmlElement 注释的字段将包含一个名称与之相同的XML元素,如下:

 
  1. @XmlRootElement

  2. public class OptionResult {

  3. @XmlElement(name = "code")

  4. private String result;

  5.  
  6. private String errorMsg;

  7.  
  8. public String getResult() {

  9. return result;

  10. }

  11.  
  12. public void setResult(String result) {

  13. this.result = result;

  14. }

  15.  
  16. public String getErrorMsg() {

  17. return errorMsg;

  18. }

  19.  
  20. public void setErrorMsg(String errorMsg) {

  21. this.errorMsg = errorMsg;

  22. }

  23. }

  24.  

然后在REST服务中使用:

 
  1. @Path("/user")

  2. public class UserResource {

  3. @POST

  4. @Produces("application/json")

  5. public OptionResult create(@BeanParam User user) {

  6. ...

  7. }

  8. }

  9.  

最后,要注册数据转换器,该转换器会自动将JavaBean转换为json数据:

 
  1. public class APIApplication extends ResourceConfig {

  2. public APIApplication() {

  3. //加载Model

  4. register(OptionResult.class);

  5.  
  6. //加载与OptionResult同一个packge的Model

  7. //packages(OptionResult.class.getPackage().getName());

  8.  
  9. //加载Resource

  10. register(UserResource.class);

  11.  
  12. //注册数据转换器

  13. register(JacksonJsonProvider.class);

  14.  
  15. // Logging.

  16. register(LoggingFilter.class);

  17. }

  18. }

  19.  

说明 :返回XML数据的原理相同,仅仅是数据转换器不同,只需要在APIApplication中同时注册XML数据转换器即可,详见 Jersey用户手册

问题总结

Ajax请求(POST、PUT和DELETE)无法将数据提交到Jersey容器

问题阐述

在短信平台的开发中,数据的CRUD全部使用Ajax技术完成,因此必须使用POST、PUT和DELETE请求。此三种请求的content-type均为“application/x-www-form-urlencoded”,使用UTF-8编码会变成“application/x-www-form-urlencoded; UTF-8”。在使用Firefox的tamperdata扩展调试程序的过程中发现,当content-type为“application/x-www-form-urlencoded”时,Jersey容器能够通过 @FormParam 注解获取到提交的数据,而content-type为“application/x-www-form-urlencoded; UTF-8”时便获取不到。

解决方案

最终我使用Java Filter和Jersey RequestFilter解决了问题。首先在Java Filter中使用UTF8将Request中的数据编码,然后在Jersey RequestFilter中将request对象中的content-type修改为“application/x-www-form-urlencoded”。如:

 
  1. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

  2. HttpServletRequest req = (HttpServletRequest)request;

  3. req.setCharacterEncoding("UTF-8");

  4. }

  5.  
  6. public class RequestFilter implements ContainerRequestFilter {

  7. @Override

  8. public void filter(ContainerRequestContext context) throws IOException {

  9. String headerString = context.getHeaderString("content-type");

  10. if (headerString != null) {

  11. //如果content-type以"application/x-www-form-urlencoded"开头,则处理

  12. if (headerString.startsWith(MediaType.APPLICATION_FORM_URLENCODED))

  13. context.getHeaders().putSingle("content-type", MediaType.APPLICATION_FORM_URLENCODED);

  14. }

  15. }

  16. }

最后在web.xml中注册Java Filter(要注册在Jersey容器之前),在APIApplication中注册Jersey RequestFilter,如下:

  1. public class APIApplication extends ResourceConfig {

  2. public APIApplication() {

  3. register(RequestFilter.class);

  4. }

  5. }

  6.  

说明 :在修复此问题后,在Github的Jersey源代码仓库中看到已经有人发现并修复了此问题,在下个Jersey正式版本中应该不会再出现这样的问题,详见 此Discussion

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值