springboot2.0 integration freemarker Quick Start

freemarkerIs a template engine written in Java

Popular java template engine What?
Jsp, Freemarker, Thymeleaf, VelocityAnd so on.

1. Getting Started

1.1 Create a project pom.xmlfile as follows

<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

1.2 Editing application.yml

server:
  port: 8088
spring:
  application:
    name: test-freemarker
  #    freemarker配置
  freemarker:
    cache: false  #关闭模板缓存,方便测试
    settings:
      template_update_delay: 0  #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
    template-loader-path: classpath:/templates
    charset: UTF-8
    check-template-location: true
    suffix: .ftl
    content-type: text/html
    expose-request-attributes: true
    expose-session-attributes: true
    request-context-attribute: request

1.3 Create a model class

In freemarkercreating a model project types under test for testing

package com.example.demo.model;

import lombok.Data;
import lombok.ToString;

import java.util.Date;
import java.util.List;

/**
 * @author john
 * @date 2019/12/20 - 16:52
 */
@Data
@ToString
public class Student {
    private String name;//姓名
    private int age;//年龄
    private Date birthday;//生日
    private Float money;//钱包
    private List<Student> friends;//朋友列表
    private Student bestFriend;//最好的朋友
}

1.4 Create a template

In the src/main/resourcescase created templates, this directory is freemarkerthe default template storage directory.
In templatescreating a template file test1.ftl, the template ${name}will eventually be freemarkerreplaced with specific data.

<html>
<head>
    <title>hello world!</title>
</head>
<body>
hello ${name}
</body>
</html>

1.5 Creating controller

package com.example.demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

/**
 * @author john
 * @date 2019/12/20 - 16:54
 */

@Controller
@RequestMapping("freemarker")
public class FreemarkerController {

    @GetMapping("/test1")
    public String freemarker(Map<String, Object> map) {
        map.put("name", "java");
        //返回模板文件名称
        return "test1";
    }
}

1.6 Test

2. FreeMarker basis

2.1 Data Model

FreemarkerStatic model and template-dependent data, data models are defined below:
the lower the method parameter mapis the freemarkerstatic data of the desired model, the mapdata is filled:

@GetMapping("/test1")
    public String freemarker(Map<String, Object> map) {
        //向数据模型放数据
        map.put("name", "john");
        Student stu1 = new Student();
        stu1.setName("小明");
        stu1.setAge(18);
        stu1.setMoney(1000.86f);
        stu1.setBirthday(new Date());
        Student stu2 = new Student();
        stu2.setName("小红");
        stu2.setMoney(200.1f);
        stu2.setAge(19);
//        stu2.setBirthday(new Date());
        List<Student> friends = new ArrayList<>();
        friends.add(stu1);
        stu2.setFriends(friends);
        stu2.setBestFriend(stu1);
        List<Student> stus = new ArrayList<>();
        stus.add(stu1);
        stus.add(stu2);
        //向数据模型放数据
        map.put("stus", stus);
        //准备map数据
        HashMap<String, Student> stuMap = new HashMap<>();
        stuMap.put("stu1", stu1);
        stuMap.put("stu2", stu2);
        //向数据模型放数据
        map.put("stu1", stu1);
        //向数据模型放数据
        map.put("stuMap", stuMap);
        //返回模板文件名称
        return "test1";
    }

2.2 List of instructions

This section defines the freemarkertemplate, the template using freemarkerinstructions on freemarkerthe instruction you need to know:

1、注释,即<#‐‐和‐‐>,介于其之间的内容会被freemarker忽略
2、插值(Interpolation):即${..}部分,freemarker会用真实的值代替${..}
3、FTL指令:和HTML标记类似,名字前加#予以区分,Freemarker会解析标签中的表达式或逻辑。
4、文本,仅文本信息,这些不是freemarker的注释、插值、FTL指令的内容会被freemarker忽略解析,直接输出内
容。

Use the list command test1.ftl template through the data in the data model:

<html>
<head>
    <title>hello world!</title>
</head>
<body>
<table>
    <tr>
        <td>序号</td>
        <td>姓名</td>
        <td>年龄</td>
        <td>钱包</td>
    </tr>
    <#list stus as stu>
        <tr>
            <td>${stu_index + 1}</td>
            <td>${stu.name}</td>
            <td>${stu.age}</td>
            <td>${stu.money}</td>
        </tr>
    </#list>
</table>
</body>
</html>

Export

_index: index, obtained using the method loop is added back in stu "_index", its value is zero

2.3 traversing Map Data

  1. Data model
    using mapcommands through the data model stuMap.

  2. template

<html>
<head>
    <title>hello world!</title>
</head>
<body>

输出stu1的学生信息:<br/>
姓名:${stuMap.stu1.name}<br/>
年龄:${stuMap.stu1.age}<br/>
遍历输出两个学生信息:<br/>
<table>
    <tr>
        <td>序号</td>
        <td>姓名</td>
        <td>年龄</td>
        <td>钱包</td>
    </tr>
    <#list stuMap?keys as k>
        <tr>
            <td>${k_index + 1}</td>
            <td>${stuMap[k].name}</td>
            <td>${stuMap[k].age}</td>
            <td>${stuMap[k].money}</td>
        </tr>
    </#list>
</table>
</body>
</html>

Output

2.4 if instruction

That instruction if the instruction is determined, is a common instruction FTL, freemarker will judge if encountered when parsing, an intermediate condition is true if the contents of the output, whether
the output is no longer skipped.
1, the data model:
use test instruction list data model.
2, the template:

<html>
<head>
    <title>hello world!</title>
</head>
<body>
<table>
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>钱包</td>
    </tr>
    <#list stus as stu>
        <tr>
            <td <#if stu.name =='小明'>style="background:red;"</#if>>${stu.name}</td>
            <td>${stu.age}</td>
            <td>${stu.money}</td>
        </tr>
    </#list>
</table>
</body>
</html>

Operators 2.5

  • Arithmetic operators FreeMarkerexpressions fully support arithmetic operations FreeMarkersupported include arithmetic operators: +, -, *, /,%

  • Logical Operators Logical Operators has the following: Logical: && Logical OR: Logical Non ||:! Logical operator can act on the Boolean value, otherwise an error

  • Comparison operator expressions of support has the following comparison operators:
    • Or = 1 ==: determining whether the two values ​​are equal.
    • 2 =:! Determine whether two values ​​are unequal.
    • 3> Or gt: determining the left to the right value is greater than the value
    • 4> or = gte: determining whether the value is greater than or equal to the right of the left value
    • 5 <Alternatively lt: judging value is smaller than the left to the right value
    • 6 <or = lte: determining whether the value is less than or equal to the right of the left value

Note:!! = And = can be used to string, number, date, and to compare for equality, but on both sides, and = = value must be the same type, or an error, and FreeMarkeraccurate comparison, "x", "x" , "X" are not equal. other symbols may be applied to the running numbers and dates, but can not act on the string, most of the time, like letters used gt operator instead> would be better, as will FreeMarker the> FTL interpreted as the end of the character label, of course, also be used to avoid this situation parentheses, such as: <# if (x> y )>

Null handling 2.6

1, to determine whether there is a variable using the "??" Usage is: variable ??, if the variable exists, returns true, false otherwise

Example: In order to prevent stus empty error may add Analyzing follows:

<#if stus??>
        <#list stus as stu>
            <tr>
                <td>${stu.name}</td>
                <td>${stu.age}</td>
                <td>${stu.money}</td>
            </tr>
        </#list>
    </#if>

2、缺失变量默认值使用 “!” 使用!要以指定一个默认值,当变量为空时显示默认值。

例:${name!''}表示如果name为空显示空字符串。
如果是嵌套对象则建议使用()括起来。

例: ${(stu.bestFriend.name)!''}表示,如果stubestFriendname为空默认显示空字符串。

2.7 内建函数

内建函数语法格式: 变量+?+函数名称

1、和到某个集合的大小

${集合名?size}

<html>
<head>
    <title>hello world!</title>
</head>
<body>
<table>
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>钱包</td>
    </tr>
    <#if stus??>
        stus集合的大小是${stus?size}
        <#list stus as stu>
            <tr>
                <td>${stu.name}</td>
                <td>${stu.age}</td>
                <td>${stu.money}</td>
            </tr>
        </#list>
    </#if>
</table>
</body>
</html>

2、日期格式化
显示年月日: ${today?date}
显示时分秒:${today?time}  
显示日期+时间:${today?datetime} <br>       
自定义格式化:  ${today?string("yyyy年MM月")}
<#if stus??>
        <#list stus as stu>
            <tr>
                <td>${stu.name}</td>
                <td>${stu.age}</td>
                <td>${stu.money}</td>
                <td>${(stu.birthday?date)!''}---${(stu.birthday?time)!''}---${(stu.birthday?datetime)!''}
                    ---${(stu.birthday?string("yyyy年MM月"))!''}</td>
            </tr>
        </#list>
    </#if>

3、内建函数c
map.put("point", 102920122);

point是数字型,使用${point}会显示这个数字的值,不并每三位使用逗号分隔。
如果不想显示为每三位分隔的数字,可以使用c函数将数字型转成字符串输出
${point?c}

4、将json字符串转成对象

一个例子:
其中用到了 assign标签,assign的作用是定义一个变量。

<#assign text="{'bank':'工商银行','account':'10101920201920212'}" />
<#assign data=text?eval />
开户行:${data.bank} 账号:${data.account}

Guess you like

Origin www.cnblogs.com/ifme/p/12074678.html