关于Thymeleaf是什么:
1.Thymeleaf是一个流行的模板引擎,该模板引擎采用Java语言开发。除了thymeleaf之外还有Velocity、FreeMarker等模板引擎,功能类似。
2.Thymeleaf在有网络和无网络的环境下皆可运行,即它可以让美工在浏览器查看页面的静态效果,也可以让程序员在服务器查看带数据的动态页面效果。这是由于它支持 html 原型,然后在 html 标签里增加额外的属性来达到模板+数据的展示方式。浏览器解释 html 时会忽略未定义的标签属性,所以thymeleaf的模板可以静态地运行;当有数据返回到页面时,Thymeleaf 标签会动态地替换掉静态内容,使页面动态显示。
3.Thymeleaf开箱即用的特性。它提供标准和spring标准两种方言,可以直在这里插入代码片
接套用模板实现JSTL、OGNL表达式效果,避免每天套模板、改jstl、改标签的困扰。同时开发人员也可以扩展和创建自定义的方言。
Thymeleaf整合SpringBoot
**1.**第一步我们要在pom文件里添加依赖,引入thymeleaf
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
**2.**第二步我们要去项目属性文件(application.yml)配置thymeleaf
spring:
thymeleaf:
mode: HTML5
encoding: UTF-8
cache: false
prefix: classpath:/templates/demo/
**3.**第三步就要去controller新建一个映射来返回url的请求页面。
ppackage com.enlistentype.controller.demo;
import com.enlistentype.model.umodel.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class ThymeleafController {
@GetMapping("/test")
public String greetingForm(Model model) {
model.addAttribute("user", new User());
return "demo1";
}
}
很简单的几行代码,往前台传一个对象user。
**3.**第三步我们要新建一个thymeleaf模板,注意要放在application.yml配置的路径下,也就是resource的template。
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
<title>Title</title>
</head>
<body>
<form action="#" th:action="@{/authless/subLogin}" th:object="${user}" method="post">
<input type="text" th:field="*{userId}" />
<input type="text" th:field="*{password}" />
<input type="submit" />
</form>
</body>
</html>
也很简单,主要就是一个用来获取登录名和密码的表单,到这里基本算已经完成了,去访问8080/test就会得到一个有登录表单的页面,如果还想继续下一步就要再在一个controller文件去处理登录数据,再通过user对象返回到前台进行渲染。