欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

freemarker自定义标签

程序员文章站 2022-06-08 23:50:01
...

/**
* 自定义freemarker方法或函数,在此注入
*
* @author haojiabin
* @version $Revision: 1.0 $, $Date: 2010-5-12 下午02:37:39 $
*/
public class ExtendedFreemarkerManager extends FreemarkerManager {

@Override
protected Configuration createConfiguration(ServletContext servletContext)
throws TemplateException {
Configuration configuration = super.createConfiguration(servletContext);
configuration.setSharedVariable("enums", BeansWrapper
.getDefaultInstance().getEnumModels()); // 枚举类处理
configuration.setSharedVariable("statics", BeansWrapper
.getDefaultInstance().getStaticModels()); // 枚举类处理

configuration.setSharedVariable("datetime", new DatetimeMethod());
return configuration;
}
}




public class DatetimeMethod implements TemplateMethodModel {

private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

@SuppressWarnings("unchecked")
public Object exec(List args) throws TemplateModelException {
Date date = new Date();
String pattern = args.get(0).toString();
try {
return new SimpleDateFormat(pattern).format(date);
} catch (RuntimeException e) {
return new SimpleDateFormat(DEFAULT_PATTERN).format(date);
}
}
}


配置strut.xml
<constant name="struts.freemarker.manager.classname" value="net.zdsoft.havewin.common.util.ExtendedFreemarkerManager" />