【FreeMarker】基础学习和Spring整合使用

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

2.Freemarker的使用方法

public class TestFreemarker {
    @Test
    public void test01() throws Exception{
        //第一步:把freemarker的jar包添加到工程中freemarker-2.3.23.jar
        //第二步:freemarker的运行不依赖web容器,可以在java工程中运行。创建一个测试方法进行测试。
        //第三步:创建一个Configration对象
        Configuration configuration = new Configuration(Configuration.getVersion());
        //第四步:告诉config对象模板文件存放的路径。
        configuration.setDirectoryForTemplateLoading(new File("G:\\eclipse-jee-mars-2\\workspace\\freemarkerDemo\\src\\main\\webapp\\WEB-INF\\ftl"));
        //第五步:设置config的默认字符集。一般是utf-8
        configuration.setDefaultEncoding("UTF-8");
        //第六步:从config对象中获得模板对象。需要制定一个模板文件的名字。
        Template template = configuration.getTemplate("first.ftl");
        //创建模板需要的数据集。可以是一个map对象也可以是一个pojo,把模板需要的数据都放入数据集。
        Map root = new HashMap<>();
        root.put("hello", "hello freemarker!");
        //第八步:创建一个Writer对象,指定生成的文件保存的路径及文件名。
        Writer writer = new FileWriter(new File("G:\\eclipse-jee-mars-2\\workspace\\freemarker\\hello.html"));
        //第九步:调用模板对象的process方法生成静态文件。需要两个参数数据集和writer对象。
        template.process(root, writer);
        //第十步:关闭writer对象。
        writer.flush();
        writer.close();
    }
}

模版first.ftl内容为${hello},运行结果如下  

这里写图片描述

3.Freemarker模板的基本写法

  • 3.1 简单数据类型数据
    使用EL表达式${hello},如上所示。
  • 3.2 包装数据类型
@Test
public void Test02() throws Exception{
    ...
    Map root = new HashMap<>();
    root.put("title", "包装数据类型");
    root.put("student", new Student("1", "张三", "上海"));
    ...
}

模版second.ftl内容为
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>${title}</title>
</head>
<body>
    <label>学号:</label>${student.id}<br>
    <label>姓名:</label>${student.name}<br>
    <label>住址:</label>${student.address}<br>
</body>
</html> 

这里写图片描述

  • 3.3 历遍集合/数组
@Test
public void Test02() throws Exception{
    ... 
    Map root = new HashMap<>();
    List<Student> studentList = new ArrayList<Student>();
    studentList.add(new Student("2", "李四2", "北京"));
    studentList.add(new Student("3", "李四3", "北京"));
    studentList.add(new Student("4", "李四4", "北京"));
    studentList.add(new Student("5", "李四5", "北京"));
    studentList.add(new Student("6", "李四6", "北京"));
    root.put("studentList", studentList);
    ...
}   
模版second.ftl内容为
<table border="1">
    <#list studentList as s>
        <#if s_index%2 == 0>
        <tr style="color:red">
        <#else>
        <tr>
        </#if>
            <td>${s_index}</td>    
            <td>${s.id}</td>
            <td>${s.name}</td>
            <td>${s.address}</td>
        </tr>
    </#list>
</table>

这里写图片描述

  • 3.4 获得当前迭代的索引
获取当前选代的索引
<#list studentList as s>
    ${s_index}
</#list>
  • 3.5 模板中判断条件
逻辑运算符(==   !=   ||   &&)
<#if 判断条件>
<#else>
</#if>
  • 3.6 日期类型格式化
默认格式
1:date
${cur_time?date}
2:datetime
${cur_time?datetime}
3:time
${cur_time?time}
自定义格式
${cur_time?string("yyyy-MM-dd HH:mm:ss")} 

@Test
public void Test02() throws Exception{
    ... 
    root.put("curDate", new Date());
    ...
}
模版second.ftl内容为
当前日期:${curDate?date}<br/>
当前日期:${curDate?time}<br/>
当前日期:${curDate?datetime}<br/>
当前日期:${curDate?string("yyyy/MM/dd HH:mm:ss")}<br/>

这里写图片描述

  • 3.7 处理null值
@Test
public void Test02() throws Exception{
    ... 
    root.put("cur_Date", null);
    root.put("val1", null);
    root.put("val2", "");
    ...
}
模版second.ftl内容为
<#if cur_Date ??>
当前日期:${cur_Date?string("yyyy/MM/dd HH:mm:ss")}<br/>
<#else>
cur_Date属性为null<br/>
</#if>
获取null:${val1!"我是默认值"}<br/>
获取"":${val2!}<br/>

这里写图片描述

  • 3.8 include引入页面
将另一个页面引入本页面时可用以下命令完成
<#include "first.ftl">

@Test
public void Test02() throws Exception{
    ... 
    root.put("hello", "first中的hello");
    ...
}
模版second.ftl内容为
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <#include "first.ftl">
    <title>${title}</title>
</head>
<body>
</body>
</html>

这里写图片描述

4.spring中使用freemarker

1.使用freemarker整合spring,把Configuration交给spring容器管理,依赖的jar包:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>4.1.3.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.23</version>
</dependency>

2.spring配置文件内容
<bean id="freemarkerConfig"
    class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
    <property name="templateLoaderPath" value="/WEB-INF/ftl/" />
    <property name="defaultEncoding" value="UTF-8" />
</bean>

3.注入FreeMarkerConfigurer 
@Autowired
private FreeMarkerConfigurer freeMarkerConfigurer;
...
//生成静态网页
Configuration configuration = freeMarkerConfigurer.getConfiguration();
Template template = configuration.getTemplate("demo.ftl");
...
发布了64 篇原创文章 · 获赞 10 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章