1.引入依赖
在maven(pom.xml)中直接引入:
也可以在创建项目时候勾选thymeleaf模板,这样会自动生成。
2.配置视图解析器
(1)默认
spring-boot很多配置都有默认配置,比如默认页面映射路径为
classpath:/templates/*.html
同样静态文件路径为
classpath:/static/
(2)自定义
在application.properties(或者application.yml)中可以配置thymeleaf模板解析器属性.就像使用springMVC的JSP解析器配置一样
按 Ctrl+C 复制代码
#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
#thymeleaf end
按 Ctrl+C 复制代码
具体可以配置的参数可以查看 org.springframework.boot.autoconfigure.thymeleaf.ThymeleafProperties 这个类,上面的配置实际上就是注入到该类中的属性值.
3.编写demo来说明使用方法
(1)控制器
复制代码
1 @Controller
2 public class HelloController(){
3 @RequestMapping(value = "/")
4 public String index(){
5 return "index";
6 }
7 }
复制代码
这样会返回一个新的视图页面index.html,当然也可以使用下面的方法
复制代码
@RequestConteoller
public class HelloController(){
@RequestMapping(value = "/")
public ModelAndView index(){
return new ModelAndView("index");
}
}
复制代码
这样能直接返回整个index页面。
注意,在html标签里一定要引入 xmlns:th="http://www.thymeleaf.org" ,这样thymeleaf模板才会启用。至于thymeleaf的具体使用方法,以后在讲。
(3)测试
访问 localhost:8080/ 这个地址,会直接跳转到 index.html 页面,并显示如下
4.基础语法
(1)引入标签
首先要在html标签里引入xmlns:th="http://www.thymeleaf.org"才能使用th:*这样的语法。
(2)获取变量值
通过在标签内部,使用 ${} 来取值,对于javaBean的话,使用 变量名.属性名 来获取,跟EL表达式一样
注意:只有写在标签内部才会生效,例如: th:text=“hello” 的意思是使用hello来代替p之前的内容,p里原来的值是为了给前端开发展示用的,这样做容易实现前后端分离。
(3)引入URL
thymeleaf对于引入URL是采用@{...}来获取的
例如: <a th:href="@{http://www.baidu.com}">绝对路径</a> 是访问绝对路径下的URL, <a th:href="@{/}">相对路径</a> 是访问相对路径下的URL。
<a th:href="@{css/bootstrap.min.css}"> 是引入默认的static下的css文件夹下的bootstrap文件,类似的标签有: th:href 和 th:src
(4)字符串替换
例如使用: <span th:text="'Welcome to our application, ' + ${user.name} + '!'"></span> 或者
<span th:text="|Welcome