发问:
模板引擎和前端框架的区别是什么?
解答:
1.JSP、Velocity、Thymeleaf等这是模板引擎,Jquery、Vue等这是前端框架。so,它们不一样。
2.缓存模板结构,在数据层操du作完直接套用模板输出到客户端界面中,减少dom操作的异常、减少拼接html的痛苦、减少各浏览器下dom操作的延迟差异 。这是模板引擎干的事情。
3.前端框架,提升开发效率,dom加载效率等。
发问:
为何选Thymeleaf,而抛弃了别的模板引擎比如JSP
解答:
1.SpringBoot默认整合Thymeleaf,不需要任何配置直接整合成功,打jar包发布不需要做任何配置。
2.Thymeleaf相对于其他的模板引擎(如:Freemaker、velocity),有强大的工具支持。
3.相对于Jsp页面,执行效率高。
引入,在pom文件中添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<properties>
<java.version>1.8</java.version>
<!-- 布局功能的支持程序 thymeleaf3主程序 对应 layout2以上版本 -->
<thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
<!-- thymeleaf2 对应 layout1版本 -->
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
</properties>
记录一个错误,是SpringBoot 和thumeleaf版本冲突的问题,这里需要把上面的切换版本配置改改
错误:An attempt was made to call the method org.thymeleaf.spring5.SpringTemplateEngine.setRenderHiddenMarkersBeforeCheckboxes(Z)V but it does not exist. Its class, org.thymeleaf.spring5.SpringTemplateEngine, is available from the following locations...
解决方案:
<properties>
<java.version>1.8</java.version>
<!-- 布局功能的支持程序 thymeleaf3主程序 对应 layout2以上版本 -->
<thymeleaf-spring5.version>3.0.9.RELEASE</thymeleaf-spring5.version>
<!-- thymeleaf2 对应 layout1版本 -->
<thymeleaf-layout-dialect.version>2.3.0</thymeleaf-layout-dialect.version>
</properties>
写一个小的测试,在Controller中添加一个访问,并在template目录下写个success.html
@RequestMapping("/success")
public String success() {
return "success";
}
使用http://localhost:8099/success,能够访问到页面内容就证明模板引擎配置ok了。
thymeleaf语法规则:
th:id="{}"
....
可以看到,我们可以使用th:**的方式替换原有的html属性,其余更多参考thymeleaf的官方文档,c:forEach 遍历,c:set 生命变量,c:if判断,jsp:include 片段包含.....。还有一些表达式语法的说明 ${} 获取对象的属性,调用方法。
success.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>成功</h1>
<!--/*@thymesVar id="hello" type=""*/-->
<div id="div01" class="mDiv" th:id="${hello}" th:class="${hello}" th:text="${hello}">这是个啥</div>
<hr>
<div th:text="${hello}">页面上的值</div>
<div th:utext="${hello}">另一种方式</div>
<hr>
<!--th:each 每次遍历都会生成这个标签-->
<h4 th:text="${user}" th:each="user:${user}"></h4>
<hr>
<h4>
<span th:each="user:${user}">[[${user}]]</span>
</h4>
</body>
</html>
HelloController
@Controller
public class HelloWorld {
@ResponseBody
@RequestMapping("/hello")
public String hello() {
return "Hello this is HelloWorld";
}
@RequestMapping("/success")
public String success(Map<String, Object> map) {
map.put("hello", "后端的内容");
map.put("user", Arrays.asList("张三", "李四", "王五", "陈粒"));
return "success";
}
}
简单的小例子,验证配置没有问题,更强大的功能在后续的复杂案例中再继续学习。
网友评论