Use the template to render freemarker

Recent projects to use, and for word template editing and rendering, so to use a template engine technology.

In the project, we use front-end rich text editor to display and preservation (and the same word format), the back-end using the freemarker rendering data. The front end, not to say, treatment is very simple, just a show, a save operation.

Background, template and need to get data, return to the front after rendering on display.

Currently realized the input string and the input file two forms. (20,180,409)

Freemark integration and use of technology are as follows:

1. introduced maven dependent

Copy the code
        <!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.23</version>
        </dependency>
Copy the code

2. Use of encapsulation tools utils

Copy the code
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 { 
            = New new StringTemplateLoader stringTemplateLoader StringTemplateLoader (); 
            stringTemplateLoader.putTemplate (name, tplStr); 
            cfg.setTemplateLoader (stringTemplateLoader); 
            Template Template = cfg.getTemplate (name, defaultCharacter); 
            the StringWriter the StringWriter new new OUT = (); 
            template.process (Data, OUT);   
            out.flush ();   
            Result = out.toString (); 
            the out.close (); 
        } the catch (Exception E) {   
            e.printStackTrace ();   
        }   
        return Result; 
    } 
    / ** 
     * after saving the template rendered to file 
     * @param templateFileDir template directory 
     * @param fileName template file name 
     * @param after targetFilePath rendered file name 
     * @param dataMap data
     @Return * 
     * / 
    public static Boolean renderingTemplateAndGenerateFile (templateFileDir String, 
            String fileName, String targetFilePath, the Map <String, Object> Datamap) { 
            Boolean = In Flag to true; 
            the try { 
                path // set the file directory   
                cfg.setDirectoryForTemplateLoading (new File ( templateFileDir)); // template path   
                // get the template   
                template template = cfg.getTemplate (fileName); 
                // set the output file name and save path   
                file the outFile = new new file (targetFilePath);  
                // the template data model and merge files generated code sets focus settings  
                BufferedWriter OUT = new new BufferedWriter (new 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);
    }

}
Copy the code

 

3. Unit Testing

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);
     }
}

 Results: Case number: AJ00000001 date: 2017-05-11 11:55:55 automatic acquisition date as follows: Description January 29, 2018: This is the description of ==========

template rendering is complete .

Guess you like

Origin www.cnblogs.com/toSeeMyDream/p/12381243.html
Recommended