品牌

spring mvc中使用velocity 做邮件模板设置日期格式的方法

首先需要在spring的配置文件中配置

<bean id="velocityEngine" class="org.springframework.ui.velocity.VelocityEngineFactoryBean">

      <property name="velocityProperties">

         <value>

          resource.loader=class

          class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader

         </value>

      </property>

   </bean>

这样配置之后就可以解析模板文件了,但是无法格式化日期,数字,要做格式化需要把DateTool和NumberTool的实例放到Model中如下代码

/**

     * 生成模板内容

     * @param vmTemplatePath 模板资源文件的路径

     * @param modelMap 模板数据

     * @return

     */

    private String generateContentImpl(String vmTemplatePath,Map<String,Object> modelMap) {        

        if(modelMap.containsKey("dateTool")){

            throw new ArgumentException("modelMap cannot contains dateTool ,dateTool is used to format date function");

        }  

        if(modelMap.containsKey("numberTool")){

            throw new ArgumentException("modelMap cannot contains numberTool ,numberTool is used to format number function");

        }

        DateTool dateTool = new DateTool();

        modelMap.put("dateTool",dateTool);

        NumberTool numberTool = new NumberTool();

        modelMap.put("numberTool", numberTool);

        String text = VelocityEngineUtils.mergeTemplateIntoString(

                velocityEngine, vmTemplatePath, "UTF-8",modelMap);

        return text;

    }

当然需要引用velocity-tools jar包。

原文来自商网EDM(电子邮件营销:http://edm.ishang.net)    转载请注明出处。
市场部网编辑部
市场部网内容中心官方账号,专注消费品牌营销的一线案例追踪与拆解,长期关注节日营销、跨界联名与品牌年轻化议题。稿件均经编辑部核校,只发经过交叉验证的行业信息。