java 设置http响应_java-如何在Spring B中启用HTTP响应缓存

java-如何在Spring B中启用HTTP响应缓存

我已经使用Spring Boot 1.0.2实现了REST服务器。 我无法阻止Spring设置禁用HTTP缓存的HTTP标头。

我的控制器如下:

@Controller

public class MyRestController {

@RequestMapping(value = "/someUrl", method = RequestMethod.GET)

public @ResponseBody ResponseEntity myMethod(

HttpServletResponse httpResponse) throws SQLException {

return new ResponseEntity("{}", HttpStatus.OK);

}

}

所有HTTP响应均包含以下标头:

Cache-Control: no-cache, no-store, max-age=0, must-revalidate

Expires: 0

Pragma: no-cache

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

在控制器中致电spring.resources.cache-period。

Call spring.resources.cache-period in the controller.

定义spring.resources.cache-period,该函数返回application.properties(我称之为setCacheSeconds(-1))。

将属性spring.resources.cache-period设置为-1或application.properties中的正值。

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

7个解决方案

52 votes

事实证明,Spring Security设置了无缓存HTTP标头。 在[http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#headers]中对此进行了讨论。

以下内容禁用了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和Spring Security应用程序中提供静态Web资源。

Samuli Kärkkäinen answered 2020-06-18T03:59:22Z

6 votes

在Spring Boot中,有很多方法可以进行HTTP缓存。 使用Spring Boot 2.1.1和其他Spring Security 5.1.1。

1.对于在代码中使用resourcehandler的资源:

您可以通过这种方式添加资源的自定义扩展。

registry.addResourceHandler

用于添加uri路径以获取资源

.addResourceLocations

用于设置文件系统中资源所在的位置(给定的是具有classpath的相对路径,但也可以使用file :: //的绝对路径。)

.setCacheControl

用于设置缓存头(自我解释。)

Resourcechain和resolver是可选的(在这种情况下,它与默认值完全相同)。

@Configuration

public class CustomWebMVCConfig implements WebMvcConfigurer {

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/*.js", "/*.css", "/*.ttf", "/*.woff", "/*.woff2", "/*.eot",

"/*.svg")

.addResourceLocations("classpath:/static/")

.setCacheControl(CacheControl.maxAge(365, TimeUnit.DAYS)

.cachePrivate()

.mustRevalidate())

.resourceChain(true)

.addResolver(new PathResourceResolver());

}

}

2.对于使用应用程序属性配置文件的资源

与上面相同,减去了特定的模式,但现在是config。此配置将应用于列出的静态位置中的所有资源。

spring.resources.cache.cachecontrol.cache-private=true

spring.resources.cache.cachecontrol.must-revalidate=true

spring.resources.cache.cachecontrol.max-age=31536000

spring.resources.static-locations=classpath:/static/

3.在控制器级别

这里的响应是作为参数注入到控制器方法中的HttpServletResponse。

no-cache, must-revalidate, private

getHeaderValue将缓存选项输出为字符串。 例如

response.setHeader(HttpHeaders.CACHE_CONTROL,

CacheControl.noCache()

.cachePrivate()

.mustRevalidate()

.getHeaderValue());

Merv answered 2020-06-18T04:00:30Z

5 votes

我找到了这个Spring扩展:[https://github.com/foo4u/spring-mvc-cache-control。]

您只需要执行三个步骤。

步骤1(pom.xml):

net.rossillo.mvc.cache

spring-mvc-cache-control

1.1.1-RELEASE

compile

步骤2(WebMvcConfiguration.java):

@Configuration

public class WebMvcConfig extends WebMvcConfigurerAdapter implements WebMvcConfigurer {

@Override

public void addInterceptors(InterceptorRegistry registry) {

registry.addInterceptor(new CacheControlHandlerInterceptor());

}

}

步骤3(控制器):

@Controller

public class MyRestController {

@CacheControl(maxAge=31556926)

@RequestMapping(value = "/someUrl", method = RequestMethod.GET)

public @ResponseBody ResponseEntity myMethod(

HttpServletResponse httpResponse) throws SQLException {

return new ResponseEntity("{}", HttpStatus.OK);

}

}

dap.tci answered 2020-06-18T04:01:07Z

0 votes

我遇到类似的问题。 我只想在浏览器中缓存一些动态资源(图像)。 如果图像改变(不是很频繁),我会改变尿液的一部分。这是我的解决方案

http.headers().cacheControl().disable();

http.headers().addHeaderWriter(new HeaderWriter() {

CacheControlHeadersWriter originalWriter = new CacheControlHeadersWriter();

@Override

public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {

Collection headerNames = response.getHeaderNames();

String requestUri = request.getRequestURI();

if(!requestUri.startsWith("/web/eventImage")) {

originalWriter.writeHeaders(request, response);

} else {

//write header here or do nothing if it was set in the code

}

}

});

Michal Ambrož answered 2020-06-18T04:01:27Z

0 votes

@Configuration

@EnableAutoConfiguration

public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

@Override

public void addResourceHandlers(ResourceHandlerRegistry registry) {

registry.addResourceHandler("/resources/**")

.addResourceLocations("/resources/")

.setCachePeriod(31556926);

}

}

Vazgen Torosyan answered 2020-06-18T04:01:43Z

0 votes

如果您不希望对静态资源进行身份验证,则可以执行以下操作:

import static org.springframework.boot.autoconfigure.security.servlet.PathRequest.toStaticResources;

@EnableWebSecurity

public class SecurityConfig extends WebSecurityConfigurerAdapter {

...

@Override

public void configure(WebSecurity webSecurity) throws Exception {

webSecurity

.ignoring()

.requestMatchers(toStaticResources().atCommonLocations());

}

...

}

并在您的application.properties中:

spring.resources.cache.cachecontrol.max-age=43200

有关可以设置的更多属性,请参见ResourceProperties.java。

cstroe answered 2020-06-18T04:02:11Z

0 votes

我在控制器中使用了以下几行。

ResponseEntity.ok().cacheControl(CacheControl.maxAge(secondWeWantTobeCached, TimeUnit.SECONDS)).body(objToReturnInResponse);

请注意,Response将具有标题Cache-Control,其值为secondWeWantTobeCached。 但是,如果我们在地址栏中输入url并按Enter,则请求将始终从Chrome发送到服务器。 但是,如果我们从某个链接中访问url,浏览器将不会发送新请求,而是从缓存中获取。

Vikky answered 2020-06-18T04:02:36Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值