Set response header in Spring Boot

2020-02-13 05:22发布

问题:

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.

回答1:

There are three ways to do this:

  1. 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);
    }
    
    1. Or you can put the response header for each call in the application (this is for Spring annotation-based, otherwise see automatically add header to every response):
    @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);
     }
    }
    
    1. 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

      • create your Interceptor that extends HandlerInterceptorAdapter:
    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;
      }
    }
    
    • In your MvcConfig thath extends WebMvcConfigurerAdapter you must Override the addInterceptors method and add new Interceptor:
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        ....
        registry.addInterceptor(new HeaderInterceptor());
    }
    

I hope I was helpful!



回答2:

Implement Filter and is registered by @Component annotation. The @Order(Ordered.HIGHEST_PRECEDENCE) is used for Advice execution precedence.

 @Component
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public class NoCacheWebFilter implements Filter {
       private static final Logger logger = LoggerFactory.getLogger(NoCacheWebFilter.class);


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.debug("Initiating WebFilter >> ");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
HeaderMapRequestWrapper requestWrapper = new 
                    HeaderMapRequestWrapper(req);
            // implement you logic to add header
            //requestWrapper.addHeader("remote_addr", "");
        chain.doFilter(requestWrapper, response); 

    }

    @Override
    public void destroy() {
        logger.debug("Destroying WebFilter >> ");
    }
    }