springboot+freemarker快速入门
1.引入pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.application.yml配置文件
server:
port: 8088 #服务端口
spring:
application:
name: test‐freemarker #指定服务名
freemarker:
cache: false #关闭模板缓存,方便测试
settings:
template_update_delay: 0 #检查模板更新延迟时间,设置为0表示立即检查,如果时间大于0会有缓存不方便进行模板测试
3.src/main/resources 目录 templates(默认在这个位置找模板)下,创建 test.ftl
<!DOCTYPE html>
<html>
<head>
<meta charset="utf‐8">
<title>Hello World!</title>
</head>
<body>
<table>
hello ${name}
</table>
</body>
</html>
4.建立Student学生实体类
@Data
@ToString
public class Student {
private String name;//姓名
private int age;//年龄
private Date birthday;//生日
private Float money;//钱包
private List<Student> friends;//朋友列表
private Student bestFriend;//最好的朋友
}
5.编写Cotroller类
package com.xuecheng.test.freemarker.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Map;
@RequestMapping("/freemarker")
@Controller
public class FreemarkerController {
@RequestMapping("/test1")
public String freemarker(Map<String, Object> map){
//学生1
Student stu1 = new Student();
stu1.setName("小明");
stu1.setAge(18);
stu1.setMoney(1000.86f);
stu1.setBirthday(new Date());
//学生2
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
HashMap<String, Student> stuMap = new HashMap<>();
stuMap.put("stu1",stu1);
stuMap.put("stu2",stu2);
//向数据模型放数据
map.put("name","小明");
map.put("stuMap",stuMap);
map.put("stus",stus);
map.put("stu2",stu2);
//返回模板文件名称
return "test1";
}
}
6.FreemarkerTestApplication启动类启动
目录结构为:
访问:http://localhost:8088/freemarker/test1
7.FreeMarker核心指令
1.插值指令:${}
<body>
<table>
hello ${name}
</table>
</body>
2.注释指令:<#‐‐和‐‐>
即<#‐‐和‐‐>,介于其之间的内容会被freemarker忽略
<body>
<table>
<#‐‐我是注释‐‐>
hello ${name}
</table>
</body>
3.FTL指令
和HTML标记类似,名字前加#予以区分,Freemarker会解析标签中的表达式或逻辑
4. List 指令:<#list stus as stu></#list>
<body>
<table>
<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>
</table>
</body>
- 遍历Map数据
<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>
- if指令:<#if ></#if>
<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>
8.FreeMarker其它指令
1.运算符
- 算数运算符:+, - , * , / , %
- 逻辑运算符:&& ,|| ,! (逻辑运算符只能作用于布尔值,否则将产生错误)
- 比较运算符:=或者==,!=, > 或者gt:, >=或者gte:, <或者lt:,<=或者lte:
2.空值处理: “??” , “!”
- stus不为空时遍历
<#if stus??>
<#list stus as stu>
......
</#list>
</#if>
- name为空时,显示“”小明“”
${name!'小明'}
3.内建函数
内建函数语法格式: 变量+?+函数名称
- 某个集合的大小
${集合名?size}
- 日期格式化
显示年月日: ${today?date}
显示时分秒:${today?time}
显示日期+时间:${today?datetime}
自定义格式化: ${today?string("yyyy年MM月")}
- 内建函数c
map.put("point", 102920122);
point是数字型,使用${point}会显示这个数字的值,每三位使用逗号分隔。 如果不想显示为每三位分隔的数字,可以使用c函数将数字型转成字符串输出
${point?c}
- 将json字符串转成对象
其中用到了 assign标签,assign的作用是定义一个变量。
<#assign text="{'bank':'工商银行','account':'10101920201920212'}" />
<#assign data=text?eval />
开户行:${data.bank}
账号:${data.account}
8.使用模板字符串静态化
public static void main(String[] args) throws IOException, TemplateException {
Configuration configuration=new Configuration(Configuration.getVersion());
String templateString="select ${param!'*'} from ${name}";
//模板加载器
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
stringTemplateLoader.putTemplate("template",templateString);
configuration.setTemplateLoader(stringTemplateLoader);
//得到模板
Template template = configuration.getTemplate("template","utf‐8");
//数据模型
Map<String,Object> map = new HashMap<>();
map.put("name","table");
map.put("param","id,code");
//静态化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//静态化内容
System.out.println(content);
}
9.使用模板文件静态化
public static void main(String[] args) throws IOException, TemplateException {
//创建配置类
Configuration configuration=new Configuration(Configuration.getVersion());
//设置模板路径
String classpath = this.getClass().getResource("/").getPath();
configuration.setDirectoryForTemplateLoading(new File(classpath + "/templates/"));
//设置字符集
configuration.setDefaultEncoding("utf‐8");
//加载模板
Template template = configuration.getTemplate("test1.ftl");
//数据模型
Map<String,Object> map = new HashMap<>();
map.put("name","小明");
//静态化
String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
//静态化内容
System.out.println(content);
InputStream inputStream = IOUtils.toInputStream(content);
//输出文件
FileOutputStream fileOutputStream = new FileOutputStream(new File("d:/test1.html"));
int copy = IOUtils.copy(inputStream, fileOutputStream);
}