问题描述
有一个人在春季3说明 @RequestBody
和 @ResponseBody
?
他们是为了什么?一个例子是好的。
Can some one explain @RequestBody
and @ResponseBody
in Spring 3?What are they for? An example would be nice.
推荐答案
有在文档一整节名为16.3.3.4映射请求体与@RequestBody注释。而一个叫16.3.3.5映射响应主体与注释@ResponseBody 。我建议你向那些部分。也与此有关:<一href=\"http://static.springsource.org/spring/docs/current/javadoc-api/index.html?org/springframework/web/bind/annotation/RequestBody.html\"><$c$c>@RequestBody$c$c>的javadoc,<一个href=\"http://static.springsource.org/spring/docs/current/javadoc-api/index.html?org/springframework/web/bind/annotation/ResponseBody.html\"><$c$c>@ResponseBody$c$c>的javadoc
There is a whole Section in the docs called 16.3.3.4 Mapping the request body with the @RequestBody annotation. And one called 16.3.3.5 Mapping the response body with the @ResponseBody annotation. I suggest you consult those sections. Also relevant: @RequestBody
javadocs, @ResponseBody
javadocs
使用的例子是这样的:
使用JavaScript库像jQuery,你会发布一个JSON对象是这样的:
Using a JavaScript-library like JQuery, you would post a JSON-Object like this:
{ "firstName" : "Elmer", "lastName" : "Fudd" }
您控制器的方法是这样的:
Your controller method would look like this:
// controller
@ResponseBody @RequestMapping("/description")
public Description getDescription(@RequestBody UserStats stats){
return new Description(stats.getFirstName() + " " + stats.getLastname() + " hates wacky wabbits");
}
// domain / value objects
public class UserStats{
private String firstName;
private String lastName;
// + getters, setters
}
public class Description{
private String description;
// + getters, setters, constructor
}
现在,如果你有(并有<$c$c><mvc:annotation-driven>$c$c>设置),春季将传入的JSON转换成从后身体UserStats对象(因为你添加的 @RequestBody
注释),它会序列化返回的对象为JSON(因为您添加的 @ResponseBody
注释)。所以浏览器/客户将会看到此JSON结果:
Now if you have Jackson on your classpath (and have an <mvc:annotation-driven>
setup), Spring would convert the incoming JSON to a UserStats object from the post body (because you added the @RequestBody
annotation) and it would serialize the returned object to JSON (because you added the @ResponseBody
annotation). So the Browser / Client would see this JSON result:
{ "description" : "Elmer Fudd hates wacky wabbits" }
请参阅我的一个完整的工作示例的这一previous答案:
See this previous answer of mine for a complete working example: http://stackoverflow.com/a/5908632/342852
注:RequestBody / ResponseBody当然不限于JSON的,既可以处理多种格式,包括纯文本和XML,JSON,但可能是最常用的格式
Note: RequestBody / ResponseBody is of course not limited to JSON, both can handle multiple formats, including plain text and XML, but JSON is probably the most used format.
这篇关于@RequestBody和春天@ResponseBody的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!