使用freemarker对模板进行渲染

最近项目中使用到了,对word模板进行编辑和渲染,所以使用到了模板引擎技术。

在项目中,我们前端使用的富文本编辑器,进行展示和保存(和word格式一致),后端采用了freemarker进行数据的渲染。前端,就不多说了,处理很简单,只有一个展示,一个保存操作。

后台,需要获取模板和数据,进行渲染后返回到前台,进行展示。

目前实现了输入字符串和输入文件两种形式。(20180409)

freemark技术的整合和使用如下:

1.引入maven依赖

复制代码
        <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>
复制代码

2.封装为utils工具类使用

复制代码
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.PropertyConfigurator;

import com.winning.Application;
import com.winning.polaris.admin.service.impl.UpgradeServiceImpl;
import com.winning.polaris.comm.util.LogUtil;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;

public class FreemarkerUtils {
    private static LogUtil logger = LogUtil.getInstance(UpgradeServiceImpl.class);
    private static String defaultCharacter = "UTF-8";
    private static Configuration cfg;
    private  FreemarkerUtils() {
    }
    static {
        cfg = new Configuration(Configuration.getVersion());
        cfg.setDefaultEncoding(defaultCharacter);
        cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
    }
    /**
     * 对模板进行渲染
     * @param data 数据Map
     * @param tplStr 模板
     * @return
     */
    public static  String generateString(
            Map<String, Object> data,  String tplStr) {
        String result = null;
        String name="myStrTpl";
        try { 
            StringTemplateLoader stringTemplateLoader= new StringTemplateLoader();
            stringTemplateLoader.putTemplate(name, tplStr);
            cfg.setTemplateLoader(stringTemplateLoader); 
            Template template = cfg.getTemplate(name,defaultCharacter);
            StringWriter out = new StringWriter(); 
            template.process(data, out);  
            out.flush();  
            result= out.toString();
            out.close(); 
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return result;
    }
    /**
     * 将模板渲染以后保存到文件
     * @param templateFileDir 模板目录
     * @param fileName 模板文件名称
     * @param targetFilePath 渲染后文件名称
     * @param dataMap 数据
     * @return
     */
    public static boolean renderingTemplateAndGenerateFile(String templateFileDir,
            String fileName,String targetFilePath,Map<String, Object> dataMap){
            boolean flag=true;
            try {
                // 设置文件所在目录的路径  
                cfg.setDirectoryForTemplateLoading(new File(templateFileDir));//模板路径  
                // 获取模版  
                Template template = cfg.getTemplate(fileName);
                // 设置输出文件名,和保存路径  
                File outFile = new File(targetFilePath);
                // 将模板和数据模型合并生成文件 重点设置编码集  
                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));  
                // 生成文件  
                template.process(dataMap, out);  
                // 关闭流  
                out.flush();  
                out.close();
            } catch (Exception e) {
                logger.error("生产模板文件失败!",e);
                flag=false;
            }
        return flag;
    }
    
    
    public static void main(String[] args) {
        PropertyConfigurator.configure(Application.class.getClassLoader().getResourceAsStream("config" + File.separator + "log4j.properties"));

        Map<String,Object> dataMap=new HashMap<String, Object>();
        dataMap.put("APP_HOME", "c:/test/appHome");
        //F:\freemark
        boolean renderingTemplateAndGenerateFile = renderingTemplateAndGenerateFile("F:\\freemark\\", "temp.txt",
                "F:\\freemark\\temp.bat",dataMap);
        
        System.out.println(renderingTemplateAndGenerateFile);
    }

}
复制代码

3.单元测试

public  class  FreemarkerUtilsTest extends  TestCase {
     
     public  void  generateStringTest(){
         
         Map<String,Object> map= new  HashMap<>();
         map.put( "date" , "2017-05-11 11:55:55" );
         map.put( "caseNo" , "AJ00000001" );
         map.put( "descrip" , "这是描述信息==========" );
         String template= "案件编号为:${caseNo!}   "
                 + " 日期为:${date!} "
                 + " 自动获取日期为:${ .now?string('yyyy年MM月dd日')}"
                 + "描述:${descrip!}" ;
         String generateString = FreemarkerUtils.generateString(map, template);
         System.out.println( "------" );
         System.out.println(generateString);
     }
}

 结果:案件编号为:AJ00000001    日期为:2017-05-11 11:55:55  自动获取日期为:2018年01月29日描述:这是描述信息==========

模板渲染完成。

猜你喜欢

转载自www.cnblogs.com/toSeeMyDream/p/12381243.html