1. 编写函数
1
package
com.freemarker.test;
2
3 import java.text.SimpleDateFormat;
4 import java.util.Date;
5 import java.util.List;
6 import freemarker.template.TemplateMethodModel;
7 import freemarker.template.TemplateModelException;
8
9
10 public class SqlGetSysdateMethod implements TemplateMethodModel
11 {
12
13
14 public Object exec( List args ) throws TemplateModelException
15 {
16 // 得到函数第一个参数,得到的字符串两头会有引号,所以replace
17 String datePattern = (args.get( 0 ).toString()).replace( " ' " , "" );
18
19 Date date = new Date();
20 SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
21
22 return sdf.format( date );
23 }
24
25 }
2
3 import java.text.SimpleDateFormat;
4 import java.util.Date;
5 import java.util.List;
6 import freemarker.template.TemplateMethodModel;
7 import freemarker.template.TemplateModelException;
8
9
10 public class SqlGetSysdateMethod implements TemplateMethodModel
11 {
12
13
14 public Object exec( List args ) throws TemplateModelException
15 {
16 // 得到函数第一个参数,得到的字符串两头会有引号,所以replace
17 String datePattern = (args.get( 0 ).toString()).replace( " ' " , "" );
18
19 Date date = new Date();
20 SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
21
22 return sdf.format( date );
23 }
24
25 }
2.注册与使用
有两种方式:
(1).在模板文件中注册,在模板中使用
<#assign getSysdate= "package com.freemarker.test.SqlGetSysdateMethod"?new()>
<#assign curdate= getSysdate("yyyy-MM-dd"t)/>
(2).处理模板文件时注册
关键代码:
Map < String,Object > root = new HashMap < String, Object > ();
root.put( " getSysdate " , new StringLengthMethod());
Configuration config = new Configuration();
File file = new File(templatePath);
// 并加载模板文件
config.setDirectoryForTemplateLoading(file);
// 设置包装器,并将对象包装为数据模型
config.setObjectWrapper( new DefaultObjectWrapper());
// 获取模板,并设置编码方式,这个编码必须要与页面中的编码格式一致
Template template = config.getTemplate(templateName,templateEncoding);
// 合并数据模型与模板
template.process(root, out);