应用控制器可以根据客户端请求,调用业务方法,并转发页面。但是,对于页面中战士动态数据的处理,只能以拼接字符串的方式进行。
应用控制器对于生成动态网页繁琐,不利于项目分工。
解决方案之一,就是利用模板引擎简化动态数据的生成。
模板引擎是为了使用户界面与业务数据(内容)分离而产生的,它可以生成特定格式的文档,用于网站的模板引擎就会生成一个标准的html文档
模板引擎可以让(网站)程序实现界面与数据分离,业务代码与逻辑代码分离,这就大大提升了开发效率,良好的设计也使得代码重用变得更加容易。
常见的模板引擎有:
Jsp
Thymeleaf
Freemarker
......
在springBoot 环境下,添加 thymeleaf 启动器
-
org.springframework.boot -
spring-boot-starter-thymeleaf
在 maven 项目的 resources 目录下,新建 application.yml。进行thymeleaf配置(可选)
- spring:
- thymeleaf:
- enabled: true #开启thymeleaf视图解析
- encoding: utf-8 #编码
- prefix: classpath:/templates/ #前缀
- cache: false #是否使用缓存
- mode: HTML #严格的HTML语法模式
- suffix: .html #后缀名
在 maven 项目的 resources 目录下,新建 templates 目录,存放 thymeleaf 页面
在应用控制器中绑定共享数据
- @RequestMapping("test")
- public String test(HttpServletRequest request){
- //绑定共享数据
- request.setAttribute("name","刘勇");
- request.setAttribute("age",20);
- //请求转发到指定页面
- return "/showInfo.html";
- }
在页面中显示共享数据
1、设置 thymeleaf 前缀
<html xmlns:th="http://www.thymeleaf.org">
2、显示共享数据
- 姓名:<span th:text="${name}">span><br>
- 年龄:<span th:text="${age}">span>
判断语句:
- <span th:if="${age>=18}">已成年span>
- <span th:if="${age<18}">未成年span>
循环语句:
在应用控制器中绑定共享数据
request.setAttribute("list",userList);
在页面中通过 th:each 进行循环
- <table border="1" cellspacing="0" width="80%">
- <thead><th>编号th><th>姓名th><th>电话th>thead>
- <tbody>
- <tr th:each="obj:${list}">
- <td th:text="${obj.id}">td>
- <td th:text="${obj.name}">td>
- <td th:text="${obj.phone}">td>
- tr>
- tbody>