gpt4 book ai didi

java - 如何在 Spring Boot 中将 Cache-Control header 添加到静态资源?

转载 作者:IT老高 更新时间:2023-10-28 20:40:32 27 4
gpt4 key购买 nike

如何在 Spring Boot 中为静态资源添加 Cache-Control HTTP header ?

尝试在应用程序中使用过滤器组件,该组件正确写入 header ,但 Cache-Control header 被覆盖。

@Component
public class CacheBustingFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException {
}

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
throws IOException, ServletException {

HttpServletResponse httpResp = (HttpServletResponse) resp;
httpResp.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
httpResp.setHeader("This-Header-Is-Set", "no-cache, no-store, must-revalidate");
httpResp.setHeader("Expires", "0");

chain.doFilter(req, resp);
}

我在浏览器中得到的是:

Cache-Control:no-store
This-Header-Is-Set:no-cache, no-store, must-revalidate
Expires:0

我想要的是:

Cache-Control:no-cache, no-store, must-revalidate
This-Header-Is-Set:no-cache, no-store, must-revalidate
Expires:0

最佳答案

这是因为 Spring Security:它重写了所有缓存头以完全禁用缓存。所以我们需要做两件事:

  1. 为静态资源禁用 Spring Security
  2. 启用静态资源缓存处理

在当前版本的 Spring Boot 中,我们可以在 application.properties 配置中更改此行为。

对某些资源禁用 spring 安全性:

# Comma-separated list of paths to exclude from the default secured 
security.ignored=/myAssets/**

为静态资源启用发送缓存头:

# Enable HTML5 application cache manifest rewriting.
spring.resources.chain.html-application-cache=true

# Enable the Spring Resource Handling chain. Disabled by default unless at least one strategy has been enabled.
spring.resources.chain.enabled=true
# Enable the content Version Strategy.
spring.resources.chain.strategy.content.enabled=true
# Comma-separated list of patterns to apply to the Version Strategy.
spring.resources.chain.strategy.content.paths=/**

# Locations of static resources.
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/

就是这样。现在 Spring 将检查您的静态文件是否已更改,并可以发送更智能的响应(If-Modiffied-Since 等)并重写您的应用缓存。

此外,如果有理由不为某些资源使用基于内容的版本 - 您可以使用备用 FixedVersion 策略并在配置中明确设置版本:

#Enable the fixed Version Strategy.
spring.resources.chain.strategy.fixed.enabled=false
# Comma-separated list of patterns to apply to the Version Strategy.
spring.resources.chain.strategy.fixed.paths=
# Version string to use for the Version Strategy.
spring.resources.chain.strategy.fixed.version=

See more in docs

关于java - 如何在 Spring Boot 中将 Cache-Control header 添加到静态资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33214501/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com