1:概念与常用注解
JAX-RS是一套用java实现REST服务的规范,提供了一些标注将一个资源类,一个POJOJava类,封装为Web资源。标注包括:
- @Path,标注资源类或方法的相对路径
- @GET,@PUT,@POST,@DELETE,标注方法是用的HTTP请求的类型
- @Produces,标注返回的MIME媒体类型
- @Consumes,标注可接受请求的MIME媒体类型
- @PathParam,@QueryParam,@HeaderParam,@CookieParam,@MatrixParam,@FormParam,分别标注方法的参数来自于HTTP请求的不同位置,例如@PathParam来自于URL的路径,@QueryParam来自于URL的查询参数,@HeaderParam来自于HTTP请求的头信息,@CookieParam来自于HTTP请求的Cookie。
2:JAX-RS的几种实现
目前JAX-RS的实现包括:
3:常用注解范例
(1)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) {
-
...
-
}
-
}
(2)@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");
-
...
-
}
-
}
(3)@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 {
-
@POST
-
public void createCustomer(@FormParam("firstname") String first,
-
@FormParam("lastname") String last) {
-
...
-
}
-
}
(4)HeaderParam
很直接,用来提取HTTP Header值的。例如:
-
@Path("/myservice")
-
public class MyService {
-
@GET
-
@Produces("text/html")
-
public String get(@HeaderParam("Referer") String referer) {
-
...
-
}
-
}
(5)@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) {
-
...
-
}
-
}
JAX-RS规范基础
原文:http://blog.csdn.net/u013628152/article/details/42655485