Mastering @RequestBody and @ResponseBody in Spring MVC: A Quick Guide
This article explains how Spring MVC uses @RequestBody to deserialize JSON request bodies into Java objects and @ResponseBody to serialize Java objects back to JSON, providing clear code examples, curl testing, and notes on @RestController behavior.
1. Introduction
In this short article we briefly introduce the commonly used Spring MVC annotations @RequestBody and @ResponseBody.
2. @RequestBody
With @RequestBody Spring MVC automatically deserializes the HTTP request body into a Java object, typically mapping the JSON payload to a DTO.
Example controller method:
@PostMapping("/request")
public ResponseEntity postController(@RequestBody LoginForm loginForm) {
exampleService.fakeAuthenticate(loginForm);
return ResponseEntity.ok(HttpStatus.OK);
}The LoginForm class:
public class LoginForm {
private String username;
private String password;
// getters and setters
}Testing with curl:
curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data '{"username": "johnny", "password": "password"}' "https://localhost:8080/.../request"3. @ResponseBody
@ResponseBody tells Spring to serialize the returned object to JSON and write it to the HTTP response body.
Example response class:
public class ResponseTransfer {
private String text;
// standard getters/setters
}Controller using @ResponseBody:
@Controller
@RequestMapping("/post")
public class ExamplePostController {
@Autowired
ExampleService exampleService;
@PostMapping("/response")
@ResponseBody
public ResponseTransfer postResponseController(@RequestBody LoginForm loginForm) {
return new ResponseTransfer("Thanks For Posting!!!");
}
}Resulting JSON response:
{
"text": "Thanks For Posting!!!"
}Note: When a controller is annotated with @RestController, @ResponseBody is implicit.
4. Summary
We built a simple Spring application that receives JSON from an Angular client using @RequestBody and returns JSON using @ResponseBody or @RestController.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
