@RequestBody and @ResponseBody
When building RESTful services based on Java Web, the Spring MVC framework provides powerful annotation support for handling HTTP request bodies and response bodies. Among them, @RequestBody and @ResponseBody are two of the most core and frequently used annotations. Their primary function is to establish automated mapping relationships between controller methods and method parameters, as well as between return types and HTTP status codes, thereby reducing developers' burden on manually parsing JSON/XML or serializing objects.
When we need to receive complex data structures sent by clients (such as user information order details), the data is typically encapsulated in an HTTP Request Body formatted as JSON. At this point, the @RequestBody annotation instructs Spring MVC to automatically extract data from the request body content and deserialize it into a Java object for method parameters.
This annotation must be placed on the parameter of a controller method and applies only to HTTP verbs that carry request body content (such as POST or PUT); methods like GET, HEAD, DELETE typically do not use this annotation. Spring MVC defaults to using Jackson JSON serializer to handle the data conversion process. If other converters are configured (such as JAXB), they can be switched by specifying attributes.
Core Functionality and Examples:
Assume we have a User class containing two fields: name and age:
public class User {
private String name;
private int age;
// Getter, Setter, Constructor...
}
The corresponding controller method is as follows. When the client sends a JSON Body { "name": "Alice", "age": 25 }, Spring automatically converts it into a User object and passes it to the method parameter:
@RestController
public class UserController {
@PostMapping("/users")
public User createUser(@RequestBody User user) {
// Spring has completed mapping from JSON to User object automatically
return new UserService().save(user);
}
}
During this process, Spring MVC parses the Content-Type in request headers (typically application/json) and after confirming the content type calls Jackson's ObjectMapper.readValue() method to complete deserialization. If the client sends XML without configuring a corresponding converter, an exception may be thrown or an error status code returned.
@ResponseBody: Serializing Object to Response Body
In contrast to receiving data, when we need to return complex data structures to clients, Spring MVC defaults to treating the method's return value directly as the HTTP Response Body (i.e., JSON/XML) rather than rendering it into an HTML page. This behavior is controlled by the @ResponseBody annotation. Like its counterpart, this annotation must be placed on a controller method or at parameters/return values to explicitly inform the framework: "Do not attempt to parse this return value as a view name; instead serialize it into response content".
After using this annotation, Spring MVC converts Java objects into JSON, XML, or other formats according to configured serializers and writes them into the HTTP Response Body. This is crucial for building pure API interfaces because it ensures backend services can expose data directly without additional frontend rendering logic.
Core Functionality and Examples:
Continuing with the User class above, if we want the controller method to return a list of user information:
@GetMapping("/users/{id}")
public List<User> getUserById(@PathVariable Long id) {
// Spring MVC automatically serializes List<User> into JSON string and puts it in response body
return userService.findById(id);
}
At this point, what the browser or client tool (such as Postman) receives will be content similar to: [{"name": "Bob", "age": 30}]. If the @ResponseBody annotation is removed, Spring MVC might attempt to find a view resolver to render an HTML page, resulting in return data that does not conform to API design specifications.
Collaborative Work and Best Practices of Both Annotations
In actual development, these two annotations often appear together, forming the standard pattern for RESTful Controllers: @RequestBody is used at the input end to receive data, while @ResponseBody (or default behavior) is used at the output end to send data. Understanding their interaction mechanism helps avoid common debugging pitfalls, such as failing deserialization when testing interfaces due to forgetting to set correct Content-Type, or mistakenly assuming HTML is returned and ignoring JSON format.
Furthermore, although these two annotations provide great convenience, one must also pay attention to performance overhead and type safety issues. Over-reliance on automatic mapping may lead to decreased code readability or difficulty tracking data flow paths. In large projects, it is recommended to combine DTO (Data Transfer Object) patterns further decouple business logic from entity classes, while using documentation tools like Swagger/OpenAPI to generate clear interface contracts, thereby improving team collaboration efficiency and maintaining reasonable control over maintenance costs.
By mastering the usage scenarios and principles of @RequestBody and @ResponseBody, developers can more efficiently build high-cohesion, low-coupling Spring MVC Web applications, ensuring consistency and stability in frontend-backend interactions.