Spring MVC @RequestBody如何工作

Evg*_*rov 4 java spring spring-mvc

我认为@RequestBody尝试params通过属性名称在注释之后将请求映射到对象.

但如果我得到:

@RequestMapping(value = "/form", method = RequestMethod.GET)
public @ResponseBody Person formGet(@RequestBody Person p,ModelMap model) {
    return p;
}
Run Code Online (Sandbox Code Playgroud)

请求:

http://localhost:8080/proj/home/form?id=2&name=asd
Run Code Online (Sandbox Code Playgroud)

返回415

当我改变@RequestBody Person p@RequestParam Map<String, String> params,没关系:

@RequestMapping(value = "/form", method = RequestMethod.GET)
public @ResponseBody Person formGet(@RequestParam Map<String, String> params) {
        return new Person();
}
Run Code Online (Sandbox Code Playgroud)

人员类:

public class Person{
    private long id;
    private String name;

    public Person() {
    }

    public Person(long id, String name) {
        super();
        this.id = id;
        this.name = name;
    }
    public long getId() {
        return id;
    }
    public void setId(long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

春天的vresion 3.2.3.RELEASE

我哪里做错了?

axt*_*avt 6

不,这是一份工作@ModelAttribute,而不是@RequestBody.

  • @ModelAttribute使用相应请求参数的值填充目标对象的字段,并在必要时执行转换.它可用于HTML表单生成的请求,带参数的链接等.

  • @RequestBody使用预先配置的HttpMessageConverters 之一将请求转换为对象.它可以用于包含JSON,XML等的请求.但是,没有HttpMessageConverter那种复制行为@ModelAttribute.