|
发表于 2023-3-7 16:32:00
|
查看: 585 |
回复: 0
SpringBoot整合前端框架Freemarker与Thymeleaf
https://blog.csdn.net/luciferlongxu/article/details/125287550
整合Freemarker
创建SpringBoot项目时选择依赖的模板引擎
或者通过pom引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>2.6.8</version>
</dependency>
controller中通过Model向前端传值
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/index")
public String index(Model model) {
// 模拟数据库取到的数据
List<User> users = new ArrayList<>();
users.add(new User("1", "Lily", 18));
users.add(new User("2", "Lisi", 21));
users.add(new User("3", "Tom", 19));
users.add(new User("4", "Tony", 20));
model.addAttribute("users", users);
return "user";
}
}
在配置文件中定义Freemarker文件后缀
resources/application.properties
server.port=8081
spring.freemarker.suffix=.ftl
前端页面通过Freemarker语法读取后台传的数据
resources/templates/user.ftl
<html>
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<table border="1" align="center" width="80%">
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
</tr>
<#list users as user>
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.age}</td>
</tr>
</#list>
</table>
</body>
</html>
访问api测试
整合Thymeleaf
创建SpringBoot项目时选择依赖的模板引擎
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.6.8</version>
</dependency>
controller中通过Model向前端传值
@Controller
public class HelloController {
@RequestMapping("/index")
public String index(Model model) {
model.addAttribute("msg", "Hello, this is test Thymeleaf");
return "index"; //指定返回给index.html页面
}
}
前端页面通过Thymeleaf语法取值
resources/templates/index.html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>Thymeleaf testing</h1>
<span th:text="${msg}"></span>
</body>
</html>
访问api测试
————————————————
版权声明:本文为CSDN博主「Lucifer Zhao」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/luciferlongxu/article/details/125287550
|
-
|