目录
4、访问项目地址 http://localhost:8080/index
4、访问项目地址 http://localhost:8080/thymeleafIndex
一 SpringBoot 整合模板引擎Freemarker
1、引入Freemarker依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2、编写Freemarker配置文件
spring:
freemarker:
allow-request-override: false
cache: false
check-template-location: true
charset: UTF-8
content-type: text/html; charset=utf-8
expose-request-attributes: false
expose-session-attributes: false
expose-spring-macro-helpers: false
## 模版文件结尾.ftl
suffix: .ftl
## 模版文件目录
template-loader-path: classpath:/templates
server:
servlet:
encoding:
force: true
charset: UTF-8
3、编写示例代码
后端代码:
@Controller
public class IndexController {
@RequestMapping("/index")
public String index(Map<String, Object> result) {
result.put("name", "fanaozhe");
result.put("sex","1");
result.put("age",27);
ArrayList<Object> arrayList = new ArrayList<>();
arrayList.add("fanaobo");
arrayList.add("fanoumeng");
result.put("arrayList",arrayList);
return "index";
}
}
前端代码:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
${name}
<!--if用法-->
<#if sex="1">
男
<#elseif sex="0">
女
<#else>
未知
</#if>
<#if age gt 18>
已经成年!
<#else>
未成年
</#if>
<!--list用法-->
<#list arrayList as list >
${list}
</#list>
</html>
注意:关于符号的用法
两种方法
1 用符号代替: > gt , >= gte ,< lt , <= lte
2 加括号 <#if(x>y)>
4、访问项目地址 http://localhost:8080/index
二 SpringBoot 整合模板引擎Thymeleaf
1、引入Thymeleaf依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2、编写Thymeleaf配置文件
###ThymeLeaf配置
spring:
thymeleaf:
#prefix:指定模板所在的目录
prefix: classpath:/templates/
#check-tempate-location: 检查模板路径是否存在
check-template-location: true
#cache: 是否缓存,开发模式下设置为false,避免改了模板还要重启服务器,线上设置为true,可以提高性能。
cache: true
suffix: .html
encoding: UTF-8
mode: HTML5
3、编写示例代码
后端代码:
@RequestMapping("/thymeleafIndex")
public String thymeleafIndex(Map<String,Object> result){
ArrayList<Object> list = new ArrayList<>();
User user1 = new User("fanaozhe","男",27);
User user2 = new User("fanaobo","男",7);
User user3 = new User("fanoumeng","女",16);
list.add(user1);
list.add(user2);
list.add(user3);
result.put("userList",list);
return "thymeleafIndex";
}
前端代码:
<!DOCTYPE html>
<!--需要在HTML文件中加入以下语句: -->
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Show User</title>
</head>
<body>
<!--循环-->
<ul th:each="user:${userList}">
<li th:text="${user.name}"></li>
<li th:text="${user.sex}"></li>
<li th:text="${user.age}"></li>
<!--判断-->
<span th:if="${user.age>17}">已经成年啦</span>
<span th:if="${user.age<17}">未成年</span>
<br>
</ul>
</body>
</html>
4、访问项目地址 http://localhost:8080/thymeleafIndex