Jersey 写restful接口时QueryParam ,FormParam 等的区别

今天用jersey写接口,发现有一个post方法中没有得到参数,查了半天发现自己一不小心将@formparam写成了@queryparam,真是一个悲伤的故事。在这里把几个参数类型整理了一下放出来。 

1. 
@PathParam 
使用@PathParam可以获取URI中指定规则的参数,举个例子: 
类中@Path("/user") 
@GET 
@Path("{username"}) 
@Produces(MediaType.APPLICATION_JSON) 
public User getUser(@PathParam("username") String userName) { 
    ... 

当浏览器请求http://localhost/user/jack时,userName值为jack。 
注意,这里的username并不是说Key是username, value是jack而是说/usr/后面跟着的东西就是username,这里username只是个变量 


2. 
@QueryParam 
@QueryParam用于获取GET请求中的查询参数,如: 
@GET 
@Path("/user") 
@Produces("text/plain") 
public User getUser(@QueryParam("name") String name, 
                    @QueryParam("age") int age) { 
    ... 

当浏览器请求http://host:port/user?name=rose&age=25时,name值为rose,age值为25。如果需要为参数设置默认值,可以使用 

3. 
@DefaultValue,如: 
@GET 
@Path("/user") 
@Produces("text/plain") 
public User getUser(@QueryParam("name") String name, 
                    @DefaultValue("26") @QueryParam("age") int age) { 
    ... 

当浏览器请求http://host:port/user?name=rose时,name值为rose,age值为26。 

4. 
@FormParam 
@FormParam,顾名思义,从POST请求的表单参数中获取数据。如: 
@POST 
@Consumes("application/x-www-form-urlencoded") 
publicvoid post(@FormParam("name") String name) { 
    // Store the message 

相信使用过html进行post提交的人对表单一定不陌生,可以想象成这就是在模拟html中表单的请求。 
5. 
使用Map 
在一个大型的server中,因为参数的多变,参数结构的调整都会因为以上几种方式而遇到问题,这时可以考虑使用@Context 注释,并获取UriInfo实例,如下: 
@GET 
public String get(@Context UriInfo ui) { 
    MultivaluedMap<String, String> queryParams = ui.getQueryParameters(); 
    MultivaluedMap<String, String> pathParams = ui.getPathParameters(); 

我觉得,可以认为map是上面几种情况的超集,因为它能够替代以上任意一种。map就是context 
同样还可以通过@Context 注释获取ServletConfig、ServletContext、HttpServletRequest、HttpServletResponse和HttpHeaders等,如下: 

@Path("/") 
publicclass Resource { 

    @Context 
    HttpServletRequest req; 

    @Context 
    ServletConfig servletConfig; 

    @Context 
    ServletContext servletContext; 

    @GET 
    public String get(@Context HttpHeaders hh) { 
        MultivaluedMap<String, String> headerParams = hh.getRequestHeaders(); 
        Map<String, Cookie> pathParams = hh.getCookies(); 
    } 


原文地址:https://www.cnblogs.com/jpfss/p/8466886.html