PathVariable 和 RequestParam的区别

PathVariable

映射 URL 绑定的占位符
通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable(“xxx“) 绑定到操作方法的入参中。

@RequestMapping("/testPathVariable/{id}")   
 public String testPathVariable(@PathVariable("id") Integer id)    {   
  System.out.println("testPathVariable:"+id);        
  return SUCCESS;    
  }
  

RequestParam

用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容。提交方式为get或post。(Http协议中,如果不指定Content-Type,则默认传递的参数就是application/x-www-form-urlencoded类型)
RequestParam实质是将Request.getParameter() 中的Key-Value参数Map利用Spring的转化机制ConversionService配置,转化成参数接收对象或字段。
get方式中query String的值,和post方式中body data的值都会被Servlet接受到并转化到Request.getParameter()参数集中,所以@RequestParam可以获取的到。

@RequestMapping(value="/requestParamTest", method = RequestMethod.GET)
    public String requestParamTest(@RequestParam(value="username") String userName, @RequestParam(value="usernick") String userNick){
        System.out.println("requestParam Test");
        System.out.println("username: " + userName);
        System.out.println("usernick: " + userNick);
        return "hello";
    }

两者的区别

PathVariable

是后端编码,设定访问规则,如果是使用PathVariable这种方式进行访问的时候,是参数作为url进行访问的,写到参数里面是不行的。请求为:
Request URI = /app/mac/wo/getVehicleRecordList/1/zhaowei
Parameters = {}

RequestParam

如果是通过RequestParam:如果是参数的话,还是需要传递参数,会按照正常的参数进行传递。请求为:
ockHttpServletRequest:
HTTP Method = GET
Request URI = /app/mac/wo/getVehicleRecordList
Parameters = {vin=[LGWEESK57GE000111], startTime=[2018-10-01 00:00:00], endTime=[2019-10-01 00:00:00]}
Headers = {}

总结

当URL指向的是某一具体业务资源(或者资源列表),例如博客,用户时,使用@PathVariable
当URL需要对资源或者资源列表进行过滤,筛选时,用@RequestParam

例如我们会这样设计URL:

/blogs/{blogId}
/blogs?state=publish

猜你喜欢

转载自blog.csdn.net/weixin_37924923/article/details/88872702