美文网首页
Spring - @PathVariable、@RequestP

Spring - @PathVariable、@RequestP

作者: OldChicken_ | 来源:发表于2018-10-19 16:53 被阅读18次

@PathVariable

在url中已经预留了变量的占位符时,需要使用@PathVariable,顾名思义,是路径(path)上的变量(variable),例如:
param1可以通过如下方式配置:

@RequestMapping(value="/springmvc/{param1}", method = RequestMethod.GET)
public String getDetails (
    @RequestParam(value="param1") String param1) {
...
}

实现GET请求的url是:

http://localhost:8080/springmvc/param1value

@RequestParam

在url中没有预留参数的占位符时,需要使用@RequestParam,顾名思义,是请求(Request)中的参数(Param)。具体使用场景有:

  1. 处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况。
  2. 用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST.
@RequestMapping(value="/springmvc", method = RequestMethod.GET)
public String getDetails (
    @RequestParam(value="param1", required=true) String param1,
    @RequestParam(value="param2", required=false) String param2){
...
}

实现GET请求的url是:

http://localhost:8080/springmvc?param1=10&param2=20

@RequestBody

在url中没有预留参数的占位符,且请求中包含结构体对象时,需要使用@RequestBody,顾名思义,是请求(Request)中的结构体(Body)。具体使用场景有:

  • 处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等。它是通过使用 HandlerAdapter 配置的 HttpMessageConverters 来解析 body,然后绑定到相应的bean上的。
@RequestMapping(value="/springmvc", method = RequestMethod.GET)
public String getDetails (@RequestBody User user) {
... 
}

实现GET请求的url是:

$scope.user = {
            username: "foo",
            auth: true,
            password: "bar"
        };    
$http.get('http://localhost:8080/springmvc', $scope.user)

参考文章:
What is difference between @RequestBody and @RequestParam?
@RequestParam vs @PathVariable
@RequestParam @RequestBody @PathVariable 等参数绑定注解详解

相关文章

网友评论

      本文标题:Spring - @PathVariable、@RequestP

      本文链接:https://www.haomeiwen.com/subject/jffuzftx.html