TL;DR
I'm most probably missing something obvious, but it seems the behaviour is different between Spring Boot 2.x and Spring Boot 3.x
Adding a custom header by extending the OncePerRequestFilter
- does not work in Spring Boot 2.7
- works in Spring Boot 3.1
On a side note, the location of HttpServletRequest
and HttpServletResponse
changed between 2.x and 3.x
(See for example Why does spring-boot-3 give javax.servlet.http.HttpServletRequest ClassNotFoundException)
Details
Spring Boot 2.7.14
Filter class to add a custom header. Does NOT add the custom header.
package com.example.controller;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; // notice the package
import javax.servlet.http.HttpServletResponse; // notice the package
import java.io.IOException;
@Component
public class KeepAliveTimeoutFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
logger.info("Adding custom header"); // to confirm we're executing this
response.addHeader("Foo", "Bar");
filterChain.doFilter(request, response);
}
}
Spring Boot 3.3.1
Filter class to add a custom header. ADDS the custom header.
package com.example.controller;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest; // notice the package
import jakarta.servlet.http.HttpServletResponse; // notice the package
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
public class KeepAliveTimeoutFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
logger.info("Adding custom header"); // to confirm we're executing this
response.addHeader("Foo", "Bar");
filterChain.doFilter(request, response);
}
}
HandlerInterceptor
doesn't allow modifying response inpostHandle
which is trigerred after the controller has processed the request. OP (and me too) wants to add a response header just before the response is sent to the client. – LongtinbeforeBodyWrite
method fromimplements ResponseBodyAdvice<Object>
. – Longtin