![](/img/trans.png)
[英]How to use the @RequestBody annotation in Spring MVC inheritance
[英]Spring MVC how @RequestBody works
我认为@RequestBody
尝试在注释后通过属性名称将请求params
映射到对象。
但如果我得到:
@RequestMapping(value = "/form", method = RequestMethod.GET)
public @ResponseBody Person formGet(@RequestBody Person p,ModelMap model) {
return p;
}
请求:
http://localhost:8080/proj/home/form?id=2&name=asd
返回415
当我用@RequestParam Map<String, String> params
更改@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();
}
人员类:
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;
}
}
Spring vresion 3.2.3.RELEASE
我哪里做错了?
不,这是@ModelAttribute
的工作,而不是@RequestBody
。
@ModelAttribute
相应请求参数的值填充目标对象的字段,并在必要时执行转换。 它可用于HTML表单生成的请求,带参数的链接等。
@RequestBody
使用预先配置的HttpMessageConverter
之一将请求转换为对象。 它可以用于包含JSON,XML等的请求。但是,没有HttpMessageConverter
可以复制@ModelAttribute
行为。
输入到bean的转换需要:
对JSON主体使用POST或PUT请求。 在请求映射中通过“消耗”指定预期内容tipe也是很好的:
@RequestMapping(value = "/form", method = RequestMethod.POST, consumes = "application/json" )
将实现HttpMessageConverter的转换器实例添加到servlet上下文(例如servlet.xml)
<bean id="jsonConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
</bean>
将jackson核心和映射器jar添加到classpath(或pom.xml)
然后你可以用curl尝试一下
curl -X POST http://localhost:8080/proj/home/form -d '{"name":"asd", "id": 2}' -H 'Content-type:application/json'
很抱歉缺少详细信息,但我希望它有所帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.