我该如何在使用Spring Boot构建的应用程序中为每个调用设置响应头呢?我想尝试使用过滤器拦截所有调用并能够设置响应头。我遵循了禁用浏览器缓存HTML5指南,但仅设置了请求头,并且不总是生效。
有三种方法可以实现这个功能:
@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);
}
}
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());
}
希望我能帮到你!
实现过滤器并通过@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 >> ");
}
}