How do you add custom response headers in a Spring Boot application?

  • To add custom response headers in a Spring boot application use ResponeEntity class.
    • Set the values using HttpHeader object.
    • Set the header object in response entity
  • To set a response header for all the response , implement a Filter class and set the header in the ServletResponse class
  • Code Snippet
public class ResFilter implements Filter {

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
        httpServletResponse.setHeader("header name", "header value");
        filterChain.doFilter(servletRequest, servletResponse);

  • Output of the above 2 code snippets

Thank You !!

Leave a Reply