首页 > 技术文章 > FreeMarker

wxguo 2020-10-14 14:04 原文

页面静态化

  • 介绍:页面静态化其实就是将原来的动态网页(例如通过ajax请求动态获取数据库中的数据并展示的网页)改为通过静态化技术生成的静态网页,这样用户在访问网页时,服务器直接给用户响应静态html页面,没有了动态查询数据库的过程。
  • 作用:为数据库减压并提高系统运行性能。
  • 常用技术:Freemarker、thymeleaf等。

Freemarker

  • 介绍:FreeMarker 是一个用 Java 语言编写的模板引擎,它基于模板来生成文本输出。FreeMarker与 Web 容器无关,即在 Web 运行时,它并不知道 Servlet 或 HTTP。它不仅可以用作表现层的实现技术,而且还可以用于生成 XML,JSP 或 Java 等。

快速入门

环境搭建

<dependency> 
      <groupId>org.freemarker</groupId> 
      <artifactId>freemarker</artifactId> 
      <version>2.3.23</version>
</dependency>

入门案例

public class FreeMarker {
    public static void main(String[] args) throws IOException, TemplateException {
        //1.创配置类
        Configuration configuration = new Configuration(Configuration.getVersion());
        //2.配置模板所在的路径
        configuration.setDirectoryForTemplateLoading(new File("F:\\"));
        //3.设置字符集
        configuration.setDefaultEncoding("utf-8");
        //4.加载模板
        Template template = configuration.getTemplate("ftl.ftl");
        //5.创建数据模型
        Map map = new HashMap();
        map.put("name","张三");
        map.put("message","今天是2020年10月14日");
        map.put("flag",true);

        List list = new ArrayList();

        Map map1 = new HashMap();
        map1.put("name","苹果");
        map1.put("price","100");

        Map map2 = new HashMap();
        map2.put("name","香蕉");
        map2.put("price","200");

        list.add(map1);
        list.add(map2);

        map.put("testList",list);

        //6.创建Writer对象
        Writer writer = new FileWriter(new File("f:\\ftl.html"));
        //7.输出
        template.process(map,writer);
        //8.关闭资源
        writer.close();
    }
}

FreeMarker指令

<body>

	${name}你好,${message}

	<#assign linkman="赵四">
	联系人:${linkman}
	
	<#include "ftl1.ftl"/>
	
	<#assign info={'phone':155555555,"address":"北京昌平"}>
	电话:${info.phone}
	地址:${info.address}
	
	<#if flag>
		实名成功
	<#else>
		实名失败
	</#if>

        <#list testList as list>
		name:${list.name}
		price:${list.price}
	</#list>
</body>

推荐阅读