一开始用的是@QueryParam来接收参数,后来学习中发现有@PathParam也可以接收,但是用法不一样,摆渡后,自己在这里做了总结:
一、@PathParam (@PathParam ,url中直接在斜杠后面添加参数值)
如,http://localhost:8181/managerinfo/rs/helloworld/user/frank
而resource里的写法是:
@GET
@Path("/user/{condition}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_HTML)
public String getHelloWithPath(@PathParam("condition") String username) {
return "Hello Path UserName " + username;
}
二、 @QueryParam (url中在后面添加【键值对】形式的参数)
如:用ajax请求
$.ajax({
type: 'GET',
contentType: "application/json",
dataType: 'html',
url: 'http://localhost:8181/managerinfo/rs/helloworld/user',
data: {
username:"frank"
},
success:function(data){
alert(data);
}
实际请求地址会是:http://localhost:8181/managerinfo/rs/helloworld/user?username=frank
以下几种写法,转载于:
http://blog.csdn.net/azhegps/article/details/72782704
这里自己没用过,记录下:
三、@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")
publicvoid post(@FormParam("name") String name) {
// Store the message
}
相信使用过html进行post提交的人对表单一定不陌生,可以想象成这就是在模拟html中表单的请求。
五、使用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();
}
}