JAX-RS入门 四: 注入

一、Annotations

  • @javax.ws.rs.PathParam: 从URI模板参数中提取数据
  • @javax.ws.rs.MatrixParam:从URI中提取Matrix参数
  • @javax.ws.rs.QueryParam:从URI中提取查询参数
  • @javax.ws.rs.FormParam:提取Post Form参数
  • @javax.ws.rs.HeaderParam:提取HTTP请求头信息
  • @javax.ws.rs.CookieParam:提取客户设置的cookie的信息
  • @javax.ws.rs.core.Context:通用的注入annotation,允许注入各种帮助或者信息对象

通常这些注释用在服务方法上,当JAX-RS收到一个请求会,就会去查找相应的服务方法,然后把方法需要的信息注入。

如果是 “每个请求一个对象”的模式,你可以将这些annotation用在变量、set方法或者是构造方法上;如果是单态模式,则不允许将这些annotation用在变量、或者set方法上,因为对像会同时处理多个请求,如果将这些值用在变量或者set方法上,则多个请求会彼此冲突,陷入错误。

二、PathParam

Java代码 复制代码  收藏代码
  1. public class CustomerResource {   
  2.     ...   
  3.     @Path("{id}")   
  4.     @GET  
  5.     @Produces("application/xml")   
  6.     public StreamingOutput getCustomer(@PathParam("id"int id) {   
  7.         ...   
  8.     }   
  9. }   

此处,取得{id}的值,并试图转换成一个int型的值。

可以同时使用多个PathParam:

Java代码 复制代码  收藏代码
  1. @Path("/customers")   
  2. public class CustomerResource {   
  3.     ...   
  4.     @Path("{first}-{last}")   
  5.     @GET  
  6.     @Produces("application/xml")   
  7.     public StreamingOutput getCustomer(@PathParam("first") String firstName,   
  8.         @PathParam("last") String lastName) {   
  9.         ...   
  10.     }   
  11. }  

PathParam的范围:总是引用最接近的PathParam的值,例如:

Java代码 复制代码  收藏代码
  1. @Path("/customers/{id}")   
  2. public class CustomerResource {   
  3.     @Path("/address/{id}")   
  4.     @Produces("text/plain")   
  5.     @GET  
  6.     public String getAddress(@PathParam("id") String addressId) {...}   
  7. }  

例如HTTP请求为:GET /customers/123/address/456 , 则 addressId 的值为456.

注入PathSegment

PathParam除了可以注入Path参数,也可以注入一个javax.ws.rs.core.PathSegment实便;PathSegment是一个特定Path片段的抽象,如下:

Java代码 复制代码  收藏代码
  1. package javax.ws.rs.core;   
  2. public interface PathSegment {   
  3.     String getPath();   //具体的URI的path片段值,去除了所有的matrix参数   
  4.     MultivaluedMap<String, String> getMatrixParameters();  //该path片段拥有的所有的matrix值   
  5. }  

然后如下使用:

Java代码 复制代码  收藏代码
  1. @Path("/cars/{make}")   
  2. public class CarResource {   
  3.     @GET  
  4.     @Path("/{model}/{year}")   
  5.     @Produces("image/jpeg")   
  6.     public Jpeg getPicture(@PathParam("make") String make,   
  7.     @PathParam("model") PathSegment car,   
  8.     @PathParam("year") String year) {   
  9.         String carColor = car.getMatrixParameters().getFirst("color");   
  10.         ...   
  11.     }   
  12. }  

例如:GET /cars/mercedes/e55;color=black/2006。则 make是mercedes;model是e55;year是2006;color是black。

  

注入多个PathSegment

如果对对应有Path含有多个path片段,则需要注入多个PathSegments类,例如:

Java代码 复制代码  收藏代码
  1. @Path("/cars/{make}")   
  2. public class CarResource {   
  3.     @GET  
  4.     @Path("/{model : .+}/year/{year}")   
  5.     @Produces("image/jpeg")   
  6.     public Jpeg getPicture(@PathParam("make") String make,   
  7.         @PathParam("model") List<PathSegment> car,   
  8.         @PathParam("year") String year) {   
  9.     }   
  10. }  

其中请求可能是:GET /cars/mercedes/e55/amg/year/2006。这里model对应的path片段为:/e55/amg。所以car变量中含有两个PathSegment对象。

用代码获取URI的信息

有时候可能想通过程序的方式获取URI中的信息,而不使用PathParam注释。这里我们需要通过接口javax.ws.rs.core.UriInfo接口去获取这些信息,UriInfo接口定义如下:

Java代码 复制代码  收藏代码
  1. public interface UriInfo {   
  2.     public String getPath();  //返回匹配的相对uri路径   
  3.     public String getPath(boolean decode); //返回解码后的相对uri路径   
  4.     public List<PathSegment> getPathSegments();  //返回path片段   
  5.     public List<PathSegment> getPathSegments(boolean decode); //返回解码后的path片段   
  6.     public MultivaluedMap<String, String> getPathParameters(); //返回PathParam表   
  7.     public MultivaluedMap<String, String> getPathParameters(boolean decode); //同上   
  8.     ...   
  9. }  

要获取UriInfo对象,就需要用到@javax.ws.rs.core.Context注释了。例如:

Java代码 复制代码  收藏代码
  1. @Path("/cars/{make}")   
  2. public class CarResource {   
  3.     @GET  
  4.     @Path("/{model}/{year}")   
  5.     @Produces("image/jpeg")   
  6.     public Jpeg getPicture(@Context UriInfo info) {   
  7.         String make = info.getPathParameters().getFirst("make");   
  8.         PathSegment model = info.getPathSegments().get(1);   
  9.         String color = model.getMatrixParameters().getFirst("color");   
  10.         ...   
  11.     }   
  12. }  

三、MatrixParam

除了上面介绍的使用PathSegment去获取MatrixParam值外,我们也可以直接使用@MatrixParam去获取值,这样来得更直接、简洁,例如:

Java代码 复制代码  收藏代码
  1. @Path("/{make}")   
  2. public class CarResource {   
  3.     @GET  
  4.     @Path("/{model}/{year}")   
  5.     @Produces("image/jpeg")   
  6.     public Jpeg getPicture(@PathParam("make") String make,   
  7.         @PathParam("model") String model,   
  8.         @MatrixParam("color") String color) {   
  9.         ...   
  10.     }   
  11. }  

不过如果Path中含有多个同名的MatrixParam,则还是需要使用PathSegment来获取,例如:GET /mercedes/e55;color=black/2006/interior;color=tan

四、@QueryParam

很显然,QueryParam用来获取查询参数,对于 GET /customers?start=0&size=10 ,例如:

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

这里start为0,size为10.

同上面的PathParam,也可以用UriInfo去获取QueryParam,例如:

Java代码 复制代码  收藏代码
  1. @Path("/customers")   
  2. public class CustomerResource {   
  3.     @GET  
  4.     @Produces("application/xml")   
  5.     public String getCustomers(@Context UriInfo info) {   
  6.         String start = info.getQueryParameters().getFirst("start");   
  7.         String size = info.getQueryParameters().getFirst("size");   
  8.         ...   
  9.     }   
  10. }  

五、@FormParam

很自然,FormParam用于提取POST请求中的Form参数,其中Content-Type被假设为application/x-www-formurlencoded。例如有以下Form请求

Html代码 复制代码  收藏代码
  1. <FORM action="http://example.com/customers" method="post">  
  2.     <P>  
  3.         First name: <INPUT type="text" name="firstname"><BR>  
  4.         Last name: <INPUT type="text" name="lastname"><BR>  
  5.         <INPUT type="submit" value="Send">  
  6.     </P>  
  7. </FORM>  

可以如下取值:

Java代码 复制代码  收藏代码
  1. @Path("/customers")   
  2. public class CustomerResource {   
  3.     @POST  
  4.     public void createCustomer(@FormParam("firstname") String first,   
  5.         @FormParam("lastname") String last) {   
  6.             ...   
  7.     }   
  8. }  

六、HeaderParam

很直接,用来提取HTTP Header值的。例如:

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

如果想提取所有的header值,那就需要用到javax.ws.rs.core.HttpHeaders接口了:

Java代码 复制代码  收藏代码
  1. public interface HttpHeaders {   
  2. public List<String> getRequestHeader(String name);   
  3.     public MultivaluedMap<String, String> getRequestHeaders();   
  4.     ...   
  5. }  

例如方法同上面的PathSegment,也是用context去获取,例如:

Java代码 复制代码  收藏代码
  1. @Path("/myservice")   
  2. public class MyService {   
  3.     @GET  
  4.     @Produces("text/html")   
  5.     public String get(@Context HttpHeaders headers) {   
  6.         String referer = headers.getRequestHeader("Referer").get(0);   
  7.         for (String header : headers.getRequestHeaders().keySet())   
  8.         {   
  9.             System.out.println("This header was set: " + header);   
  10.         }   
  11.         ...   
  12.     }   
  13. }  

七、@CookieParam

提取cookie信息,例如:

Java代码 复制代码  收藏代码
  1. @Path("/myservice")   
  2. public class MyService {   
  3.     @GET  
  4.     @Produces("text/html")   
  5.     public String get(@CookieParam("customerId"int custId) {   
  6.         ...   
  7.     }   
  8. }  

这里注入了的是一个cookie的值,如果想取得更多的信息,而不公公是基本值,则可以直接注入javax.ws.rs.core.Cookie对象,例如:

Java代码 复制代码  收藏代码
  1. @Path("/myservice")   
  2. public class MyService {   
  3.     @GET  
  4.     @Produces("text/html")   
  5.     public String get(@CookieParam("customerId") Cookie custId) {   
  6.         ...   
  7.     }   
  8. }   

Cookie类具有一些其他的方法可以用来获取更多信息,例如:

Java代码 复制代码  收藏代码
  1. package javax.ws.rs.core;   
  2. public class Cookie   
  3. {   
  4.     public String getName() {...}   
  5.     public String getValue() {...}   
  6.     public int getVersion() {...}   
  7.     public String getDomain() {...}   
  8.     public String getPath() {...}   
  9.     ...   
  10. }  

也可以用javax.ws.rs.core.HttpHeaders获取所有的cookie:

Java代码 复制代码  收藏代码
  1. public interface HttpHeaders {   
  2.     ...   
  3.     public Map<String, Cookie> getCookies();   
  4. }  
Java代码 复制代码  收藏代码
  1. @Path("/myservice")   
  2. public class MyService {   
  3.     @GET  
  4.     @Produces("text/html")   
  5.     public String get(@Context HttpHeaders headers) {   
  6.         for (String name : headers.getCookies().keySet())   
  7.         {   
  8.             Cookie cookie = headers.getCookies().get(name);   
  9.             System.out.println("Cookie: " +   
  10.                 name + "=" + cookie.getValue());   
  11.         }   
  12.         ...   
  13.     }   
  14. }  

猜你喜欢

转载自zzc1684.iteye.com/blog/1674374