JAX-RS之queryparam、PathParam、DefaultValue、FormParam、Context、RestController等

这几天做东西接触了JAX-RS的东西,没有系统的从开始就学,只是单纯去复制粘贴的用,主要用到了几个Annotations变量,具体如下:

queryparam、PathParam、FormParam、Context、RestController。下面就分别解释下他们的用法:

1.@queryparam

Path("/users")
public class UserService {
 
    @GET
    @Path("/query")
    public Response getUsers(
        @QueryParam("from") int from,
        @QueryParam("to") int to,
        @QueryParam("orderBy") List<String> orderBy) {
 
        return Response
           .status(200)
           .entity("getUsers is called, from : " + from + ", to : " + to
            + ", orderBy" + orderBy.toString()).build();
 
    }
 
}

这里,在url中输入"/users/query/from=1&to=100&orderBy=name&orderBy=age",则输出一下结果:

getUsers is called, from : 1, to : 100, orderBy[name, age] 

这里,也可以以动态方式获得,如下:

@Path("/users")
public class UserService {
 
    @GET
    @Path("/query")
    public Response getUsers(@Context UriInfo info) {
 
        String from = info.getQueryParameters().getFirst("from");
        String to = info.getQueryParameters().getFirst("to");
        List<String> orderBy = info.getQueryParameters().get("orderBy");
 
        return Response
           .status(200)
           .entity("getUsers is called, from : " + from + ", to : " + to
            + ", orderBy" + orderBy.toString()).build();
 
    }
 

URL:users/query?from=100&to=200&orderBy=age&orderBy=name 
输出为: 
getUsers is called, from : 100, to : 200, orderBy[age, name] 
注意这里把orderby后的两个参数读入为LIST处理了. 

2.@pathParam

与@queryParam类似,但是,queryparam在url中是用键值对来传递,而在pathParam中是只出现值而不出现参数,

url如是:"/users/2011/20/10",例如:

@GET
    @Path("{year}/{month}/{day}")
    public Response getUserHistory(
            @PathParam("year") int year,
            @PathParam("month") int month, 
            @PathParam("day") int day) {
 
       String date = year + "/" + month + "/" + day;
 
       return Response.status(200)
        .entity("getUserHistory is called, year/month/day : " + date)
        .build();
 
    }

这里通过上面的url将输出:

  getUserHistory is called, year/month/day : 2011/20/10

可以用多个param,并且若path中有相同参数名,则采用最接近的参数名所对应的值,如

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

如:customers/123/address/456 , 则 addressId 的值为456.


3.@DefaultValue

@Path("/users")
public class UserService {
 
    @GET
    @Path("/query")
    public Response getUsers(
        @DefaultValue("1000") @QueryParam("from") int from,
        @DefaultValue("999")@QueryParam("to") int to,
        @DefaultValue("name") @QueryParam("orderBy") List<String> orderBy) {
 
        return Response
           .status(200)
           .entity("getUsers is called, from : " + from + ", to : " + to
            + ", orderBy" + orderBy.toString()).build();
 
    }

输入url为:/users/query

输出为:

getUsers is called, from : 1000, to : 999, orderBy[name]

4.@FormParam

FormParam用于提取post请求中的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) {
            ...
    }
}

5.@context

当jax-rs服务基于servlet发布的时候 ,还可以通过@Context注入servlet中的ServletConfig , ServletContext ,HttpServletRequest , HttpServletResponse

然后REST就可以通过sessionid来保持住用户状态。举例如下:

@Path("UserContext")
public class UserContext {
    
    @Context UriInfo uriInfo;
    @Context HttpHeaders httpHeaders;
    @Context SecurityContext sc;
    @Context Request req;
    @Context Response resp;
    @Context HttpServletResponse response;
    @Context HttpServletRequest request;
    
    @GET
    public String hi(@QueryParam("name") String yourName ){
        if(yourName!=null)
            request.getSession().setAttribute("name", yourName);
        
        String username = (String) request.getSession().getAttribute("name");
        if(username!=null){
            System.out.println(request.getSession().getId() + ":" + username);
        }
        else{
            System.out.println(request.getSession().getId() + "没有用户");
        }
        return null;
    }
}
<!--在web.xml加入-->
  <servlet>
      <display-name>JAX-RS REST Servlet</display-name>
      <servlet-name>JAX-RS REST Servlet</servlet-name>
      <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
      <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
      <servlet-name>JAX-RS REST Servlet</servlet-name>
      <url-pattern>/services/*</url-pattern>
  </servlet-mapping>

在url中输入:”/rest/services/UserContext“则输出:

A46756539D2E39CC2CFFCB3FE1C99E70没有用户  

 

若在url中输入:http://localhost:8080/rest/services/UserContext?name=hello

则输出:

A46756539D2E39CC2CFFCB3FE1C99E70:hello  

 

6.@RestController

它继承自@Controller注解,我们可以开发REST服务的时候不需要使用@Controller而专门的@RestController

定义如下:

@Target(value=TYPE)
 @Retention(value=RUNTIME)
 @Documented
 @Controller
 @ResponseBody
public @interface RestController

7.还有cookieparam和headerparam等,此处没怎么接触,就先不学习了。

原文地址:https://www.cnblogs.com/Pillar/p/4361886.html