小编典典

Spring MVC-为什么不能同时使用@RequestBody和@RequestParam

spring

结合使用HTTP开发客户端和发布请求和Content-Type应用程序/ x-www-form-urlencoded

1)仅@RequestBody

请求-本地主机:8080 / SpringMVC /欢迎进入正文-name = abc

Code

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, Model model) {
    model.addAttribute("message", body);
    return "hello";
}

//如预期的那样将正文命名为“ name = abc”

2)仅@RequestParam

请求-本地主机:8080 / SpringMVC /欢迎进入正文-name = abc

Code

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestParam String name, Model model) {
    model.addAttribute("name", name);
    return "hello";
}

//预期名称为“ abc”

3)两者在一起

请求-本地主机:8080 / SpringMVC /欢迎进入正文-name = abc

Code

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, @RequestParam String name, Model model) {
    model.addAttribute("name", name);
    model.addAttribute("message", body);
    return "hello";
}

// HTTP错误代码400-客户端发送的请求在语法上不正确。

4)上面的参数位置已更改

请求-本地主机:8080 / SpringMVC /欢迎进入正文-name = abc

Code

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestParam String name, @RequestBody String body, Model model) {
    model.addAttribute("name", name);
    model.addAttribute("message", body);
    return "hello";
}

//没有错误。名称为“ abc”。身体是空的

5)在一起但获取类型url参数

请求-本地主机:8080 / SpringMVC / welcome?name = xyz在正文中-name = abc

Code

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestBody String body, @RequestParam String name, Model model) {
    model.addAttribute("name", name);
    model.addAttribute("message", body);
    return "hello";
}

//名称为“ xyz”,主体为“ name = abc”

6)与5)相同,但参数位置已更改

Code

@RequestMapping(method = RequestMethod.POST)
public String printWelcome(@RequestParam String name, @RequestBody String body, Model model) {
    model.addAttribute("name", name);
    model.addAttribute("message", body);
    return "hello";
}

// name =’xyz,abc’主体为空

有人可以解释这种行为吗?


阅读 1299

收藏
2020-04-13

共1个答案

小编典典

@RequestBodyjavadoc的状态

指示方法参数的注释应绑定到Web请求的正文。

它使用的注册实例HttpMessageConverter将请求主体反序列化为带注释的参数类型的对象。

@RequestParamjavadoc的状态

指示方法参数应绑定到Web请求参数的注释。

  1. Spring将请求的主体绑定到以注释的参数@RequestBody

  2. Spring将来自请求主体的请求参数(URL编码的参数)绑定到你的方法参数。Spring将使用参数的名称,即。name,以映射参数。

  3. 参数按顺序解析。首先@RequestBody处理。spring会消耗掉所有的HttpServletRequest InputStream。然后,当它尝试解析@RequestParam默认情况下的时required,查询字符串中没有请求参数,也没有请求正文的剩余内容,即。没有。因此失败400,因为处理程序方法无法正确处理请求。

  4. 处理程序@RequestParam首先执行操作,读取可以HttpServletRequest InputStream映射请求参数的内容,即。整个查询字符串/网址编码的参数。这样做并获取abc映射到参数的值name。@RequestBody运行处理程序时,请求主体中没有任何内容,因此使用的参数为空字符串。

  5. 处理程序@RequestBody读取主体并将其绑定到参数。然后,的处理程序@RequestParam可以从URL查询字符串获取请求参数。

  6. 用于@RequestParam从正文和URL查询字符串读取的处理程序。通常会将它们放在中Map,但是由于参数类型为String,Spring会将序列号Map分隔为逗号分隔的值。@RequestBody然后,处理程序再也没有从身体读取的内容了。

2020-04-13