在 Spring 引导中设置响应 header

Set response header in Spring Boot

如何为我的应用程序中使用 Spring Boot 进行的每次调用设置响应 header? 我想尝试使用过滤器来拦截所有调用并能够设置响应 header。 我遵循了指南 Disable browser caching HTML5,但只设置了请求 header,并不总是如此。

实现过滤器并通过@Component注解注册。 @Order(Ordered.HIGHEST_PRECEDENCE) 用于 Advice 执行优先级。

 @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 >> ");
    }
    }

有以下三种方法:

  1. 设置对特定控制器的响应,在控制器中class:

    @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. 或者您可以将 each 调用的响应 header 放入应用程序中(这是针对 Spring annotation-based,否则请参阅 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. 我找到的最后一种方法是使用扩展 HandlerInterceptorAdapter 的拦截器;有关详细信息,请参阅 https://www.concretepage.com/spring/spring-mvc/spring-handlerinterceptor-annotation-example-webmvcconfigureradapter

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

希望对您有所帮助!