freemarker 笔记

Posted wenteryan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了freemarker 笔记相关的知识,希望对你有一定的参考价值。

什么是 freemarker

FreeMarker是一个基于Java的模板引擎,最初专注于使用MVC软件架构生成动态网页。但是,它是一个通用的模板引擎,不依赖于servlets或HTTP或html,因此它通常用于生成源代码,配置文件或电子邮件。

使用场景

为了提高页面的访问速度,需要把页面静态化,使用 Freemarker 实现网页静态化。

常用的使用方法

1)访问 map 中的 key

$key

2)访问 pojo 中的属性

Student 对象。学号、姓名、年龄

$pojo.property

3)取集合中的数据

集合大小:$studentList?size<br>
遍历集合:<br>
<table>
    <tr><td>学号</td><td>姓名</td><td>年龄</td></tr>
     <#list studentList as student>
     <tr><td>$student.studentNo</td><td>$student.name</td><td>$student.age</td></tr>
     </#list>
</table>

4)取循环中的下标

<table>
    <tr><td>序号</td><td>学号</td><td>姓名</td><td>年龄</td></tr>
     <#list studentList as student>
     <tr><td>$student_index+1</td><td>$student.studentNo</td><td>$student.name</td><td>$student.age</td></tr>
     </#list>
</table>

5)判断

<table>
    <tr><td>序号</td><td>学号</td><td>姓名</td><td>年龄</td></tr>
     <#list studentList as student>
         <#if student_index % 2 == 0>
         <tr bgcolor="#556b2f">
         <#else>
         <tr bgcolor="#cd5c5c">
         </#if>
     <td>$student_index+1</td><td>$student.studentNo</td><td>$student.name</td><td>$student.age</td></tr>
     </#list>
</table>

6)日期类型格式化

当前日期:$date?date<br>
当前时间:$date?time<br>
当前日期和时间:$date?datetime<br>
自定义日期格式:$date?string("yyyy-MM-dd HH:mm:ss")<br>

7)Null 值的处理

<#list studentList as student>
$student_index
</#list>

8)Include 标签

<#include "footer.ftl"/>

9)处理Json字符串转对象

<table>
    <tr><td>序号</td><td>学号</td><td>姓名</td><td>年龄</td></tr>
    <#assign jsons = jsonList?eval>
     <#list jsons as student>
         <#if student_index % 2 == 0>
         <tr bgcolor="#556b2f">
         <#else>
         <tr bgcolor="#cd5c5c">
         </#if>
     <td>$student_index+1</td><td>$student.studentNo</td><td>$student.name</td><td>$student.age</td></tr>
     </#list>
</table>

Freemarker 整合 spring

引入jar包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javazhan</groupId>
  <artifactId>freemaker-spring-demo</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>freemaker-spring-demo Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <properties>
    <spring.version>4.2.7.RELEASE</spring.version>
    <freemaker.version>2.3.27-incubating</freemaker.version>
  </properties>
  <dependencies>
    <!-- spring start -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>$spring.version</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>$spring.version</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>$spring.version</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>$spring.version</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>$spring.version</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>$spring.version</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>$spring.version</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>$spring.version</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>$spring.version</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>$spring.version</version>
    </dependency>
    <!-- spring end -->

      <!-- 添加Servlet支持 -->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
      </dependency>

      <dependency>
          <groupId>javax.servlet.jsp</groupId>
          <artifactId>javax.servlet.jsp-api</artifactId>
          <version>2.3.1</version>
      </dependency>

    <dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>$freemaker.version</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>1.7.9</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jul-to-slf4j</artifactId>
      <version>1.7.6</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>jcl-over-slf4j</artifactId>
      <version>1.7.6</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.2</version>
    </dependency>
  </dependencies>
  <build>
    <finalName>freemaker-spring-demo</finalName>
  </build>
</project>

添加配置
web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         id="WebApp_ID" version="2.5">

      <display-name>Archetype Created Web Application</display-name>
      
      <!-- 编码过滤器 -->
      <filter>
            <filter-name>encodingFilter</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                  <param-name>encoding</param-name>
                  <param-value>UTF-8</param-value>
            </init-param>
      </filter>
      <filter-mapping>
            <filter-name>encodingFilter</filter-name>
            <url-pattern>/*</url-pattern>
      </filter-mapping>

      <!-- 添加对springmvc的支持 -->
      <servlet>
            <servlet-name>springMVC</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                  <param-name>contextConfigLocation</param-name>
                  <param-value>classpath:spring/springmvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
            <servlet-name>springMVC</servlet-name>
            <url-pattern>*.html</url-pattern>
      </servlet-mapping>
</web-app>

springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">

    <context:component-scan base-package="com.javazhan.controller" />
    <mvc:annotation-driven />

    <!-- 配置freeMarker视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.freemarker.FreeMarkerView"/>
        <property name="contentType" value="text/html; charset=utf-8"/>
        <property name="cache" value="true"/>
        <property name="prefix" value="" /><!-- 上面已经配了,这里就不用配啦 -->
        <property name="suffix" value=".ftl" />
    </bean>

    <!-- 配置freemarker -->
    <bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="templateLoaderPath" value="classpath:ftl/" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
</beans>

模板 hello.ftl

<!DOCTYPE>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>FreeMarker Demo</title>
</head>
<body>
</body>
1)访问 map 中的 key<br>
$hello<br>

2)访问 pojo 中的属性<br>
$student.name<br>

3)取集合中的数据<br>
集合大小:$studentList?size<br>
遍历集合:<br>
<table>
    <tr><td>学号</td><td>姓名</td><td>年龄</td></tr>
     <#list studentList as student>
     <tr><td>$student.studentNo</td><td>$student.name</td><td>$student.age</td></tr>
     </#list>
</table>

4)取循环中的下标<br>
<table>
    <tr><td>序号</td><td>学号</td><td>姓名</td><td>年龄</td></tr>
     <#list studentList as student>
     <tr><td>$student_index+1</td><td>$student.studentNo</td><td>$student.name</td><td>$student.age</td></tr>
     </#list>
</table>

5)判断<br>
<table>
    <tr><td>序号</td><td>学号</td><td>姓名</td><td>年龄</td></tr>
     <#list studentList as student>
         <#if student_index % 2 == 0>
         <tr bgcolor="#556b2f">
         <#else>
         <tr bgcolor="#cd5c5c">
         </#if>
     <td>$student_index+1</td><td>$student.studentNo</td><td>$student.name</td><td>$student.age</td></tr>
     </#list>
</table>

6)日期类型格式化<br>
当前日期:$date?date<br>
当前时间:$date?time<br>
当前日期和时间:$date?datetime<br>
自定义日期格式:$date?string("yyyy-MM-dd HH:mm:ss")<br>

7)Null 值的处理<br>
null值的处理:$list!"list 为 null"<br>
null值的处理:
<#if list2??>
    list2 不为 null
<#else>
    list2 为 null
</#if>

<br>
8)Include 标签
<#include "footer.ftl"/>

9)处理Json字符串转对象<br>
<table>
    <tr><td>序号</td><td>学号</td><td>姓名</td><td>年龄</td></tr>
    <#assign jsons = jsonList?eval>
     <#list jsons as student>
         <#if student_index % 2 == 0>
         <tr bgcolor="#556b2f">
         <#else>
         <tr bgcolor="#cd5c5c">
         </#if>
     <td>$student_index+1</td><td>$student.studentNo</td><td>$student.name</td><td>$student.age</td></tr>
     </#list>
</table>
</html>

模板 footer.ftl

<p>这是个footer @ 版权归 <a href="http://yandongquan.xin">yandongquan个人博客</a></p>

模板 comment_template.ftl

<table>
    <tr><td>学号</td><td>姓名</td><td>年龄</td></tr>
     <#list studentList as student>
     <tr><td>$student.studentNo</td><td>$student.name</td><td>$student.age</td></tr>
     </#list>
</table>

生成静态文件 HtmlGenController.java

package com.javazhan.controller;

import com.google.gson.Gson;
import com.javazhan.pojo.Student;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @Author: yandq
 * @Description:
 * @Date: Create in 17:48 2018/3/22
 * @Modified By:
 */
@RestController
public class HtmlGenController 

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @RequestMapping("/genhtml/id")
    public String genHtml(@PathVariable("id") String id)throws Exception 
        // 1、从 spring 容器中获得 FreeMarkerConfigurer 对象。
        // 2、从 FreeMarkerConfigurer 对象中获得 Configuration 对象。
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        // 3、使用 Configuration 对象获得 Template 对象
        Template template = configuration.getTemplate("hello.ftl");
        // 4、创建数据集
        Map<String, Object> root = new HashMap<String, Object>();
        // 1)访问 map 中的 key
        root.put("hello", "hello freemarker");

        // 2)访问 pojo 中的属性
        Student student = new Student();
        student.setStudentNo("10001");
        student.setName("张三");
        student.setAge(23);
        root.put("student", student);

        // 3)取集合中的数据
        List<Student> list = new ArrayList<Student>();
        Student student1 = new Student();
        student1.setStudentNo("10001");
        student1.setName("张三");
        student1.setAge(23);
        list.add(student1);
        Student student2 = new Student();
        student2.setStudentNo("10002");
        student2.setName("张三2");
        student2.setAge(24);
        list.add(student2);

        Student student3 = new Student();
        student3.setStudentNo("10003");
        student3.setName("张三3");
        student3.setAge(21);
        list.add(student3);

        root.put("studentList", list);

        // 6)日期类型格式化
        root.put("date", new Date());

        // 7)Null 值的处理
        root.put("list", null);

        // 9)处理Json字符串转对象
        root.put("jsonList", new Gson().toJson(list));

        // 5、创建输出文件的 Writer 对象。
        Writer out = new BufferedWriter( new OutputStreamWriter( new FileOutputStream("D:/Work/Workspaces/IdeaProjects/Git/JavaStudyDemo/freemaker-spring-demo/src/main/resources/html/GOODS"+id+".html"), "UTF-8"));
        // 下面的会乱码
//        Writer out = new FileWriter(new File("D:/Work/Workspaces/IdeaProjects/Git/JavaStudyDemo/freemaker-spring-demo/src/main/resources/html/GOODS"+id+".html"));
        // 6、调用模板对象的 process 方法,生成文件。
        template.process(root, out);
        // 7、关闭流。
        out.flush();
        out.close();
        return "OK";
    

    @RequestMapping("/comment")
    public void genHtml(HttpServletResponse response)throws Exception 
        // 1、从 spring 容器中获得 FreeMarkerConfigurer 对象。
        // 2、从 FreeMarkerConfigurer 对象中获得 Configuration 对象。
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        // 3、使用 Configuration 对象获得 Template 对象
        Template template = configuration.getTemplate("comment_template.ftl");
        // 4、创建数据集
        Map<String, Object> root = new HashMap<String, Object>();

        List<Student> list = new ArrayList<Student>();
        Student student1 = new Student();
        student1.setStudentNo("10001");
        student1.setName("张三");
        student1.setAge(23);
        list.add(student1);
        Student student2 = new Student();
        student2.setStudentNo("10002");
        student2.setName("张三2");
        student2.setAge(24);
        list.add(student2);
        Student student3 = new Student();
        student3.setStudentNo("10003");
        student3.setName("张三3");
        student3.setAge(21);
        list.add(student3);
        root.put("studentList", list);

        response.setContentType("text/html; charset=" + "UTF-8");
        Writer out = response.getWriter();
        // 6、调用模板对象的 process 方法,生成文件。
        template.process(root, out);
        // 7、关闭流。
        out.flush();
        out.close();
    



结果图

![](GOODS101.png

package com.javazhan.controller;

import com.javazhan.pojo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yandq
 * @Description:
 * @Date: Create in 11:46 2018/3/23
 * @Modified By:
 */
@Controller
public class FtlController 

    @RequestMapping("/ftl")
    public ModelAndView genHtml()throws Exception 
        ModelAndView mv = new ModelAndView();

        List<Student> list = new ArrayList<Student>();
        Student student1 = new Student();
        student1.setStudentNo("10001");
        student1.setName("张三");
        student1.setAge(23);
        list.add(student1);
        Student student2 = new Student();
        student2.setStudentNo("10002");
        student2.setName("张三2");
        student2.setAge(24);
        list.add(student2);
        Student student3 = new Student();
        student3.setStudentNo("10003");
        student3.setName("张三3");
        student3.setAge(21);
        list.add(student3);

        mv.addObject("studentList", list);
//        mv.setViewName("comment_template.ftl");
        // 配置加上这个<property name="suffix" value=".ftl" />
        mv.setViewName("comment_template");
        return mv;
    


结果图

以上是关于freemarker 笔记的主要内容,如果未能解决你的问题,请参考以下文章

freemarker生成word文档

类和对象

笔记之_Java整理freemarker

深耕MySQL - 50道SQL练习题

学习笔记初识FreeMarker简单使用

学习笔记FreeMarker 之于Servlet与Stuts2的应用