如何在Spring Boot中启用HTTP响应缓存

我已经使用Spring Boot" title="Spring Boot">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

我尝试了以下操作来删除或更改这些标头:

  1. 调用setCacheSeconds(-1)控制器。
  2. 调用httpResponse.setHeader("Cache-Control", "max-age=123")控制器。
  3. 定义@Bean是回报WebContentInterceptor的,我打过电话setCacheSeconds(-1)
  4. 将属性设置spring.resources.cache-period为-1或正值application.properties

    以上都不起作用。如何在Spring Boot中为所有或单个请求禁用或更改这些标头?

回答:

事实证明,Spring Security设置了无缓存HTTP标头。

以下内容禁用了HTTP响应标头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);

}

}

以上是 如何在Spring Boot中启用HTTP响应缓存 的全部内容, 来源链接: utcz.com/qa/432650.html

回到顶部