问题背景
在美化网页过程中,修改好CSS后在本地已经可以显示出我想要的效果了。于是就把修改好后的css加载到springboot中运行,结果问题出现了:我修改后的css样式始终不能加载!打开F12看到css样式成功的被请求,然后再进一步点进去看css文件,发现我修改的部分并没有加载,现在用的css还是我修改以前的css。这里我注意到一个细节,然后才明白是怎么回事
原来spring boot会把静态文件缓存到浏览器本地。但这样就造成了一个问题:如果服务器静态文件修改,浏览器端在未过期之前是不会重新加载文件的。此时需要通过版本号来控制。spring boot版本号支持两种,一种是文件md5,另一种是固定版本号。我采用的是md5方式,spring boot启动时会计算每个静态文件的md5值并缓存,浏览器访问时每个静态文件后缀前加上md5值作为版本号,如果服务器md5值改变则浏览器重新加载。(需要重启应用才会重新生成md5)
下面来设置md5方式:
1、先设置文件配置application.properties
# 资源缓存时间,单位秒
spring.resources.cache.period=604800
# 开启gzip压缩
spring.resources.chain.compressed=true
# 启用缓存
spring.resources.chain.cache=true
# 使用MD5版本号
spring.resources.chain.strategy.content.enabled=true
spring.resources.chain.strategy.content.paths=/**
2、添加静态资源控制类,使用ResourceUrlProvider
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.servlet.resource.ResourceUrlProvider;
/**
* 使用ResourceUrlProvider进行版本管理
* 并避免在版本发生改变时,由于浏览器缓存而产生资源版本未改变的错误
*/
@ControllerAdvice
public class ControllerConfig {
@Autowired
private ResourceUrlProvider resourceUrlProvider;
@ModelAttribute("urls")
public ResourceUrlProvider urls() {
return this.resourceUrlProvider;
}
}
3、在网页中引用静态文件
注意:如果使用的thymeleaf模板引擎的话,那么需要这么进行编写:
<link rel="stylesheet" th:href="${urls.getForLookupPath('/css/font.css')}">
<link rel="stylesheet" th:href="${urls.getForLookupPath('/css/xadmin.css')}">
<script th:src="${urls.getForLookupPath('/lib/layui/layui.js')}" charset="utf-8"></script>
<script type="text/javascript" th:src="${urls.getForLookupPath('/js/xadmin.js')}"></script>