在Spring Boot中设置响应头

时间:2018-03-22 14:11:34

标签: spring-boot filter browser-cache response-headers no-cache

如何在使用Spring Boot创建的应用程序中为每个调用设置响应头? 我想尝试使用过滤器来拦截所有调用,并能够设置响应头。 我按照指南Disable browser caching HTML5进行了操作,但只设置了请求标题,并非总是如此。

2 个答案:

答案 0 :(得分:8)

有三种方法可以做到这一点:

  1. 在Controller类中设置特定控制器的响应:

    @Controller
    @RequestMapping(value = DEFAULT_ADMIN_URL + "/xxx/")
    public class XxxController
    ....
        @ModelAttribute
        public void setResponseHeader(HttpServletResponse response) {
           response.setHeader("Cache-Control", "no-cache");
           ....
        }
    

    @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. 或者您可以将每个调用的响应标头放在应用程序中(这是基于Spring注释的,否则请参阅automatically add header to every response):
    2. @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. 我发现的最后一种方法是使用扩展HandlerInterceptorAdapter的Interceptor;有关详细信息,请参阅https://www.concretepage.com/spring/spring-mvc/spring-handlerinterceptor-annotation-example-webmvcconfigureradapter

        • 创建扩展HandlerInterceptorAdapter的拦截器:
      2. 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;
          }
        }
        
        • 在扩展WebMvcConfigurerAdapter的MvcConfig中,您必须覆盖addInterceptors方法并添加新的拦截器:
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            ....
            registry.addInterceptor(new HeaderInterceptor());
        }
        

        我希望我能提供帮助!

答案 1 :(得分:0)

实施过滤器并由@Component注释注册。 @Order(Ordered.HIGHEST_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 >> ");
    }
    }