环境说明
- 后台框架:springboot
- 前台语言:html,css,js,jquery,bootstrap
问题描述
项目每次发布后,如果前台的html或css或js有改动,必须先清空浏览器的缓存才能看到修改后的效果
解决办法
在项目打war包时,给项目中的css,js 添加版本号
- 修改pom.xml,在properties中添加版本号的取值规则
<maven.build.timestamp.format>yyyyMMddHHmmss</maven.build.timestamp.format>
- 修改pom.xml,在plugins中替换规则,在css/js文件末尾追加?v=时间戳
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- css,js 打包添加版本号,解决前端页面样式缓存问题 -->
<plugin>
<groupId>com.google.code.maven-replacer-plugin</groupId>
<artifactId>replacer</artifactId>
<version>1.5.3</version>
<executions>
<execution>
<!-- 设置生命周期 -->
<phase>prepare-package</phase>
<goals>
<goal>replace</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- 自动识别到项目target文件夹 -->
<basedir>${project.build.directory}</basedir>
<!-- 替换的文件所在目录规则 -->
<includes>
<include>**/*.html</include>
</includes>
<replacements>
<!-- 更改规则,在css/js文件末尾追加?v=时间戳,反斜杠表示字符转义 -->
<replacement>
<token>\.css\"</token>
<value>.css?v=${maven.build.timestamp}\"</value>
</replacement>
<replacement>
<token>\.css\'</token>
<value>.css?v=${maven.build.timestamp}\'</value>
</replacement>
<replacement>
<token>\.js\"</token>
<value>.js?v=${maven.build.timestamp}\"</value>
</replacement>
<replacement>
<token>\.js\'</token>
<value>.js?v=${maven.build.timestamp}\'</value>
</replacement>
</replacements>
</configuration>
</plugin>
3.在前端html页面中设置meta标签 清除页面缓存
<!-- Pragma:设定禁止浏览器从本地计算机的缓存中访问页面内容。这样设定,访问者将无法脱机浏览-->
<meta http-equiv="Pragma" content="no-cache">
<!-- Cache-Control:指定请求和响应遵循的缓存机制。-->
<meta http-equiv="Cache-Control" content="no-store,no-cache">
<!-- expires:可以用于设定网页的到期时间。一旦网页过期,必须到服务器上重新传输 -->
<meta http-equiv="expires" content="0">