• [Freemarker]自定义时间戳函数


    使用freemarker的web项目经常需要用在Url后面加上时间戳来保证资源不被缓存,我们可以自定义方法实现时间戳。

    先看freemarker配置信息:

    <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="urlTimestampMethod" />
                </map>
            </property>
        </bean>
        <bean id="urlTimestampMethod" class="com.xxx.UrlTimestampMethodModel" />

    下面看UrlTimestampMethodModel是如何实现的:

    //必须实现freemarker.template.TemplateDirectiveModel
    @Component public class UrlTimestampMethodModel implements TemplateDirectiveModel { @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); } catch (Exception ex) { } env.getOut().write(strTimestamp); } 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://abc.com?t=<@urlTimestamp />">123</a>
  • 相关阅读:
    IOS-github优秀开源项目大全
    IOS-UISearchBar
    iOS-资源大全
    基于java的https双向认证,android上亦可用
    三重Des对称加密在Android、Ios 和Java 平台的实现
    Python练习—文件
    C语言文件进阶操作
    C语言文件基本操作
    二叉树模板
    单源最短路——Dijkstra算法
  • 原文地址:https://www.cnblogs.com/xiaoyangjia/p/3945108.html
Copyright © 2020-2023  润新知