如何在使用Spring Boot创建的应用程序中为每个调用设置响应头? 我想尝试使用过滤器来拦截所有调用,并能够设置响应头。 我按照指南Disable browser caching HTML5进行了操作,但只设置了请求标题,并非总是如此。
答案 0 :(得分:8)
有三种方法可以做到这一点:
在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); }
@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); } }
我发现的最后一种方法是使用扩展HandlerInterceptorAdapter的Interceptor;有关详细信息,请参阅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()); }
我希望我能提供帮助!
答案 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 >> ");
}
}