- 整合Thymeleaf
- 整合FreeMarker
一、整合Thymeleaf
1.1、添加依赖
<!--整合thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1.2、配置控制器
package cn.waggag.controller;
import cn.waggag.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.util.ArrayList;
import java.util.List;
@RestController
public class UserController {
@GetMapping("/thymeleaf")
public ModelAndView usersThymeleaf(){
List<User> users = new ArrayList<>();
users.add(new User("王港",23));
users.add(new User("仲夏三十",23));
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("users",users);
modelAndView.setViewName("usersthymeleaf");
System.out.println(users);
return modelAndView;
}
}
1.3、在resources下创建templates目录,创建usersthymeleaf.html
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>整合thymeleaf</title>
</head>
<body>
<table border="1" align="center">
<tr>
<td>用户名</td>
<td>密码</td>
</tr>
<tr th:each="user:${users}">
<td th:text="${user.name}"></td>
<td th:text="${user.age}"></td>
</tr>
</table>
</body>
</html>
1.4、运行结果
二、整合FreeMarker
2.1、添加依赖
<!--整合freemaker-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
2.2、配置控制器
@GetMapping("/freemarker")
public ModelAndView usersFreeMarker(){
List<User> users = new ArrayList<>();
users.add(new User("王港",23));
users.add(new User("仲夏三十",23));
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("users",users);
modelAndView.setViewName("usersfreemarker");
System.out.println(users);
return modelAndView;
}
2.3、在resources下创建templates目录,创建usersfreemarker.ftl
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<title>整合FreeMarker</title>
</head>
<body>
<table border="1" align="center">
<tr>
<td>用户名</td>
<td>密码</td>
</tr>
<#if users ?? && (users?size>0)>
<#list users as user>
<tr>
<td>${user.name}</td>
<td>${user.age}</td>
</tr>
</#list>
</#if>)
</table>
</body>
</html>
2.4、测试结果
注意:目前流行前后端分离技术,可以不需要整合试图技术,后端直接提供接口即可。