推荐阅读
开发传统Java WEB工程时,我们可以使用JSP页面模板语言,但是在SpringBoot中已经不推荐使用了。SpringBoot支持如下页面模板语言
- Thymeleaf
- FreeMarker
- Velocity
- Groovy
- JSP
上面并没有列举所有SpringBoot支持的页面模板技术。其中Thymeleaf是SpringBoot官方所推荐使用的,下面来谈谈Thymeleaf一些常用的语法规则。
一. 添加Thymeleaf依赖
要想使用Thhymeleaf,首先要在pom.xml文件中单独添加Thymeleaf依赖。
<dependency>
<groupId>org.springframework. boot</groupId>
<artifactId>spring-boot-starter-thymeleaf </artifactId>
</dependency>
Spring Boot默认存放模板页面的路径在src/main/resources/templates或者src/main/view/templates,这个无论是使
用什么模板语言都一样,当然默认路径是可以自定义的,不过一般不推荐这样做。另外Thymeleaf默认的页面文件后缀是.html。
二. 数据显示
在MVC的开发过程中,我们经常需要通过Controller将数据传递到页面中,让页面进行动态展示。
1. 显示普通文本
创建一个Controller对象,在其中进行参数的传递
@Controller
public class ThymeleafController {
@RequestMapping(value = "show", method = RequestMethod.GET)
public String show(Model model){
model.addAttribute("uid","123456789");
model.addAttribute("name","Jerry");
return "show";
}
}
在SpringBoot默认的页面路径下创建show.html文件,内容如下
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>SpringBoot模版渲染</title>
<meta http-equiv="Content-Type" content= "text/html;charset=UTF-8"/>
</head>
<body>
<p th:text="'用户ID:' + ${uid}"/>
<p th:text="'用户名称:' + ${name}"/>
</body>
</html>
可以看到在p标签中有th:text属性,这个就是thymeleaf的语法,它表示显示一个普通的文本信息。
如果我们要显示的信息是存在资源文件中的,同样可以在页面中显示,例如资源文件中定义了内容welcome.msg=欢迎{0}光临!。可以在页面中将其显示
<h2 th:text="#{welcome.msg('admin')}"/>
另外,在th:utext中还能做一些基础的数学运算
<p th:text="'数学计算:1+2=' + (1 + 2)"/>
2. 显示带有样式的普通文本
如果我们想要传递到的页面的信息,它本身是带有CSS样式的,这个时候如何在页面中将携带的样式信息也显示出来?此时我们的控制器方法这样写。
@RequestMapping(value = "showStyle", method = RequestMethod.GET)
public String showStyle(Model model){
model.addAttribute("uid","123456789&