今天用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();
}
}