Spring MVC Tutorial
Core Spring MVC
Spring MVC - Annotation
Spring MVC - Form Handling
Spring MVC with JSTL
Spring MVC with REST API
Spring MVC with Database
The @ResponseBody
annotation in Spring is used to bind the return value of a method to the response body of the HTTP request, effectively bypassing the standard view resolver mechanism. When you annotate a method with @ResponseBody
, Spring will serialize the return value and send it as the HTTP response body.
This is particularly useful when building RESTful web services where you want to directly send data like JSON or XML to the client.
Make sure you have the necessary dependencies to handle JSON or XML responses. For JSON, the most common library is Jackson.
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.x.x</version> </dependency>
Let's create a simple Spring MVC controller that returns a Person
object as a JSON response:
Person
model:public class Person { private String name; private int age; // Constructors, getters, and setters... }
PersonController
:@RestController @RequestMapping("/person") public class PersonController { // Using @ResponseBody @RequestMapping(value = "/get", method = RequestMethod.GET) @ResponseBody public Person getPerson() { return new Person("John", 30); } }
In the above code, the @ResponseBody
annotation indicates that the Person
object should be serialized to JSON and sent back as the HTTP response body.
Note: The @RestController
annotation, introduced in Spring 4, is a convenience annotation that combines @Controller
and @ResponseBody
. So when you use @RestController
, every method in the controller will have @ResponseBody
behavior by default, meaning they will serialize their return value into the HTTP response. Therefore, in the context of a @RestController
, you won't need to explicitly add the @ResponseBody
annotation to your methods.
When you make a GET request to /person/get
, you'll receive a JSON response like:
{ "name": "John", "age": 30 }
The @ResponseBody
annotation works with the HttpMessageConverter
mechanism of Spring. Based on the content type requested and the libraries available on the classpath, Spring decides which HttpMessageConverter
to use. For example, with Jackson on the classpath, Spring will use the MappingJackson2HttpMessageConverter
to handle JSON responses.
Using @ResponseBody in Spring MVC:
This annotation is used to indicate that the return value of a method should be directly written to the HTTP response body. It is typically used with the ResponseEntity
class or other types that Spring can convert to a suitable HTTP response body.
@RequestMapping("/example") @ResponseBody public String exampleMethod() { return "This string will be directly written to the response body."; }
JSON response with @ResponseBody in Spring:
@RequestMapping("/jsonExample") @ResponseBody public Map<String, Object> jsonExample() { Map<String, Object> data = new HashMap<>(); data.put("key1", "value1"); data.put("key2", "value2"); return data; }
Customizing response content with @ResponseBody:
@RequestMapping("/customizedResponse") @ResponseBody public ResponseEntity<String> customizedResponse() { HttpHeaders headers = new HttpHeaders(); headers.add("Custom-Header", "Custom Value"); return new ResponseEntity<>("Custom Response Body", headers, HttpStatus.OK); }
Using @ResponseBody for XML response in Spring:
@RequestMapping("/xmlExample") @ResponseBody public Person xmlExample() { Person person = new Person(); person.setName("John Doe"); person.setAge(25); return person; }
Handling binary data with @ResponseBody in Spring:
@RequestMapping(value = "/binaryData", produces = MediaType.IMAGE_JPEG_VALUE) @ResponseBody public byte[] binaryData() throws IOException { InputStream in = getClass().getResourceAsStream("/path/to/image.jpg"); return IOUtils.toByteArray(in); }
Spring MVC @ResponseBody and Jackson example:
@RequestMapping("/jacksonExample") @ResponseBody public Person jacksonExample() { Person person = new Person(); person.setName("Jane Doe"); person.setAge(30); return person; }
Using @ResponseBody in Spring Boot RESTful services:
It is similar to using @ResponseBody
in Spring MVC. Spring Boot simplifies the process of building RESTful services by providing auto-configuration and sensible defaults.
@RestController public class MyController { @RequestMapping("/springBootExample") @ResponseBody public String springBootExample() { return "Spring Boot RESTful Service Example"; } }