java – 如何使用Spring MVC和Spring Security为资源处理程序启用HTTP缓存

前端之家收集整理的这篇文章主要介绍了java – 如何使用Spring MVC和Spring Security为资源处理程序启用HTTP缓存前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望为某些静态资源(如图像)启用HTTP缓存,Spring Security对此进行了限制. (这些资源不是安全性关键,但也不应公开访问).如何避免Spring Security添加禁用缓存的HTTP响应头?

如果我将SetCachePeriod()添加到WebMvcConfigurerAdapter.addResourceHandlers()中的资源处理程序注册中,如下所示:

@H_403_4@registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/").setCachePeriod(3600);

资源仍然返回,并带有以下标题,禁用高速缓存:

@H_403_4@Cache-Control: max-age=3600,must-revalidate Expires: Mon,04 Aug 2014 07:45:36 GMT Pragma: no-cache

我想避免在项目中引入任何XML配置,目前仅使用Java注释配置.

有没有比扩展Spring资源处理程序更好的解决方案?

解决方法

您可以使用webContentInterceptor资源来允许静态资源缓存. @H_403_4@<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/static/*"/> <bean id="webContentInterceptor" class="org.springframework.web.servlet.mvc.WebContentInterceptor"> <property name="cacheSeconds" value="31556926"/> <property name="useExpiresHeader" value="true"/> <property name="useCacheControlHeader" value="true"/> <property name="useCacheControlNoStore" value="true"/> </bean> </mvc:interceptor> </mvc:interceptors>

使用注释配置缓存拦截器是按照以下方式完成的.
在Web配置类中,您可以为WebContentInterceptor类添加一个bean,并将其添加拦截器列表中.

@H_403_4@@Bean public WebContentInterceptor webContentInterceptor() { WebContentInterceptor interceptor = new WebContentInterceptor(); interceptor.setCacheSeconds(31556926); interceptor.setUseExpiresHeader(true);; interceptor.setUseCacheControlHeader(true); interceptor.setUseCacheControlNoStore(true); return interceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(webContentInterceptor()); }

参考this site看看它是如何完成的.

猜你在找的Java相关文章