Spring中的@RequestBody和@ResponseBody注释 [英] @RequestBody and @ResponseBody annotations in Spring
问题描述
有人可以在Spring 3中解释 @RequestBody
和 @ResponseBody
注释吗?它们适用于什么?任何例子都会很棒。
Can someone explain the @RequestBody
and @ResponseBody
annotations in Spring 3? What are they for? Any examples would be great.
推荐答案
文档中有一整段称为 16.3.3.4使用@RequestBody注释映射请求正文。一个名为 16.3。 3.5使用@ResponseBody注释映射响应正文。我建议你查阅这些部分。也相关: @RequestBody
javadocs, @ResponseBody
javadocs
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
用法示例如下:
使用像JQuery这样的JavaScript库,你会发布一个像这样的JSON-Object:
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
}
现在,如果你有在您的类路径上杰克逊(并且 < mvc:annotation-driven>
setup),Spring会将传入的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" }
有关完整的工作示例,请参阅我之前的答案: https://stackoverflow.com/a/5908632/342852
See this previous answer of mine for a complete working example: https://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.
更新:
自Spring 4.x以来,您通常不会在方法级别使用 @ResponseBody
,而是 @RestController
在类级别上,具有相同的效果。请参阅创建REST控制器@RestController注释
Update:
Ever since Spring 4.x, you usually won't use @ResponseBody
on method level, but rather @RestController
on class level, with the same effect. See Creating REST Controllers with the @RestController annotation
这篇关于Spring中的@RequestBody和@ResponseBody注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!