This post will discuss how to add a header to a specific response in a Spring Boot application.

There are several ways to add a custom header to a specific response in a Spring Boot application.

1. Using HttpServletResponse

To set the response for a specific controller, we can do something like:

 
The above code will set the response for all endpoints in the controller. To set response for a specific endpoint in the controller, we can add the HttpServletResponse instance at the endpoint as an argument and then call the setHeader() method of the HttpServletResponse object for setting the headers:

2. Using ResponseEntity

As demonstrated below, we can also add headers to the ResponseEntity builder with the HttpHeaders class.

That’s all about adding a header to a specific response in Spring Boot.

 
Read More:

Set a header to all responses in Spring Boot