Junior — Middle
What is the difference between ResponseEntity and ResponseBody annotations in the context of HTTP response handling in Spring?
sobes.tech AI
Answer from AI
The @ResponseBody annotation in Spring indicates that the return value of a controller method should be serialized directly into the HTTP response body (for example, in JSON or XML), bypassing view rendering. It applies to methods or classes.
ResponseEntity is a wrapper class that allows not only returning the response body but also setting the HTTP status, headers, and other response parameters. Using ResponseEntity provides more flexible control over the HTTP response.
Example:
@GetMapping("/user")
@ResponseBody
public User getUser() {
return new User("John", 30); // body will be serialized into JSON
}
@GetMapping("/userWithStatus")
public ResponseEntity<User> getUserWithStatus() {
User user = new User("John", 30);
return ResponseEntity.status(HttpStatus.OK)
.header("Custom-Header", "value")
.body(user);
}
Thus, @ResponseBody is a way to indicate that the method returns the response body, and ResponseEntity is an object that contains the body, status, and headers of the HTTP response.