Home  >  Spring 5

Spring @RequestBody Example

By Arvind Rai, April 30, 2020
This page will walk through Spring @RequestBody annotation example. The @RequestBody is annotated at method parameter level to indicate that this method parameter will bound to web request body. The consumes attribute of @RequestMapping can specify the media types acceptable to @RequestBody parameter. The @RequestBody can be used with HTTP methods POST, PUT etc. Hence we can use @RequestBody parameter in the methods annotated with @PostMapping and @PutMapping etc.
On this page we will discuss using @RequestBody in detail with complete example.

1. Technologies Used

Find the technologies being used in our example.
1. Java 11
2. Spring 5.2.5.RELEASE
3. Spring Boot 2.2.6.RELEASE
4. Maven 3.5.2

2. Maven Dependency

Find the Maven dependency to run the example.
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency> 

3. Using @RequestBody Annotation

To use @RequestBody, annotate the method parameter with it.
@PostMapping(value = "book")
public ResponseEntity<Book> addBook(@RequestBody Book book) {
   ------
} 
Now the body of web request will be assigned to book parameter.
By default a controller method consumes all media types. We can specify the specific media type to be consumed by @RequestBody. To consume application/json media-type, write code as following.
@PostMapping(value = "book", consumes = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<Book> addBook(@RequestBody Book book) {
   ------
} 
To consume application/xml media-type, write code as following.
@PostMapping(value = "book", consumes = { MediaType.APPLICATION_XML_VALUE })
public ResponseEntity<Book> addBook(@RequestBody Book book) {
   ------
} 
Find the code snippet to use @RequestBody with HTTP PUT method.
@PutMapping(value = "book", consumes = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<Book> updateBook(@RequestBody Book book) {
   ------
} 
Find the code snippet to use @RequestBody to consume byte array.
@PostMapping(value = "send", consumes = { MediaType.APPLICATION_OCTET_STREAM_VALUE })
public String userData(@RequestBody byte[] data) {
   ------
} 

4. Complete Example

BookController.java
package com.concretepage.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.concretepage.domain.Book;
import com.concretepage.service.BookService;

@RestController
public class BookController {
	@Autowired
	private BookService bookService;

	@PostMapping(value = "book", consumes = { MediaType.APPLICATION_JSON_VALUE })
	public ResponseEntity<Book> addBook(@RequestBody Book book, UriComponentsBuilder builder) {
		bookService.addBook(book);
		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(builder.path("/book/{id}").buildAndExpand(book.getBookId()).toUri());
		return new ResponseEntity<Book>(book, headers, HttpStatus.CREATED);
	}	
	
	@PostMapping(value = "send", consumes = { MediaType.APPLICATION_OCTET_STREAM_VALUE })
	public String userData(@RequestBody byte[] data) {
		bookService.userData(data);
		return "Data sent.";
	}
} 
Book.java
package com.concretepage.domain;
public class Book {
	private int bookId;
	private String name;
	private String writer;
        //Setters and Getters
} 
BookService.java
package com.concretepage.service;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.stereotype.Service;
import com.concretepage.domain.Book;

@Service
public class BookService {
	public void addBook(Book book) {
		book.setBookId(101);
	}
	public void userData(byte[] data) {
		InputStream is = new ByteArrayInputStream(data);
		try {
			while (is.available() != 0) {
				System.out.print((char) is.read());
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
} 
Find the client code.
RestClientUtil.java
package com.concretepage.client;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.concretepage.domain.Book;
public class RestClientUtil {
	public void addBookDemo() throws URISyntaxException {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);

		URI uri = new URI("http://localhost:8080/book");
		Book book = new Book();
		book.setName("Learning Spring");
		book.setWriter("Krishna");

		HttpEntity<Book> httpEntity = new HttpEntity<Book>(book, headers);

		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<Book> responseEntity = restTemplate.exchange(uri, HttpMethod.POST, httpEntity,
				Book.class);

		System.out.println("Status Code: " + responseEntity.getStatusCode());
		System.out.println("Location: " + responseEntity.getHeaders().getLocation());
	}
	
	public void sendText() throws URISyntaxException, IOException {
		URI url = new URI("http://localhost:8080/send");
		String msg = "Hello World!";
		HttpEntity<byte[]> requestEntity = new HttpEntity<>(msg.getBytes());
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> res = restTemplate.postForEntity(url, requestEntity, String.class);
		System.out.println(res.getStatusCodeValue());
		System.out.println(res.getBody());
	}
	public static void main(String args[]) throws URISyntaxException, IOException {
		RestClientUtil util = new RestClientUtil();
		util.addBookDemo();
		util.sendText();		
	}
} 

5. Run Application

Download the project and run the following command from root folder of the project using command prompt.
mvn spring-boot:run 
Now run client code as Java Application.

6. Reference

Spring doc: @RequestBody

7. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI








©2020 concretepage.com | Privacy Policy | Contact Us