Can someone explain the @RequestBody and @ResponseBody annotations in Spring 3? What are they for? Any examples would be great.
Can someone explain the @RequestBody and @ResponseBody annotations in Spring 3? What are they
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
@RequestBodyjavadocs,@ResponseBodyjavadocsUsage examples would be something like this:
Using a JavaScript-library like JQuery, you would post a JSON-Object like this:
Your controller method would look like this:
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@RequestBodyannotation) and it would serialize the returned object to JSON (because you added the@ResponseBodyannotation). So the Browser / Client would see this JSON result:See this previous answer of mine for a complete working example: https://stackoverflow.com/a/5908632/342852
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.
Update
Ever since Spring 4.x, you usually won’t use
@ResponseBodyon method level, but rather@RestControlleron class level, with the same effect.Here is a quote from the official Spring MVC documentation: