Freemarker是一个比较知名Java模版引擎,使用人数众多,今天记录下使用Freemarker来生成静态文件,主要应用场景为页面静态化以及代码生成器中。
引入Maven依赖 目前最新的版本
1 2 3 4 5 <dependency >        <groupId > org.freemarker</groupId >         <artifactId > freemarker</artifactId >         <version > 2.3.26-incubating</version >  </dependency > 
开始编码 新建一个工具类,比如FreemarkerUtils,具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 private  static  Configuration cfg = null ;  private  Configuration getConfiguration() {       if  (null  == cfg) {            cfg = new  Configuration (Configuration.VERSION_2_3_26);                        cfg.setClassForTemplateLoading(this .getClass(), "/templates/" );                        cfg.setEncoding(Locale.getDefault(), "UTF-8" );                        cfg.setObjectWrapper(new  DefaultObjectWrapper ());                        cfg.setTemplateExceptionHandler(TemplateExceptionHandler                                            .IGNORE_HANDLER);        }        return  cfg; }     public  boolean createFile(String  templatePath, Map<String , Object> data,                                         String  outputPath) {        try  {                        Configuration cfg = getConfiguration();                        Template template = cfg.getTemplate(templatePath);                        Writer out = new  BufferedWriter (new  OutputStreamWriter (                          new  FileOutputStream (outputPath), "UTF-8" ));            template.process(data, out);            out.flush();            out.close();        } catch  (IOException | TemplateException e) {            return  false ;        }        return  true ; } 
在maven项目resources下创建templates文件夹,用于存放模版文件,然后新建一个test.ftl模版文件,即可根据这个文件来进行定制生成我们想要的静态文件。
测试 1 2 3 4 FreemarkerUtils f = new  FreemarkerUtils (); Map <String ,Object> data  = new  HashMap<>();data .put("name" ,"hello world" );f.createFile("test.ftl" ,data ,"D:\\test.ftl" ); 
直接运行即可,就会看到D盘下生成我们需要的静态文件了。