JAX-RS入门 五: 自动类型转换

一、默认类型转换规则

 

在上一节中,已经了解了怎么使用那个annotations去提取请求中各种信息,不过得到的信息值默认都是一个string类型。

 

这一节介绍JAX-RS一些内置的自动类型转换及其规则。

 

理论上JAX-RS可以将请求信息转换成任一Java类型,只要该Java类型满足以下条件之一:

  1. 基本类型: int、short、float、double、byte、char 或 boolean 等
  2. 定义了带单个String参数的构造方法
  3. 拥有一个static的valueOf(String)方法,并且这个方法返回这个类型的一个实例
  4. java.util.List<T>、java.util.Set<T>或java.util.SortedSet<T>,其中 T 满足条件2或者3,或者是一个String

例如:

转换成int代码   收藏代码
  1. @GET  
  2. @Path("{id}")  
  3. public String get(@PathParam("id") int id) {...}  

 

转成对象代码   收藏代码
  1. @Path("/myservice")  
  2. public class MyService {  
  3.     @GET  
  4.     @Produces("text/html")  
  5.     public String get(@HeaderParam("Referer") URL referer) {  
  6.         ...  
  7.     }  
  8. }  

 

Valueof()方法代码   收藏代码
  1. public enum Color {  
  2.     BLACK,  
  3.     BLUE,  
  4.     RED,  
  5.     WHITE,  
  6.     SILVER  
  7. }  
  8.   
  9. @GET  
  10. @Path("/{model}/{year}")  
  11. @Produces("image/jpeg")  
  12. public Jpeg getPicture(@PathParam("make") String make,  
  13.     @PathParam("model") String model,  
  14.     @MatrixParam("color") Color color) {  
  15.     ...  
  16. }  

 

转成一个list代码   收藏代码
  1. import java.util.List;  
  2. @Path("/customers")  
  3. public class CustomerResource {  
  4.     @GET  
  5.     @Produces("application/xml")  
  6.     public String getCustomers(  
  7.         @QueryParam("start") int start,  
  8.         @QueryParam("size") int size,  
  9.         @QueryParam("orderBy") List<String> orderBy) {  
  10.         ...  
  11.     }  
  12. }  
  13.   
  14. 输入:GET /customers?orderBy=last&orderBy=first  

 

如果转换失败,则认为client请求出错,返回一个404错误。

 

二、定义缺省值 @DefaultValue

 

通过使用@DefaultValue注释,可以给某个请求参数定义缺省值,当client的请求中未包含此参数,则缺省参数值将被使用,例如:

缺省值代码   收藏代码
  1. @Path("/customers")  
  2. public class CustomerResource {  
  3.     @GET  
  4.     @Produces("application/xml")  
  5.     public String getCustomers(@DefaultValue("0") @QueryParam("start") int start,  
  6.         @DefaultValue("10") @QueryParam("size") int size) {  
  7.         ...  
  8.     }  
  9. }   

如果请求中未提供 start 请求参数,则缺省值0将被使用;如果请求中未包含 size 参数,则缺省值10被使用。

 

三、强制不解码 @Encoded

 

使用@Encoded注释,用来告诉JAX-RS,不需要自动解码,直接使用编码后的请求值,例如:

@encoded代码   收藏代码
  1. @GET  
  2. @Produces("application/xml")  
  3. public String get(@Encoded @QueryParam("something") String str) {...}  

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值