In Spring MVC, the ResponseEntity is used to wrap an HTTP response that can contain both the body of the response and any relevant headers. The ResponseEntity is very useful for handling HTTP responses when building RESTful APIs in Spring MVC.
With ResponseEntity, we can customize the HTTP status code, headers, and the response body. It allows us to control the HTTP response in a finer-grained manner.
Here is an example of how we can use ResponseEntity in Spring MVC:
@RequestMapping(value = "/products/{id}", method = RequestMethod.GET)
public ResponseEntity<Product> getProduct(@PathVariable("id") long id) {
Product product = productService.getProductById(id);
if (product == null) {
return new ResponseEntity<Product>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Product>(product, HttpStatus.OK);
}
Here, we are defining an endpoint to get a product with a given id. In this method, we are using the ProductService to retrieve the product with the given id. If the product is not found, we are returning a ResponseEntity with a HttpStatus.NOT_FOUND status code. If the product is found, we are returning a ResponseEntity with a HttpStatus.OK status code and the product as the response body.
The ResponseEntity can also be used to set the headers of the HTTP response. Here is an example:
@RequestMapping(value = "/products", method = RequestMethod.POST)
public ResponseEntity<Product> createProduct(@RequestBody Product product) {
productService.createProduct(product);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(URI.create("/products/" + product.getId()));
return new ResponseEntity<Product>(headers, HttpStatus.CREATED);
}
Here, we are defining an endpoint to create a new product. After creating the product using the ProductService, we are setting the location header to the URI of the newly created product. We are then returning a ResponseEntity with a HttpStatus.CREATED status code and the headers we just set.
In summary, ResponseEntity is a powerful tool in Spring MVC for building RESTful APIs. It allows us to customize the HTTP response in a finer-grained manner by setting the HTTP status code, headers, and response body.