实际项目中使用freemaker做模板

在之前的一篇文章中项目中Spring结合Freemaker渲染网页,示例了使用freemaker来做spring mvc的视图处理。本文使用freemaker来处理系统外发消息时候的消息模板处理。比如用户后给用户发送激活邮件,用户修改密码后给用户发送提醒短信等,这些场景下都会使用到模板引擎。记得之前在杭研的时候,使用velocity来开发报文构件,freemaker作业也差不多。

设计

在项目中,模板保存在数据库中,notify_template(id,subject,content,memo),在一些功能模块的初始化中,将template_id传进去。最后,在交易处理的某个阶段,调用发送服务时,在发送服务中检索模板ID在和交易信息一起,生成完整的信息。

核心代码

public class FreeMarkerTemplateUtil {
    private static Log log = LogFactory.getLog(FreeMarkerTemplateUtil.class);
    private FreeMarkerTemplateUtil( )
    {}

    /**
     * 实用模板从数据库中取出为字符串
     * @param templateContent
     * @param paraMap
     * @return
     */
    public static String templateParser(String templateContent,Map<String, String> paraMap) {
        try {
            StringReader reader = new StringReader(templateContent);
            Template template;
            template = new Template("", reader, null);
            StringWriter out = new StringWriter();

            if (paraMap != null) {
                template.process(paraMap, out);

                String result = out.toString();
                if (log.isDebugEnabled()) {
                    log.debug("template content is:[" + result + "]");
                }
                return result;
            } else {
                return templateContent;
            }
        } catch (Exception e) {
            log.error(e);
            log.error("templateContent = " + templateContent + "\ncontent = "+ paraMap);
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 适合模板保存在本地目录
     * @param paramMap
     * @param templateLoadingDir
     * @param templateFilePath
     * @return
     * @throws IOException
     * @throws TemplateException
     */
    public static String processTemplate( Map< String, Object > paramMap,String templateLoadingDir, String templateFilePath ) throws IOException,
            TemplateException {
        if ( StringUtils.isBlank( templateLoadingDir ) ) {
            throw new TemplateException( "模板文件目录为空", Environment.getCurrentEnvironment( ) );
        }
        else if ( StringUtils.isBlank( templateFilePath ) ) {
            throw new TemplateException( "模板路径为空", Environment.getCurrentEnvironment( ) );
        }
        Configuration cfg = new Configuration( );
        cfg.setDirectoryForTemplateLoading( new File( templateLoadingDir ) );
        cfg.setDefaultEncoding( CharEncoding.UTF_8 );
        Template template = cfg.getTemplate( templateFilePath );

        if ( paramMap == null || paramMap.isEmpty( ) )
        {
            return template.toString( );
        }
        return StringUtils.trimToEmpty( FreeMarkerTemplateUtils.processTemplateIntoString(template, paramMap ) );
    }
}
//简单调用
public static void  main(String[] args)throws Exception{
        NotifyTemplate notifyTemplate = new NotifyTemplate();
        //
        notifyTemplate.setContent("orderNo=${order_no}&status=${status}&respCode=${resp_code}");
        notifyTemplate.setId(400L);

        Map<String, String> content= new HashMap<>();
        content.put("order_no","_123456");
        content.put("status","1");
        content.put("resp_code","000000");
        System.out.println(FreeMarkerTemplateUtil.templateParser( notifyTemplate.getContent(),content));

        String templateLoadingDir="E:\\";
        String templateFilePath="template.txt";
        Map<String, Object> content2= new HashMap<>();
        content2.put("order_no","_123456");
        content2.put("status","1");
        content2.put("resp_code","000000");
        System.out.println(FreeMarkerTemplateUtil.processTemplate(content2, templateLoadingDir,templateFilePath));
    }

总结

FreeMaker有国际化功能,在Configuration中传入Locale即可,它就会给要查找的模板增加后缀,优先使用有后缀的模板,比如传入的模板名为temp.txt,而Locale.ENGLISH,它就会去找temp_en.txt。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值