JAX-RS入门 四: 注入

来源:互联网 发布:淘宝 400 编辑:程序博客网 时间:2024/05/15 12:10

一、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


public class CustomerResource {...@Path("{id}")@GET@Produces("application/xml")public StreamingOutput getCustomer(@PathParam("id") int id) {...}}

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

 

可以同时使用多个PathParam:

@Path("/customers")public class CustomerResource {...@Path("{first}-{last}")@GET@Produces("application/xml")public StreamingOutput getCustomer(@PathParam("first") String firstName,@PathParam("last") String lastName) {...}}
PathParam的范围:总是引用最接近的PathParam的值,例如:

@Path("/customers/{id}")public class CustomerResource {@Path("/address/{id}")@Produces("text/plain")@GETpublic String getAddress(@PathParam("id") String addressId) {...}}

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

 

注入PathSegment

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

package javax.ws.rs.core;public interface PathSegment {String getPath();   //具体的URI的path片段值,去除了所有的matrix参数MultivaluedMap<String, String> getMatrixParameters();  //该path片段拥有的所有的matrix值}
然后如下使用:
@Path("/cars/{make}")public class CarResource {@GET@Path("/{model}/{year}")@Produces("image/jpeg")public Jpeg getPicture(@PathParam("make") String make,@PathParam("model") PathSegment car,@PathParam("year") String year) {String carColor = car.getMatrixParameters().getFirst("color");...}}
例如:GET /cars/mercedes/e55;color=black/2006。则 make是mercedes;model是e55;year是2006;color是black。

注入多个PathSegment

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

@Path("/cars/{make}")public class CarResource {@GET@Path("/{model : .+}/year/{year}")@Produces("image/jpeg")public Jpeg getPicture(@PathParam("make") String make,@PathParam("model") List<PathSegment> car,@PathParam("year") String year) {}}

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

 

用代码获取URI的信息

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

public interface UriInfo {public String getPath();  //返回匹配的相对uri路径public String getPath(boolean decode); //返回解码后的相对uri路径public List<PathSegment> getPathSegments();  //返回path片段public List<PathSegment> getPathSegments(boolean decode); //返回解码后的path片段public MultivaluedMap<String, String> getPathParameters(); //返回PathParam表public MultivaluedMap<String, String> getPathParameters(boolean decode); //同上...}
要获取UriInfo对象,就需要用到@javax.ws.rs.core.Context注释了。例如:

@Path("/cars/{make}")public class CarResource {@GET@Path("/{model}/{year}")@Produces("image/jpeg")public Jpeg getPicture(@Context UriInfo info) {String make = info.getPathParameters().getFirst("make");PathSegment model = info.getPathSegments().get(1);String color = model.getMatrixParameters().getFirst("color");...}}

三、MatrixParam

 

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

@Path("/{make}")public class CarResource {@GET@Path("/{model}/{year}")@Produces("image/jpeg")public Jpeg getPicture(@PathParam("make") String make,@PathParam("model") String model,@MatrixParam("color") String color) {...}}

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

 

四、@QueryParam

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

@Path("/customers")public class CustomerResource {@GET@Produces("application/xml")public String getCustomers(@QueryParam("start") int start,@QueryParam("size") int size) {...}}

这里start为0,size为10.

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

@Path("/customers")public class CustomerResource {@GET@Produces("application/xml")public String getCustomers(@Context UriInfo info) {String start = info.getQueryParameters().getFirst("start");String size = info.getQueryParameters().getFirst("size");...}}

五、@FormParam

 

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

<FORM action="http://example.com/customers" method="post"><P>First name: <INPUT type="text" name="firstname"><BR>Last name: <INPUT type="text" name="lastname"><BR><INPUT type="submit" value="Send"></P></FORM>
取值:

@Path("/customers")public class CustomerResource {@POSTpublic void createCustomer(@FormParam("firstname") String first,@FormParam("lastname") String last) {...}}

六、HeaderParam

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

@Path("/myservice")public class MyService {@GET@Produces("text/html")public String get(@HeaderParam("Referer") String referer) {...}}
如果想提取所有的header值,那就需要用到javax.ws.rs.core.HttpHeaders接口了:
public interface HttpHeaders {public List<String> getRequestHeader(String name);public MultivaluedMap<String, String> getRequestHeaders();...}
例如方法同上面的PathSegment,也是用context去获取,例如:
@Path("/myservice")public class MyService {@GET@Produces("text/html")public String get(@Context HttpHeaders headers) {String referer = headers.getRequestHeader("Referer").get(0);for (String header : headers.getRequestHeaders().keySet()){System.out.println("This header was set: " + header);}...}}

七、@CookieParam

提取cookie信息,例如:

@Path("/myservice")public class MyService {@GET@Produces("text/html")public String get(@CookieParam("customerId") int custId) {...}}
这里注入了的是一个cookie的值,如果想取得更多的信息,而不仅仅是基本值,则可以直接注入javax.ws.rs.core.Cookie对象,例如:

@Path("/myservice")public class MyService {@GET@Produces("text/html")public String get(@CookieParam("customerId") Cookie custId) {...}} 

















0 0