This post will discuss how to set a header to all responses in a Spring Boot application.

In the previous post, we have covered how to set a header on a single response using HttpServletResponse or ResponseEntity. This post will discuss how to set a custom header to all responses in our application.

The idea is to use a filter. By using a filter, we can avoid adding responses manually for each of the mapping methods. There are several ways to register a filter class and set a response header in the Spring Boot application.

1. Extending OncePerRequestFilter

To create a custom filter, we can also extend the abstract class OncePerRequestFilter and annotate the filter with @Component. To set a header to each response, use addHeader() method of the HttpServletResponse interface. This is demonstrated below:

2. Implementing Filter Interface

We can also implement the Filter interface and annotate the filter with one of the Spring stereotypes, such as @Component for Spring to recognize it. To set the custom header to each response, use addHeader() method of the HttpServletResponse interface.

That’s all about setting a header to all responses in Spring Boot.