Freemarker模板文件返回字符串
首先,先创建一个ftl文件:
Html代码
<div style="width:100%;font-size:12px;">Hello ${name}(${getUserAge(name)})</div>
之后,创建一个java应用程序类:
Java代码
package freemarker; import java.io.File; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.HashMap; import java.util.Locale; import java.util.Map; import freemarker.template.Configuration; import freemarker.template.DefaultObjectWrapper; import freemarker.template.Template; import freemarker.template.TemplateException; /** * * @Desc 获取FTL文件生成的字符串,以供调用 * @author xujp1 * @version Revision: 1.00 Date: May 9, 2012 */ public class GenerateStringFromFtl { private static Configuration conf = null; public static void main(String args[]) { conf = new Configuration(); try { conf.setDirectoryForTemplateLoading(new File("WebRoot/WEB-INF/template")); } catch (IOException e) { e.printStackTrace(); } conf.setObjectWrapper(new DefaultObjectWrapper()); conf.setLocale(Locale.CHINA); conf.setSharedVariable("getUserAge", new GetUserAge());//自定义方法供调用 conf.setDefaultEncoding("utf-8"); conf.setClassicCompatible(true);//处理空值为空字符串 String tempReturn = ""; Map<String, Object> root = new HashMap<String, Object>(); String name = "xujp1"; root.put("name", name); try { tempReturn = generateHtmlFromFtl(root, "hellouser.ftl"); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); } System.out.println(tempReturn); } public static String generateHtmlFromFtl(Object root, String tempPath) throws IOException, TemplateException { Template temp = conf.getTemplate(tempPath); Writer out = new StringWriter(2048); temp.process(root, out); return out.toString(); } }
由于有用到自定义方法,因此在建个方法类:
Java代码
package freemarker; import java.util.List; import freemarker.template.SimpleScalar; import freemarker.template.TemplateMethodModel; import freemarker.template.TemplateModelException; /** * * @Desc freemarker中使用的方法,根据传入的参数返回相应的值 * @author xujp1 * @version Revision: 1.00 Date: May 9, 2012 */ public class GetUserAge implements TemplateMethodModel { /* (non-Javadoc) * @see freemarker.template.TemplateMethodModel#exec(java.util.List) */ @SuppressWarnings("unchecked") @Override public Object exec(List args) throws TemplateModelException { if(args.size() != 1) { throw new TemplateModelException("Wrong arguments!"); } int age = 0; if("xujp1".equalsIgnoreCase((String)args.get(0))) age = 25; else age = 24; return new SimpleScalar(String.valueOf(age)); } }
运行后,得到所要的结果
相关推荐
Lzs 2020-10-23
聚合室 2020-11-16
零 2020-09-18
Justhavefun 2020-10-22
jacktangj 2020-10-14
ChaITSimpleLove 2020-10-06
Andrea0 2020-09-18
周游列国之仕子 2020-09-15
afanti 2020-09-16
88234852 2020-09-15
YClimb 2020-09-15
风雨断肠人 2020-09-04
卖口粥湛蓝的天空 2020-09-15
stulen 2020-09-15
pythonxuexi 2020-09-06
abfdada 2020-08-26
梦的天空 2020-08-25