userimage

What is @RequestBody @ResponseBody Spring framework?

What is @RequestBody @ResponseBody Spring framework?
userimage

@RequestBody and @ResponseBody annotations are used to bind the HTTP request/response body with a domain object in method parameter or return type. Behind the scenes, these annotation uses HTTP Message converters to convert the body of HTTP request/response to domain objects.

 

@RequestBody

 

If a method parameter is annotated with @RequestBody, Spring will bind the incoming HTTP request body to that parameter. While doing that, Spring will use HTTP Message converters to convert the HTTP request body into domain object, based on Accept header present in request.

 

The Accept header is used by HTTP clients to tell the server what content types they will accept. The server sends back the response, which will include a Content-Type header telling the client what the content type of the returned content actually is. In case of POST or PUT request, browsers do send data in request, so they actually send content-type as well.

Take this method for example:

 

@RequestMapping(value="/user/create", method=RequestMethod.POST)

public ResponseEntity<Void> createUser(@RequestBody User user, UriComponentsBuilder ucBuilder){

                if(userService.isUserExist(user)){

                                System.out.println("A User with name "+user.getName()+" already exist");

                                return new ResponseEntity<Void>(HttpStatus.CONFLICT);

                }

 

                // do some action

               

                HttpHeaders headers = new HttpHeaders();

                headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());

                return new ResponseEntity<Void>(headers, HttpStatus.CREATED);

}

 

This is the controller method to handle typical HTTP Post request [for URL /user/create]. In a pure REST oriented approach, this controller method creates a user, and returns the HTTP 201[CREATED] along with a LocationHeader containing the locations of newly created user [/app-address/user/1 e.g].

 

Now back to our original discussion, HTTP Post request body contains the detail of user to be created. When a client sends a request [/user/create] to create a user, it will be intercepted in this method. Method parameter user is marked with @RequestBody annotation. Thanks to this annotation, Spring will try to bind the request body [which can be JSON/XML/Other] to user object[ Means crating a new user object with the details found in the request body like user name,age etc..], based on Content-Type header in Http request.

 

But Spring need help to convert the request body into user object. It needs a converter which can convert the data in HTTP request body [which can be JSON/XML/Other] into user object.

 

For example, if the Content-Type in request Header was one of application/json or application/xml , that means the POST body contains json or XML[Popular formats], and if Jackson library is found in your classpath, Spring will delegate the conversion to MappingJackson2HttpMessageConverter [for json] or MappingJackson2XmlHttpMessageConverter [for xml].

 

To declare a dependency to Jackson library (jackson-databind) include following dependency in your pom.xml

 

<dependency>

                <groupId>com.fasterxml.jackson.core</groupId>

                <artifactId>jackson-databind</artifactId>

                <version>${jackson.version}</version>

</dependency>

 

ResponseEntity (used in above example) represents the entire HTTP response. Good thing about it is that you can control anything that goes into it. You can specify status code, headers, and body. Next post goes into details of it with a fully working example.

 

@ResponseBody

 

If a method is annotated with @ResponseBody, Spring will bind the return value to outgoing HTTP response body. While doing that, Spring will use HTTP Message converters to convert the return value to HTTP response body , based on Content-Type present in request HTTP header.

 

Take this method for example:

 

@RequestMapping(value = "/user/all", method = RequestMethod.GET)

public @ResponseBody List<User> listAllUsers() {

                return userService.findAllUsers();

}

This is the controller method to handle typical HTTP GET request [for URL /user/all] to retrieve all users. In this case, Spring will convert the user list into appropriate format [JSON/XML/Other] using available converters, based on content type.

Answer is