我已经使用Spring Boot 1.0.2实现了REST服务器。我无法阻止Spring设置禁用HTTP缓存的HTTP标头。
我的控制器如下:
@Controller public class MyRestController { @RequestMapping(value = "/someUrl", method = RequestMethod.GET) public @ResponseBody ResponseEntity<String> myMethod( HttpServletResponse httpResponse) throws SQLException { return new ResponseEntity<String>("{}", HttpStatus.OK); } }
所有HTTP响应均包含以下标头:
Cache-Control: no-cache, no-store, max-age=0, must-revalidate Expires: 0 Pragma: no-cache
我尝试了以下操作来删除或更改这些标头:
setCacheSeconds(-1)
httpResponse.setHeader("Cache-Control", "max-age=123")
@Bean
WebContentInterceptor
spring.resources.cache-period
application.properties
事实证明,Spring Security设置了无缓存HTTP标头。
以下内容禁用了HTTP响应标头Pragma: no-cache,但不能解决该问题:
Pragma: no-cache
import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; @Configuration @EnableWebMvcSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { // Prevent the HTTP response header of "Pragma: no-cache". http.headers().cacheControl().disable(); } }
我最终完全为公共静态资源禁用了Spring Security,如下所示(与上述相同):
@Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/static/public/**"); }
这需要配置两个资源处理程序以正确获取缓存控制标头:
@Configuration public class MvcConfigurer extends WebMvcConfigurerAdapter implements EmbeddedServletContainerCustomizer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { // Resources without Spring Security. No cache control response headers. registry.addResourceHandler("/static/public/**") .addResourceLocations("classpath:/static/public/"); // Resources controlled by Spring Security, which // adds "Cache-Control: must-revalidate". registry.addResourceHandler("/static/**") .addResourceLocations("classpath:/static/") .setCachePeriod(3600*24); } }