Jersey1.8在spring环境下的实现 包括实例代码

最近项目里面要使用rest或者webservice来实现一些对外的接口。

 下载地址: http://download.java.net/maven/2/com/sun/jersey/contribs/jersey-spring/

或官网

https://maven.java.net/content/repositories/releases/com/sun/jersey/contribs/jersey-spring/1.9/

所需包:

jersey-client-1.8.jar

jersey-core-1.8.jar

jersey-json-1.8.jar

jersey-server-1.8.jar

jersey-spring-1.8.jar

查了很多资料,最后选择了Restlet、Apache CXF、Jersey。

Restlet是抛弃了servlet api,自身实现了一些api,最关键的是没有提供spring的集成。

CXF很好,很强大,但是觉得它的json不爽,总是要先绕道jaxb。

 

Jersey是sun推出来的,很轻量、很环保、支持JAX-RS规范,据说要整合到jdk中去的。

 

最终权衡之下选择了Jersey。

 

Jersey的官方网站http://jersey.java.net/,相关文件可以在里面下载的。

 

1.资料,在线文档。

http://jersey.java.net/nonav/documentation/latest/getting-started.html

可以通过maven进行环境的搭建。

我没有使用maven的习惯,最后手工下载的,下载了好久,基本把所有插件都下载到了。

这边附近只能上传10M,上传一张相关的lib截图,需要的另外附上。

 

2.与spring集成

在classpath里里加入jersey-spring.jar,web.xml里面划一个url如/restapi/* 归Jersey的SpringServlet管即可。 然后SpringServlet就会在Spring的Context里查找支持某个具体path的Bean来出来处理请求。

 

Xml代码   收藏代码
  1. <!-- Jersey 配置 -->  
  2. <servlet>  
  3.   <servlet-name>JerseyServlet</servlet-name>  
  4.   <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>  
  5.   <init-param>  
  6.     <param-name>com.sun.jersey.config.property.packages</param-name>  
  7.       <!-- 系统启动时扫描的包的路径-->  
  8.     <param-value>com.tianque.locationtalk.api</param-value>  
  9.     <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>  
  10.     <param-value>true</param-value>  
  11.       
  12.   </init-param>     
  13. </servlet>  

 

3.参数支持和接口

@PathParam用来表示Restful风格下在URL中的id等标识。

@QueryParameter可以转换任何有以String为参数的构造函数的类,还可以设定defaultValue, 当参数为空时会自动抛异常

@POST+ @Consumes 以POST方式传递XML或JSON编码的Java对象

@Context UriInfo,@Context HttpHeaders, @Context HttpServletRequest 获取灵活的,不固定的参数. 可以从原版HttpServletRequest中获取,也可以用封装好的更方便的UriInfo和HttpHeaders.

 

4.使用Jackson处理JSON

 在classpath里加入jersey-json.jar后,在服务端,web.xml里SpringServlet的定义要加入

 		<init-param>
			<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
			<param-value>true</param-value>
		</init-param>
 
5.要生成rest的service类
 
pojo对象,必须加入 @XmlRootElement,用于标识对象转化成xml或者json
Java代码   收藏代码
  1. package com.xxx.locationtalk.api;  
  2.   
  3. import javax.xml.bind.annotation.XmlRootElement;  
  4.   
  5.   
  6. @XmlRootElement  
  7. public  class  User {  
  8.   
  9.         public Long userId;  
  10.         public String userName;  
  11.         public String nickName;  
  12.           
  13.         public User(){  
  14.               
  15.         }  
  16.         public User(Long userId,String userName,String nickName){  
  17.             this.userId =userId;  
  18.             this.userName=userName;  
  19.             this.nickName=nickName;  
  20.         }  
  21.     }  
  
具体映射出去的service类,其中调用了某个spring的service去读取数据库,各个不同的url实现了xml的对象输出,json对象的输出,以及list对象的输出,以及一些赋值操作和json对象赋值操作。
Java代码   收藏代码
  1. package com.xxx.locationtalk.api;  
  2.   
  3.   
  4. import java.io.UnsupportedEncodingException;  
  5. import java.net.URLEncoder;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8.   
  9. import javax.ws.rs.GET;  
  10. import javax.ws.rs.PUT;  
  11. import javax.ws.rs.Path;  
  12. import javax.ws.rs.Produces;  
  13. import javax.ws.rs.QueryParam;  
  14. import javax.ws.rs.core.MediaType;  
  15.   
  16. import org.springframework.beans.factory.annotation.Autowired;  
  17. import org.springframework.context.annotation.Scope;  
  18. import org.springframework.stereotype.Component;  
  19.   
  20. import com.xxx.locationtalk.domain.MobileNumber;  
  21. import com.xxx.locationtalk.service.MobileNumberService;  
  22.   
  23. @Component  
  24. @Scope("request")  
  25. @Path("/bookapi")  
  26. public class BookService {  
  27.     @Autowired  
  28.     private MobileNumberService mobileNumberService;  
  29.       
  30.     public MobileNumberService getMobileNumberService() {  
  31.         return mobileNumberService;  
  32.     }  
  33.   
  34.     public void setMobileNumberService(MobileNumberService mobileNumberService) {  
  35.         this.mobileNumberService = mobileNumberService;  
  36.     }  
  37.     //外部传过来的参数  
  38.     @QueryParam("id") String userId;  
  39.   
  40.     @GET  
  41.     @Produces(MediaType.TEXT_PLAIN)  
  42.     public String helloWorld() {  
  43.         String ret = "Hello World!";  
  44.         return ret;  
  45.     }  
  46.       
  47.     // 子路径  
  48.     @Path("getUsers")     
  49.     @GET  
  50.     @Produces( {MediaType.APPLICATION_XML })  
  51.     public List<User>  getUsers() {  
  52.         List<User> users = new ArrayList<User>();  
  53.         for (long i = 1; i < 5; i++) {  
  54.             User user = new User();  
  55.             user.userId=(i);  
  56.             user.userName=("yuhan" + i);  
  57.             user.nickName=("supben" + i);  
  58.             users.add(user);  
  59.         }    
  60.         return users;  
  61.     }    
  62.       
  63.     // 子路径  
  64.     @Path("getUserById")  
  65.     @GET  
  66.     @Produces( {MediaType.APPLICATION_JSON })  
  67.     public User getUsersById(){  
  68.         User user = new User();  
  69. //使用spring的类读取数据库信息,随便赋值  
  70.         MobileNumber object=mobileNumberService.getMobileNumberById(Long.valueOf(userId));  
  71.         user.userId=object.getId();  
  72.         user.userName=object.getUsersName();  
  73.         user.nickName=object.getMobileNumber();  
  74.         return user;  
  75.     }  
  76.     @Path("getUserXmlById")  
  77.     @GET  
  78.     @Produces( {MediaType.APPLICATION_XML })  
  79.     public User getUsersByIdForXML(){  
  80.         User user = new User();  
  81.         MobileNumber object=mobileNumberService.getMobileNumberById(Long.valueOf(userId));  
  82.         user.userId=object.getId();  
  83.         user.userName=object.getUsersName();  
  84.         user.nickName=object.getMobileNumber();  
  85.         return user;  
  86.     }  
  87.     @Path("setUser")  
  88.     @PUT  
  89.     @Produces( {MediaType.APPLICATION_JSON })  
  90.     public User setUser(User user){  
  91.         if(user==null){  
  92.             System.out.println("数值为空!!");  
  93.             user.userId=(13486197987L);  
  94.             user.userName=("yuhan");  
  95.             user.nickName=("supben");  
  96.         }else{  
  97.             System.out.println("user.userId="+user.userId);  
  98.             System.out.println("user.userName="+user.userName);  
  99.             System.out.println("user.nickName="+user.nickName);  
  100.             user.userId=(user.userId);  
  101.             user.userName=(user.userName);  
  102.             user.nickName=(user.nickName);        
  103.         }  
  104.   
  105.         return user;  
  106.     }  
  107.     // 子路径  
  108.     @Path("getUserByXML")  
  109.     @GET  
  110.     @Produces( {MediaType.APPLICATION_XML })  
  111.     public User getUserByIdWithXML() throws UnsupportedEncodingException{  
  112.         User user = new User();  
  113.         user.userId=(10000L);  
  114.         user.userName=URLEncoder.encode(("哈哈"), "utf-8");  
  115.         user.nickName=URLEncoder.encode(("老色狼"), "utf-8");  
  116.         return user;  
  117.     }    
  118.       
  119.   
  120. }  
 
然后通过浏览器发布出去,在浏览器中即可通过
http://localhost:8080/api/bookapi/getUserByXML获得一个xml格式的对象
http://localhost:8080/api/bookapi/setUser可以对一个user对象进行赋值
http://localhost:8080/api/bookapi/getUserXmlById可以传入一个id参数,获得一个xml格式的对象
6.client的demo演示
Java代码   收藏代码
  1. package com.xxx.locationtalk.api;  
  2.   
  3. import java.io.UnsupportedEncodingException;  
  4.   
  5. import javax.ws.rs.core.MediaType;  
  6. import javax.ws.rs.core.MultivaluedMap;  
  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. import com.sun.jersey.api.json.JSONConfiguration;  
  14. import com.sun.jersey.core.util.MultivaluedMapImpl;  
  15. import com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider;  
  16.   
  17. public class ClientDemo{  
  18.     public static void main(String[] args) throws UnsupportedEncodingException{  
  19.         ClientConfig clientConfig = new DefaultClientConfig();  
  20.         clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);  
  21.           
  22.   
  23.         Client c = Client.create(clientConfig);  
  24.         String url = "http://localhost:8080/api/bookapi";  
  25.         WebResource r = c.resource(url);  
  26.           
  27.         User user = new User();  
  28.         user.userId=1000L;  
  29.         user.userName="江江123";  
  30.         user.nickName="老色狼";  
  31.           
  32.         System.out.println("状态码="+r.path("setUser").accept(new String[] {MediaType.APPLICATION_JSON}).  
  33.         entity(user, MediaType.APPLICATION_JSON).put(ClientResponse.class).getStatus());  
  34.   
  35.           
  36.         MultivaluedMap<String, String> param = new MultivaluedMapImpl();    
  37.         param.add("userId""10000");    
  38.         param.add("userName""脏话");  
  39.         param.add("nickName""脏话色狼");  
  40.           
  41.         System.out.println(r.queryParams(param)    
  42.                 .type(MediaType.APPLICATION_JSON).post(String.class));  
  43.           
  44.   
  45.     }  
  46. }  
 这个client演示了俩种rest的实现方法
  • 输入URL Query参数 client.path("/xxx").queryParam("name", name)
  • 输入JSON编码的对象 client.path("/xxx").entity(user, MediaType.APPLICATION_JSON)

 

 

附件包括

一张相关的jersey用到的所有lib截图

官方下载的最新jersey说明文档

官方下载的jersey1.8.zip,包括核心的lib以及doc

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值