ResponseEntity object is
Spring’s wrapper around the request response. It inherits from the
HttpEntity object and contains the Http response code (
httpstatus), the response header (
header), and the response body (
body). A Spring MVC interface to get user information usually we return the entity directly (with
is equivalent to using
ResponseEntity as the return value of the controller.
But we can do much more when using
Customizing the response code
ResponseEntity.ok above already contains the return
200 Http response code, we can also customize the return response code with
Customizing the response body
The response body that places the response is usually the data of our interface, here is an example.
Typically we specify the response headers for the Spring MVC interface by setting the
produces() attributes in the
@RequestMapping and its Restful family of annotations. If you are using
ResponseEntity, you can set it via a chain call.
All standard request headers have their corresponding setting methods, you can also set custom request headers with
header(String headerName, String... headerValues) to set a custom request header.
Let’s look at an abstract interface for handling return values of Spring MVC controller interfaces
One of its key implementations,
HttpEntityMethodProcessor, is the processor that handles controller methods that return a type of
HttpEntity. It will give the three kinds of information carried by
ResponseEntity to the
ServletServerHttpResponse object to render the view and set the processing flag to indicate that the response has been processed directly, and other subsequent methods will not be processed, with a very high priority.
Usually you write a download file interface is to get the
HttpServletResponse object, and then configure the
Content-Type to write a stream inside. If you use
ResponseEntity will be more simple and elegant.
Above is an example of downloading the Spring Boot configuration file
application.yml. There are three main steps.
- Wrap the file to be downloaded into an
org.springframework.core.io.Resourceobject, which has a number of implementations. Here we use
PathResourceare common implementations.
- Then configure the download file request header
Content-Disposition. It has two modes for downloading:
inlinemeans show the file content directly in the browser;
attachmentmeans download as a file. Please don’t forget the file extension, e.g.
application.ymlhere. If you don’t specify
Content-Disposition, you’ll need to set the corresponding
Content-Typeaccording to the file extension, which can be a bit tricky.
- Finally, the
ResponseEntity<Resource>is assembled and returned.
The above interface corresponds to the following effect.
org.springframework.http.converter.ResourceHttpMessageConverterfor the principle
Today we have shared the role and mechanism of
ResponseEntity in Spring and also shared an alternative way to download files. Interested to see the source code implementation.