controller中通过Model向前端传值org.springframework.boot spring-boot-starter-freemarker2.6.8
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/index")
public String index(Model model) {
// 模拟数据库取到的数据
List 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
用户列表
| ID | 姓名 | 年龄 |
|---|---|---|
| ${user.id} | ${user.name} | ${user.age} |
整合Thymeleaf 创建SpringBoot项目时选择依赖的模板引擎 引入依赖
controller中通过Model向前端传值org.springframework.boot spring-boot-starter-thymeleaf2.6.8
@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
访问api测试Title Thymeleaf testing



