七、模板引擎
1.简介
目前Java Web开发推荐使用模板引擎,不建议使用jsp页面
- jsp的缺点:本质时Servlet,需要后台进行编译,效率较低
- 模板引擎:不需要编译,速度快
常用的模板引擎:Freemarker、Thymeleaf等
SpringBoot推荐Thymeleaf,且默认不支持jsp,因为jsp必须要打成war包。
补充:目前主流的web开发更推荐前后端分离,前端使用MVVM框架,Vue.js、Angular、React等
2.Thymeleaf的使用
步骤:
1.添加Thymeleaf的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
2.将html页面放到templates下
templates下的html不能直接访问,需要使用Controller跳转,由Thymeleaf进行渲染
ThymeleafAutoConfiguration—>ThymeleafProperties
public static final String DEFAULT_PREFIX = "classpath:/templates/";public static final String DEFAULT_SUFFIX = ".html";
默认拼接前缀和后缀
3.使用thymeleaf
<!DOCTYPE html><html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <h2>success</h2> <!--使用th:text属性设置元素中的文本,表达式:${}可以获取作用域中的数据--> <p th:text="${name}"></p></body></html>
4.修改页面后,让其实时生效
由于thymeleaf默认启用了缓存,将缓存禁用掉
#禁用thymeleaf的缓存spring.thymeleaf.cache=false
补充:还需要开启idea的自动编译,idea默认保存时不会自动编译
3.语法规则
3.1 常用属性
- th:text、th:utext
- 设置元素中的文本内容
- th:text对特殊字符进行转义,等价于内联方式[[${ }]]
- th:utext不对特殊字符集进行转义,等价于内联方式[(${ })]
<!DOCTYPE html><html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"><head> <meta charset="UTF-8"> <title>Title</title></head><body> <!--th:text、th:utext--> <div th:text="${hello}">aaa</div> <div th:utext="${hello}">bbb</div> <!--使用内联方式,可以在文本前后添加内容--> <div>[[${hello}]]aaa</div> <div>[(${hello})]bbb</div></body></html>
- th:html原生属性
- 用来替换指定的html原生属性的值
@RequestMapping("/test2")public String test2(Model model){ model.addAttribute("hello", "<mark>你好</mark>"); model.addAttribute("id", "mydiv"); model.addAttribute("title", "this is a div"); return "result";}<!--th:html原生属性--><div id="div1" title="这是一个div" th:id="${id}" th:title="${title}">div</div>
- th:if、th:unless、th:switch、th:case
- 条件判断,类似于if
<!--th:if、th:unless、th:switch、th:case--><div th:if="${age>=18}">成年</div><p th:unless="${age<18}">成年</p><p th:switch="${role}"> <span th:case="student">学生</span> <span th:case="teacher">老师</span> <span th:case="*">其他</span></p><hr>
- th:each
- 循环,类似于for each
<!--th:each--><ul> <li th:each="name:${names}" th:text="${name}"></li></ul>
- th:object、th:field
- 用于表单数据对象的绑定,将表单绑定到Controller的一个JavaBean参数,常与th:field
- 一起使用,需要和*{}选择表达式配合使用
<!--th:object、th:field--><h2>修改用户信息</h2><!--th:object指定对象,th:field指定属性--><form action="modify" method="post" th:object="${user}"> 编号:<input type="text" th:field="*{id}" readonly> <br> 姓名:<input type="text" th:field="*{name}"> <br> 年龄:<input type="text" th:field="*{age}"> <br> <input type="submit" value="修改"></form>
- th:fragment
- 声明代码片段,常用于页面头部和尾部的引入
<!--th:fragment--><header th:fragment="head"> 这是页面的头部,导航</header>
- th:include、th:insert、th:replace
- 引入代码片段,类似于jsp:include
<!--th:include、th:insert、th:replace--><!--引入templates/include下的header.html页面中的fragment为head的片段--><div th:include="include/header::head"></div>
- 三者之间的区别
th:incl