参数(Parameter Annotations)
Parameter Annotations用于获取client发送的数据。本文只介绍常用的注解,更多详见Jersey用户手册
@PathParam
使用@PathParam可以获取URI中指定规则的参数,比如:
@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只是个变量
至于key,value的形式,下面也有
@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。如果需要为参数设置默认值,可以使用@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。
@FormParam
@FormParam,顾名思义,从POST请求的表单参数中获取数据。如:
@POST @Consumes("application/x-www-form-urlencoded") public void post(@FormParam("name") String name) { // Store the message }