springboot2.0整合freemarker快速入门
freemarker
是一个用Java开发的模板引擎
常用的java模板引擎还有哪些?
Jsp
、Freemarker
、Thymeleaf
、Velocity
等。
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数据
数据模型
使用map
指令遍历数据模型中的stuMap
。模板
<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)!''}
表示,如果stu
或bestFriend
或name
为空默认显示空字符串。
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快速入门的更多相关文章
- FreeMarker 快速入门
FreeMarker 快速入门 FreeMarker是一个很值得去学习的模版引擎.它是基于模板文件生成其他文本的通用工具.本章内容通过如何使用FreeMarker生成Html web 页面 和 代码自 ...
- SpringBoot2.0 整合 Redis集群 ,实现消息队列场景
本文源码:GitHub·点这里 || GitEE·点这里 一.Redis集群简介 1.RedisCluster概念 Redis的分布式解决方案,在3.0版本后推出的方案,有效地解决了Redis分布式的 ...
- 第二篇:SpringBoot2.0整合ActiveMQ
本篇开始将具体介绍SpringBoot如何整合其它项目. 如何创建SpringBoot项目 访问https://start.spring.io/. 依次选择构建工具Maven Project.语言ja ...
- SpringBoot2.0 整合 QuartJob ,实现定时器实时管理
一.QuartJob简介 1.一句话描述 Quartz是一个完全由java编写的开源作业调度框架,形式简易,功能强大. 2.核心API (1).Scheduler 代表一个 Quartz 的独立运行容 ...
- SpringBoot2.0 整合 Swagger2 ,构建接口管理界面
一.Swagger2简介 1.Swagger2优点 整合到Spring Boot中,构建强大RESTful API文档.省去接口文档管理工作,修改代码,自动更新,Swagger2也提供了强大的页面测试 ...
- SpringBoot2.0 整合 Dubbo框架 ,实现RPC服务远程调用
一.Dubbo框架简介 1.框架依赖 图例说明: 1)图中小方块 Protocol, Cluster, Proxy, Service, Container, Registry, Monitor 代表层 ...
- springboot2.0整合logback日志(详细)
<div class="post"> <h1 class="postTitle"> springboot2.0整合logback日志(详 ...
- SpringBoot整合ActiveMQ快速入门
Spring Boot 具有如下特性: 为基于 Spring 的开发提供更快的入门体验 开箱即用,没有代码生成,也无需 XML 配置.同时也可以修改默认值来满足特定的需求. 提供了一些大型项目中常见的 ...
- Shiro第四篇【Shiro与Spring整合、快速入门、Shiro过滤器、登陆认证】
Spring与Shiro整合 导入jar包 shiro-web的jar. shiro-spring的jar shiro-code的jar 快速入门 shiro也通过filter进行拦截.filter拦 ...
随机推荐
- codeforces700B
CF700B Connecting Universities 题意翻译 树之王国是一个由n-1条双向路连接着n个城镇的国家,任意两个城镇间都是联通的. 在树之王国共有2k所大学坐落于不同的城镇之中. ...
- Django基础之Session版登录验证
from functools import wraps def check_login(func): @wraps(func) def inner(request, *args, **kwargs): ...
- BZOJ 4898 Luogu P3778 [APIO2017]商旅 (分数规划、最短路)
题目链接: (bzoj)https://www.lydsy.com/JudgeOnline/problem.php?id=4898 (luogu)https://www.luogu.org/probl ...
- redis慢查询笔记
慢查询 生命周期 两个配置 三个命令 运维经验 生命周期 1.发送命令 2,排队执行命令因为单线程 3.执行命令 4.返回结果 慢查询发生在第三阶段 客户端超时并不一定有慢查询,但慢查询是客户端超时的 ...
- PowerShell入门学习
一.概要 Powershell是运行在windows机器上实现系统和应用程序管理自动化的命令行脚本环境. powershell需要.NET环境的支持,同时支持.NET对象.之所以将Powershell ...
- qt 元对象系统
元对象系统 Qt中的元对象系统是用来处理对象间通讯的信号/槽机制.运行时的类型信息和 动态属性系统. 它基于下列三类: QObject类: 类声明中的私有段中的Q_OBJECT宏: 元对象编译器(mo ...
- [学习]sentinel中的DatatSource(一) ReadableDataSource
sentinel是今年阿里开源的高可用防护的流量管理框架. git地址:https://github.com/alibaba/Sentinel wiki:https://github.com/alib ...
- tornado框架学习
tornado是一个非阻塞的web服务器框架,每秒可以处理上千个客户端连接(都是在一个线程中,不需要为每个客户端创建线程,资源消耗少),适合用来开发web长连接应用,如long polling(轮询) ...
- JAVA类定义的修饰
命名类的访问权限public.protected.friendly,private 这四个的权限, 作用域: 当前(父,超)类: 同一Package: 派生(子)类: 其他Package: publi ...
- Tween(补间)动画
视图动画,也叫Tween(补间)动画可以在一个视图容器内执行一系列简单变换(位置.大小.旋转.透明度).譬如,如果你有一个TextView对象,您可以移动.旋转.缩放.透明度设置其文本,当然,如果它有 ...