freemarker是一个用Java开发的模板引擎

常用的java模板引擎还有哪些?

JspFreemarkerThymeleafVelocity 等。

1. 快速入门

1.1 创建工程pom.xml文件如下

<?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 编辑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 创建模型类

freemarker的测试工程下创建模型类型用于测试

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 创建模板

src/main/resources下创建templates,此目录为freemarker的默认模板存放目录。

templates下创建模板文件test1.ftl,模板中的${name}最终会被freemarker替换成具体的数据。

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

1.5 创建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 测试

2. FreeMarker 基础

2.1 数据模型

Freemarker静态化依赖数据模型和模板,下边定义数据模型:

下边方法形参map即为freemarker静态化所需要的数据模型,在map中填充数据:

@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指令

本节定义freemarker模板,模板中使用freemarker的指令,关于freemarker的指令需要知道:

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

在test1.ftl模板中使用list指令遍历数据模型中的数据:

<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>

输出

_index:得到循环的下标,使用方法是在stu后边加"_index",它的值是从0开始

2.3 遍历Map数据

  1. 数据模型

    使用map指令遍历数据模型中的stuMap

  2. 模板

<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>

输出结果

2.4 if指令

if 指令即判断指令,是常用的FTL指令,freemarker在解析时遇到if会进行判断,条件为真则输出if中间的内容,否

则跳过内容不再输出。

1、数据模型:

使用list指令中测试数据模型。

2、模板:

<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>

2.5 运算符

  • 算数运算符 FreeMarker表达式中完全支持算术运算,FreeMarker支持的算术运算符包括:+, - , * , / , %

  • 逻辑运算符 逻辑运算符有如下几个: 逻辑与:&& 逻辑或:|| 逻辑非:! 逻辑运算符只能作用于布尔值,否则将产生错误

  • 比较运算符 表达式中支持的比较运算符有如下几个:

    • 1 =或者==:判断两个值是否相等.
    • 2 !=:判断两个值是否不等.
    • 3 >或者gt:判断左边值是否大于右边值
    • 4 >=或者gte:判断左边值是否大于等于右边值
    • 5 <或者lt:判断左边值是否小于右边值
    • 6 <=或者lte:判断左边值是否小于等于右边值

注意: =和!=可以用于字符串,数值和日期来比较是否相等,但=和!=两边必须是相同类型的值,否则会产生错误,而且FreeMarker是精确比较,"x","x ","X"是不等的.其它的运行符可以作用于数字和日期,但不能作用于字符串,大部分的时候,使用gt等字母运算符代替>会有更好的效果,因为 FreeMarker会把>解释成FTL标签的结束字符,当然,也可以使用括号来避免这种情况,如:<#if (x>y)>

2.6 空值处理

1、判断某变量是否存在使用 “??” 用法为:variable??,如果该变量存在,返回true,否则返回false

例:为防止stus为空报错可以加上判断如下:

<#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}

springboot2.0整合freemarker快速入门的更多相关文章

  1. FreeMarker 快速入门

    FreeMarker 快速入门 FreeMarker是一个很值得去学习的模版引擎.它是基于模板文件生成其他文本的通用工具.本章内容通过如何使用FreeMarker生成Html web 页面 和 代码自 ...

  2. SpringBoot2.0 整合 Redis集群 ,实现消息队列场景

    本文源码:GitHub·点这里 || GitEE·点这里 一.Redis集群简介 1.RedisCluster概念 Redis的分布式解决方案,在3.0版本后推出的方案,有效地解决了Redis分布式的 ...

  3. 第二篇:SpringBoot2.0整合ActiveMQ

    本篇开始将具体介绍SpringBoot如何整合其它项目. 如何创建SpringBoot项目 访问https://start.spring.io/. 依次选择构建工具Maven Project.语言ja ...

  4. SpringBoot2.0 整合 QuartJob ,实现定时器实时管理

    一.QuartJob简介 1.一句话描述 Quartz是一个完全由java编写的开源作业调度框架,形式简易,功能强大. 2.核心API (1).Scheduler 代表一个 Quartz 的独立运行容 ...

  5. SpringBoot2.0 整合 Swagger2 ,构建接口管理界面

    一.Swagger2简介 1.Swagger2优点 整合到Spring Boot中,构建强大RESTful API文档.省去接口文档管理工作,修改代码,自动更新,Swagger2也提供了强大的页面测试 ...

  6. SpringBoot2.0 整合 Dubbo框架 ,实现RPC服务远程调用

    一.Dubbo框架简介 1.框架依赖 图例说明: 1)图中小方块 Protocol, Cluster, Proxy, Service, Container, Registry, Monitor 代表层 ...

  7. springboot2.0整合logback日志(详细)

    <div class="post"> <h1 class="postTitle"> springboot2.0整合logback日志(详 ...

  8. SpringBoot整合ActiveMQ快速入门

    Spring Boot 具有如下特性: 为基于 Spring 的开发提供更快的入门体验 开箱即用,没有代码生成,也无需 XML 配置.同时也可以修改默认值来满足特定的需求. 提供了一些大型项目中常见的 ...

  9. Shiro第四篇【Shiro与Spring整合、快速入门、Shiro过滤器、登陆认证】

    Spring与Shiro整合 导入jar包 shiro-web的jar. shiro-spring的jar shiro-code的jar 快速入门 shiro也通过filter进行拦截.filter拦 ...

随机推荐

  1. [Vue] : Vue概述

    什么是Vue.js Vue.js 是目前最火的一个前端框架,React是最流行的一个前端框架. Vue.js 是前端的主流框架之一,和Angular.js.React.js 一起,并成为前端三大主流框 ...

  2. 小程序和vue的区别

    最近开发了一个比较完整的小程序项目,打算总结一下,小程序开发和vue开发的代码上的区别 1.小程序的路由写在app.json文件里,vue写在route.js里 2.小程序用 src="{{ ...

  3. google中select添加onclick

    有下拉跳转框如下所示: <select name="page" size="1" > <option onclick="refurb ...

  4. 预处理、const、static与sizeof-用#define实现宏并求最大值和最小值

    1:实现代码: #define MAX(x,y) (((x)>(y)) ? (x):(y)) #define MIN(x,y) (((x)>(y)) ? (x):(y)) 需要注意的几点: ...

  5. 中间件 | kafka简介、使用场景、设计原理、主要配置及集群搭建

    开源Java学习 公众号 一.入门 1.简介 Kafka is a distributed,partitioned,replicated commit logservice.它提供了类似于JMS的特性 ...

  6. Fragment 和Activity的数据传递实例代码

    package com.example.fragment; import android.os.Bundle; import android.support.v4.app.FragmentActivi ...

  7. hk clearing participant & Exchange Participant of SEHK

    https://www.hkex.com.hk/-/media/HKEX-Market/Services/Clearing/Securities/Infrastructure/CCASS-3-Term ...

  8. html提交表单,php在后台获取表单内容的方法_例1

    html代码:   <html>   <head>   <meta http-equiv="Content-Type" content="t ...

  9. Android View重绘和更新: invalidate和requestLayout 总结的不错 赶紧复制。。哈哈

    总述:View有两个很重要的方法:invalidate和requestLayout,常用于View重绘和更新. Invalidate:To farce a view to draw,call inva ...

  10. TextInput组件的常用属性

    1.TextInput组件基本介绍: TextInput是一个允许用户在应用中通过键盘输入文本的基本组件.本组件的属性提供了多种特性的配置,譬如自动完成.自动大小写.占位文字,以及多种不同的键盘类型( ...