JAVA FreeMarker工具類


FreeMarkerUtil.java

 1 package pers.kangxu.datautils.utils;
 2 
 3 import java.io.File;
 4 import java.io.StringWriter;
 5 import java.util.Map;
 6 
 7 import pers.kangxu.datautils.common.Constants;
 8 
 9 import freemarker.template.Configuration;
10 import freemarker.template.Template;
11 
12 /**
13  * 
14  * <b>
15  *    FreeMarkerUtil 模板工具
16  * </b>
17  * @author kangxu
18  *
19  */
20 public class FreeMarkerUtil {
21     
22     /**
23      * 
24      * TODO
25      * <br>
26      * @author kangxu2 2016-11-23
27      *
28      * @param fltFile  flt文件名
29      * @param templatePath flt文件路徑   src/template
30      * @param datas 數據集合
31      * @return
32      */
33     public static String geneFileStr(String fltFile,String templatePath,Map<String, Object> datas){
34         
35         Configuration cfg = new Configuration();
36         try {
37             cfg.setDirectoryForTemplateLoading(new File(templatePath));
38             Template template = cfg.getTemplate(fltFile,Constants.ENCODING);
39             template.setEncoding(Constants.ENCODING);
40             
41             StringWriter out = new StringWriter();  
42             
43             template.process(datas, out);  
44             
45             out.flush();
46             out.close();
47             
48             return out.getBuffer().toString();
49             
50             
51         } catch (Exception e) {
52             e.printStackTrace();
53         } 
54         
55         return null;
56         
57     }
58  
59 }

 使用方式 FreeMarkerUtilTester.java

 1 package pers.kangxu.datautils.test;
 2 
 3 import java.util.HashMap;
 4 import java.util.Map;
 5 
 6 import pers.kangxu.datautils.common.verifycode.BuildVerifyCode;
 7 import pers.kangxu.datautils.utils.FreeMarkerUtil;
 8 
 9 public class FreeMarkerUtilTester {
10 
11     public static void main(String[] args) {
12         Map<String, Object> datas = new HashMap<String, Object>();
13         datas.put("code", BuildVerifyCode.generateVerifyCode(4));
14         System.out.println(FreeMarkerUtil.geneFileStr("sms.flt","template",datas));
15     }
16 }

sms.flt

 1 您的驗證碼是:${code}。請不要把驗證碼泄露給其他人。 

運行結果

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM