导入pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
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/**
注意:在开发项目期间cache: false ,项目开发完了建议改为true
list.ftl 相关代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>角色</title>
<#include 'common.ftl' >
</head>
<body>
<h1>取值</h1>
welcome 【${name !'啦啦啦'}】 to page
<h1>非空判断</h1>
<#if name?exists>
你好
</#if>
<h1>条件表达式</h1>
<#if sex=='男'>
穿裤子
<#elseif sex=='女'>
穿群子
<#else>
不告诉你
</#if>
<table border="1" width="800px">
<thead bgcolor="aqua">
<tr>
<td>id</td>
<td>名字</td>
<td>密码</td>
</tr>
</thead>
<tbody>
<#list users as user>
<tr>
<td>${user.uid}</td>
<td>${user.usename}</td>
<td>${user.password}</td>
</tr>
</#list>
</tbody>
</table>
<h2>变量的设置(局部,全局)</h2>
<#assign ctx1 >
${springMacroRequestContext.contextPath}
</#assign>
<#global ctx2>
${springMacroRequestContext.contextPath}
</#global>
<h2>include</h2>
<#include 'foot.ftl'>
</body>
</html>
foot.ftl相关代码
版本权
<a href="login.ftl">登录1</a>
<a href="${ctx2}/toLogin">登录2</a>
common.ftl相关代码
<#assign ctx >
${springMacroRequestContext.contextPath}
</#assign>
<base href="${ctx}/" >
<script type="javascript" src="static/qq.js"></script>
login.ftl相关代码
欢迎进入login 页面
相关controller层的Java代码
@RequestMapping("/role/list")
public ModelAndView rolelist(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("name",null);
modelAndView.addObject("sex","男");
List<User> list=new ArrayList<>();
list.add(new User(1,"zs","123"));
list.add(new User(2,"ls","123"));
modelAndView.addObject("users",list);
modelAndView.setViewName("list");
return modelAndView ;
}
@RequestMapping("/toLogin")
public ModelAndView toLogin(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.setViewName("login");
return modelAndView ;
}
浏览器显示结果
注意点:
1、application.yml中可以配置模板存放位置的根路径、以及静态资源文件存放位置的根路径
2、${springMacroRequestContext.contextPath}:SpringBoot中获取项目名
3、不推荐使用全局变量。即便它们属于不同的命名空间, 全局变量也被所有模板共享,因为它们是被 import进来的。
4、freemarker模板也可以像jsp那样设置根路径
<#include 'common.ftl'>
<script src="js/xxx.js" type="text/javascript"></script