restful里的resource类里的各种接收参数方式

一开始用的是@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(); 
    } 
}  





  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值