在web大行其道的今天,有了接口之后最好的展示方式就是用页面。而Spring Boot中对于模板页有良好的支持。下面我们来介绍Spring Boot推荐的模板 thymeleaf。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
需要注意,为了让thymeleaf识别一个模板,你必须使用下面的html头标签:
<html xmlns:th="http://www.thymeleaf.org">
...
</html>
<script th:inline="javascript">
var article = [[${article}]];
...
</script>
首先我们在resources目录下新建templates文件夹和static文件夹。
关于这两个文件夹,在Spring Boot中,静态资源默认是访问resources下的static文件夹,动态html资源默认是访问resourcess目录下的templates。当然这两个默认路径可以再application.yml中进行配置,一般我们都使用默认路径。由于我们需要的是一个由Spring Boot生成的动态模板页,因此在templates下新建demo1.html。
由于动态模板页需要先经过后台接口,然后才返回一个html页面到前端,因此在controller文件夹下新建ThymeleafController.java。
@Controller
public class ThymeleafController {
@GetMapping("/thymeleaf")
public String testMapper() {
return "demo1";
}
}
注意我们使用了@Controller而不是@RestController。具体的区别请查看Spring Boot从入门到精通-注解详解。
写了一个路径为/thymeleaf的接口,该接口直接返回了一个值为我们需要返回的html的名字的字符串。
目录结构如下:
目录结构
<p th:text="'你好,thymeleaf~~~'"> hello world!</p>
@GetMapping(value = "thymeleaf")
public String articleInfo(Model model) {
model.addAttribute("data", "i'm a data");
User user = new User();
user.setUserId(1);
user.setUserName("admin");
user.setPassword("123");
user.setPhone("110");
model.addAttribute("user", user);
return "demo1";
}
在方法上新增了一个入参model,通过model传递前端需要的值。而这个“data”就是前端的变量名。
<h1 th:text="'hello,' + ${data} + '!'">测试文本!</h1>
<h1 th:text="'标号:'+ ${user.userId}">id</h1>
另外也可以在JavaScript中直接使用对象接收。
home.data: i'm other data
html上的代码:
<h1 th:text="#{home.data}">你好,这是一条消息</h1>
<p th:if="${user.userId} >= 1">用户的id大于1,于1,所以能显示这些</p>
<p th:unless="${user.userName == null }">当“用户名称为空”这个条件不成立就显示, 用户名为:<span th:text="${user.userName}">用户名</span></p>
<div th:switch="${user.userName}">
<h1><p th:case="admin">他是管理员</p></h1>
<h1><p th:case="admin2">这是第二个</p></h1>
<h1><p th:case="*">你是游客</p></h1>
</div>
你的操作系统语言环境为:
<span th:text="${#locale.language}"></span>,<span th:text="${#locale.displayCountry}"></span>,<span th:text="${#ctx.locale}"></span>