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.
Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.
You can set response headers, you can add response headers. And you can wonder what the difference is. But think about it for a second, then do this exercise. Draw a line from the HttpResponse method to the method's behavior.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With