1.pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.application.yml文件的默认配置
spring:
thymeleaf:
cache: false
freemarker:
# 设置模板后缀名
suffix: .ftl
# 设置文档类型
content-type: text/html
# 设置页面编码格式
charset: UTF-8
# 设置页面缓存
cache: false
# 设置ftl文件路径,默认是/templates,为演示效果添加role
template-loader-path: classpath:/templates/role
mvc:
static-path-pattern: /static/**
3.controller层
@RequestMapping("/role/list")
public ModelAndView roleList(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("list");
modelAndView.addObject("name","老王");
modelAndView.addObject("sex","gril");
List list = new ArrayList();
list.add(new Role(1,"老师","传授知识"));
list.add(new Role(2,"学生","搞事情"));
modelAndView.addObject("roles",list);
return modelAndView;
}
@RequestMapping("/login")
public String login(){
return "login";
}
4.list.ftl文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>角色列表</title>
</head>
<body>
<#--当不加!并且name为null时会报错 !后代表!为空时的默认值可以不填-->
welcome 【${name!'未知'}】 to freemarker!
<h3>exists用在逻辑判断</h3>
<#if name?exists>
${name}
</#if>
<h2>条件</h2>
<#if sex=='girl'>
女
<#elseif sex=='boy'>
男
<#else>
保密
</#if>
<h2>循环</h2>
<#list roles as role>
${role.roleName}
</#list>
<table width="600px" border="1px">
<thead>
<tr>
<td>角色id</td>
<td>角色名</td>
<td>角色备注</td>
</tr>
<#list roles as role>
<tr>
<td>${role.rid}</td>
<td>${role.roleName}</td>
<td>${role.desc}</td>
</tr>
</#list>
</thead>
</table>
<h2>局部变量(assign)/全局变量(global)</h2>
<#--将项目名赋值给a,作用域为当前页面-->
<#assign a>
${springMacroRequestContext.contextPath}
</#assign>
<#--将项目名赋值给a,作用域在整个项目-->
<#global b>
${springMacroRequestContext.contextPath}
</#global>
${a}和${b}
<h2>include(引入文件)</h2>
<#include 'foot.ftl'>
</body>
</html>
5.foot.ftl文件
底部内容
<a href="login.ftl">登录1</a>
<a href="${b}/login">登录2</a>
<#assign cPath>
${springMacroRequestContext.contextPath}
</#assign>
<script type="text/javascript" src="${cPath}/static/js/a.js"></script>
6.页面效果
注意:当点击登录1时会报错因为在freemarker中不可直接使用路径因为spring会自动过滤导致路径不对所以需要按照登录2那样先进入后台controller层处理跳转.