使用freemarker的web项目经常需要用在Url后面加上时间戳来保证资源不被缓存,我们可以自定义方法实现时间戳。
配置
Spring中的freemarker配置信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer"> <property name="templateLoaderPath" value="/WEB-INF/ftl/" /> <property name="defaultEncoding" value="UTF-8" /> <property name="freemarkerSettings"> <props> <prop key="template_update_delay">0</prop> <prop key="locale">zh_CN</prop> <prop key="default_encoding">UTF-8</prop> </props> </property> <property name="freemarkerVariables"> <map> <entry key="urlTimestamp" value-ref="urlTimesTampDirective" /> </map> </property> </bean>
|
实现代码
- 必须实现
freemarker.template.TemplateDirectiveModel
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| @Component("urlTimesTampDirective") public class UrlTimesTampDirective extends BaseDirective {
@SuppressWarnings("rawtypes") @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { String strTimestamp = ""; try { strTimestamp = String.valueOf(System.currentTimeMillis()) + getRandom(1000, 9999); Writer out = env.getOut(); out.write(strTimestamp); } catch (Exception ex) { ex.printStackTrace(); } }
private int getRandom(int min, int max) { Random random = new Random(); return Integer.parseInt(String.valueOf(random.nextInt(max) % (max - min + 1) + min)); } }
|
使用
<a href="http://code.skyheng.com?t=<@urlTimestamp />">我的博客</a>
<script src="${ctx}/resources/base/common.js?t=<@urlTimestamp/>"></script>
个人微信公众号 | 技术交流QQ群 |
|
|