要使新版本的客户端(浏览器)缓存无效,我必须向我的资源 URL 添加一个随机字符串参数。
我使用 Spring MVC 开发一个 Web 应用程序,并使用 Maven 来构建该项目。
我的问题是如何用 Maven 生成这样的字符串?当我有可能将变量放置在任何文件、JSP、标签中时,这是有意义的:
<link rel="stylesheet" type="text/css" href="/css/master.css?cache={random}" media="all"/>
并在构建时用随机字符串替换变量。
最佳答案
您可以只使用版本号,而不是在 Maven 构建期间生成随机字符串。这对于每个版本都是不同的,并且适合您的用例。
为此,您可以使用 filtering maven-war-plugin
的功能。在 JSP 中,声明占位符 ${project.version}
:
<link rel="stylesheet" type="text/css" href="/css/master.css?cache=${project.version}" media="all"/>
然后,在 Maven 构建过程中,您可以过滤此文件,Maven 会自动用当前版本替换此占位符。
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<webResources>
<resource>
<directory>src/main/webapp</directory>
<filtering>true</filtering>
</resource>
</webResources>
</configuration>
</plugin>
<小时/>
如果你确实想生成一个随机字符串,你可以使用 maven-antrun-plugin
执行以下任务(取自 this answer ):
<scriptdef name="generateguid" language="javascript">
<attribute name="property" />
<![CDATA[
importClass( java.util.UUID );
project.setProperty( attributes.get( "property" ), UUID.randomUUID() );
]]>
</scriptdef>
<generateguid property="guid1" />
<echo message="${guid1}" />
属性 guid1
将保存您的随机字符串,请务必设置 exportAntProperties
在插件配置中设置为 true
。然后,您可以使用 ${guid1}
占位符而不是 ${project.version}
关于java - 通过Maven生成url nocache参数字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33014552/