基于Tim Barclay的答案,我创建了一个过滤器。如果所请求的资源是使用js、css、png、jpg、gif或svg扩展名的文件,则该过滤器会将Cache-Control和Expires设置为一年后,并禁用缓存。
希望对某些人有所帮助!
protected void setCacheHeaders(Environment environment, String urlPattern, int seconds) {
FilterRegistration.Dynamic filter = environment.servlets().addFilter(
"cacheControlFilter",
new Filter() {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;
String[] cacheFileTypes = {"js","css","png","jpg","gif","svg"};
String filetypeRequested = FilenameUtils.getExtension(httpServletRequest.getRequestURL().toString());
if (httpServletRequest.getMethod() == "GET" && seconds > 0 && Arrays.asList(cacheFileTypes).contains(filetypeRequested)) {
httpServletResponse.setHeader("Cache-Control", "public, max-age=" + seconds);
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.SECOND, seconds);
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
httpServletResponse.setHeader("Expires", format.format(c.getTime()));
} else {
httpServletResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
httpServletResponse.setHeader("Expires", "0");
httpServletResponse.setHeader("Pragma", "no-cache");
}
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
);
filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, urlPattern);
}
PS:我无法使用已接受答案的方法来设置Expires
头文件:
resp.setHeader("Expires", new Date().getTime()+500000 + "");
我的版本相比之下非常臃肿,但它可以工作:
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.SECOND, seconds);
SimpleDateFormat format = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("GMT"));
httpServletResponse.setHeader("Expires", format.format(c.getTime()));
env.servlets().addFilter("MyFilter", CacheControlFilter()).addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*")
- charlie_pl