How can I set the response header for each call in my application made with Spring Boot? I would like to try to use a filter to intercept all the calls and be able to set the response header. I followed the guide Disable browser caching HTML5, but only set the request header, and not always.
There are three ways to do this:
Set the response for a specific controller, in the Controller class:
@Controller @RequestMapping(value = DEFAULT_ADMIN_URL + "/xxx/") public class XxxController .... @ModelAttribute public void setResponseHeader(HttpServletResponse response) { response.setHeader("Cache-Control", "no-cache"); .... }
or
@RequestMapping(value = "/find/employer/{employerId}", method = RequestMethod.GET) public List getEmployees(@PathVariable("employerId") Long employerId, final HttpServletResponse response) { response.setHeader("Cache-Control", "no-cache"); return employeeService.findEmployeesForEmployer(employerId); }
@Component public class Filter extends OncePerRequestFilter { .... @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { //response.addHeader("Access-Control-Allow-Origin", "*"); //response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Cache-Control", "no-store"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. response.setHeader("Expires", "0"); // Proxies. filterChain.doFilter(request, response); } }
The last way I found is using an Interceptor that extends HandlerInterceptorAdapter; for more info see https://www.concretepage.com/spring/spring-mvc/spring-handlerinterceptor-annotation-example-webmvcconfigureradapter
public class HeaderInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) { httpServletResponse.setHeader("Cache-Control", "no-store"); // HTTP 1.1. httpServletResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0. httpServletResponse.setHeader("Expires", "0"); // Proxies. return true; } }
@Override public void addInterceptors(InterceptorRegistry registry) { .... registry.addInterceptor(new HeaderInterceptor()); }
I hope I was helpful!