Java架构技术进阶SpringBoot精选

SpringBoot整合Apache FreeMarker(一)

2020-02-15  本文已影响0人  程就人生

天天写增删改查,终于写腻歪了。重复的劳动,枯燥而烦闷,让人打不起精神,更浪费时间,本来可以把时间用来做更有意义的事情上去的。那么,怎么解决增删改查平淡而又枯燥的工作呢?有小弟当然好,如果没有,也别担心,用工具类来解决这个问题便好,这便是Apache的FreeMarker。

Apache FreeMarker是一款模板引擎,基于模板和要改变的数据,来生成文本(HTML网页,电子邮件,配置文件,源代码等)的Java类库。模板所使用的的语音是FTL(FreeMarker template langeuage)。接下来就看看SpringBoot是如何整合FreeMarker的吧。

首先,使用Spring Starter Project搭建一个项目,把SpringBoot整合FreeMarker的模板引入;

<!--springboot整合freemarker-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<!--apache的commons-io,文件操作工具类-->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>
<!--测试-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>         
</dependency>

这里还用到了apache的commons-io,用于替换后的文本生成,也需要引入一下;

第二步,简单的模板文件;

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Hello World!</title>
</head>
<body>
Hello,${name}!
</body>
</html>

模板文件放在templates文件夹下,和测试代码里面获取模板路径必须保持一致;

第三步,测试代码;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.ResourceUtils;

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

/**
 * Freemarker生成文件测试
 * @author 程就人生
 * @date 2020年2月15日
 */
public class FreemarkerTest {
    
    private Logger log = LoggerFactory.getLogger(FreemarkerTest.class);
    
    /**
     * 模板文件静态化
     */
    @Test
    public void testGenerateHtml(){       
        try {           
            // 创建配置类
            Configuration configuration = new Configuration(Configuration.getVersion());
            //获取模板路径
            URL url = ResourceUtils.getURL("classpath:templates");
            //加载模板路径
            configuration.setDirectoryForTemplateLoading(new File(url.getPath()));
            // 设置字符集
            configuration.setDefaultEncoding("utf-8");
            // 加载模板
            Template template = configuration.getTemplate("demo.ftl");
            // 数据模型
            Map<String,Object> map = new HashMap<>();
            map.put("name", "静态化测试,啦啦啦啦");
            // 静态化
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
            // 将替换后的文件内容转成输入流
            InputStream inputStream = IOUtils.toInputStream(content);
            // 再用文件输出流输出文件
            FileOutputStream fileOutputStream = new FileOutputStream(new File("src/main/resources/templates/demo.html"));
            int copy = IOUtils.copy(inputStream, fileOutputStream);
            log.info(copy+"");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 使用模板字符串静态化
     */
    @Test
    public void testGenerateHtmlByString(){        
        try {
            // 创建配置类
            Configuration configuration = new Configuration(Configuration.getVersion());
            // 设置字符集
            configuration.setDefaultEncoding("utf-8");
            // 测试模板内容
            String templateString="" +
                    "<html>\n" +
                    "<meta charset=\"utf-8\">\n" +
                    " <head></head>\n" +
                    " <body>\n" +
                    " hi:${name}\n" +
                    " </body>\n" +
                    "</html>";
            // 模板加载器
            StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
            stringTemplateLoader.putTemplate("template",templateString);
            configuration.setTemplateLoader(stringTemplateLoader);
            // 得到模板
            Template template = configuration.getTemplate("template");
            // 数据模型
            Map<String,Object> map = new HashMap<>();
            map.put("name","使用模板字符串静态化,lalallllll");
            // 静态化
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
            // 将替换后的文件内容转成输入流
            InputStream inputStream = IOUtils.toInputStream(content);
            // 输出文件
            FileOutputStream fileOutputStream = new FileOutputStream(new File("src/main/resources/templates/demo1.html"));
            int copy = IOUtils.copy(inputStream, fileOutputStream);
            log.info(copy+"");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }        
    }
}

第四步,选中测试文件运行;

测试结果-1
测试结果-2

最后总结
这只是FreeMarker的简单应用,要想生成增删改查的页面,还是需要把模板文件好好写一写,做一款通用的增删改查的模板出来。这样,在日后使用的时候,就方便多了,代码生成后,只需要修改一下就完工了,想想就很兴奋。还等什么,快写一个通用的模板吧。

参考文档:
https://freemarker.apache.org/
http://freemarker.foofun.cn/index.html

上一篇 下一篇

猜你喜欢

热点阅读