How to set HTTP response HEADERS in @RestController?
The HTTP response headers are very important. It is so, because the HEADERS values can inform to the HTTP client definitions about how to receive and interpret the received data. It include important fields, such as:
·
SET-COOKIE:
·
CONTENT-TYPE:
·
Content-Language:
·
RESPONSE-CODE:
·
Accept-Language:
·
Access-Control-Allow-Methods:
·
Etc;
You
can see a list here: https://en.wikipedia.org/wiki/List_of_HTTP_header_fields
Using
Spring boot and its @RestController, although there are a few annotations and attributes (ex. @CrossOrigem,
produces, etc.) that assists in the definition of how HTTP HEADERS have to be
produced, it is possible to generate that with more fine control using the
HttpHeaders class. Objects from this class have a method named .set(key,
value), which works as a map, you can set many key/value data, and each one
will be part of the HTTP Header. Once this object is created and its data
assigned, it is possible to return the HTTP response to the client, composing a
ResponseEntity object with the HTTPHeaders. This composition can be done by ResponseEntity
constructor, as you can see in the code below:
private ResponseEntity buildResponseEntitySuccess(Object result) {
HttpHeaders
responseHeaders = new HttpHeaders();
responseHeaders.set("Access-Control-Allow-Origin","*");
responseHeaders.set("Access-Control-Allow-Credentials", "true");
responseHeaders.set("Access-Control-Allow-Methods", "POST, GET, OPTIONS,
DELETE");
responseHeaders.set("Access-Control-Max-Age", "3600");
responseHeaders.set("Access-Control-Allow-Headers", "Content-Type, Accept,
X-Requested-With, remember-me");
return new ResponseEntity(result, responseHeaders, HttpStatus.OK);
}
It is important to
highlight that using ResponseEntity the @RestController still responsible to
part the output as the expected content-type. Hence, you can just set any
Object in the first parameter of this constructor, and Spring Boot will handle
it. This way, there is not sideback effect of using ResponseEntity as the
return type of a @RequestMapping, or returning a List of any specific type.
You can download an
example of this code from github:
https://github.com/rafaelqg/code/blob/main/http_headers_rest_controller.js
You may watch a video
class here:
Comments
Post a Comment