Last Updated on 04 October 2024   |   Print Email
If you’re curious about the meaning and purpose of the @ResponseBody annotation in the Spring framework, you’ve come the right post. In this article, I’d like to provide insights into the semantics, syntax, and usage of this Spring annotation, which I believe you’ll find helpful.
1. What is @ResponseBody annotation?
According to its official Javadocs, this annotation indicates a method return value should be bound to the web response body. What does that mean?Well, it means that Spring MVC will automatically serialize the Java object returned by a handler method in a controller to the content type accepted by the client, through an HttpMessageConverter. For example, if the client accepts the “application/json” content type, the MappingJackson2HttpMessageConverter is used to convert the Java object returned by the handler method into an appropriate JSON document, which is then sent in the response body.In other words, using @ResponseBodyannotation saves you a lot of time, as you don’t have to manually write code to convert Java objects to JSON/XML content, which is commonly required by web clients. It also helps in writing cleaner and more readable code as it eliminates boilerplate.Having said that, the @ResponseBodyannotation is widely used in REST API development with the Spring framework and Spring MVC because of its convenience.
2. Understand @ResponseBody annotation by code examples
Using this annotation is very simple since it doesn’t have any attributes. You can apply it to a handler method or a Spring MVC controller class. The following code example illustrates the use of the @ResponseBodyannotation in a hander method:
package net.codejava;
import org.springframework.web.bind.annotation.ResponseBody;
...
@RestController
@RequestMapping("/api/students")
public class StudentApiController {
@GetMapping("/{id}")
@ResponseBody
public Student getStudent(@PathVariable(name = "id") Integer id) {
Student student = repo.findById(id).get();
return student;
}
}
In this example, the getStudent() handler method is annotated with the @ResponseBody annotation, so Spring MVC will serialize the Student object returned by the method into the corresponding JSON document. Suppose the Student class is written as follows:
public class Student {
private Integer id;
private String name;
// getters and setters are not shown
}
Then the server could return the following JSON in the response body, for example, for student ID 123:
{
"id": 123,
"name": "Mark Collins"
}
If a handler method returns a collection (e.g., List), Spring MVC will serialize the collection into an array of JSON objects. For example, consider the following handler method:
@GetMapping
@ResponseBody
public List<Student> listStudent() {
return repo.findAll();
}
You can use the @ResponseBody annotation at the class level, for example, to annotate a controller class. In that case, all the handler methods inherit the annotation, so you don’t have to apply it to each method individually. For example:
@RestController
@RequestMapping("/api/students")
@ResponseBody
public class StudentApiController {
@GetMapping
public List<Student> listStudent() {
...
}
@GetMapping("/{id}")
public Student getStudent(@PathVariable(name = "id") Integer id) {
...
}
@PostMapping
public Student addStudent(@RequestBody Student student) {
...
}
...
}
Another real-world example of using the @ResponseBody annotation is in an exception handler class rather than a controller class. Check this article and this one for more examples.
3. Implicit Use of @ResponseBody annotation
You don’t need to use this annotation in a REST controller class because it is already included in the @RestController already:
@Controller
@ResponseBody
public @interface RestController {
...
}
That means all handler methods in a @RestController class have their return values bound to the web response body automatically. Therefore, you may need to use this annotation explicitly in classes other than REST controllers.If you want to see the use of this annotation in a real-world project, watch the coding in this video:
Summary
Using the @ResponseBody annotation is a convenient way to have Java objects returned by handler methods serialized to the content type accepted by the client, such as JSON or XML, so you don’t have to manually write code to convert Java objects into other representations. You can apply this annotation at the method or class level, and it is implicitly used by the @RestController annotation.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments