前言:
thymeleaf 是由thyme [ta?m] (百里香) ,leaf[li:f] (葉子)兩個(gè)單詞組成.
thymeleaf 是java模版引擎屋群,可以很好的和spring集成雏门。
1. 引入依賴(lài)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2. application.properties中添加配置
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.check-template-location=true
spring.thymeleaf.suffix=.html
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
spring.thymeleaf.mode=HTML
注:
Spring Boot使用的Thymeleaf 3.0或者更高版本是配置:spring.thymeleaf.mode=HTML伤柄。
如果Thymeleaf 2.0版本的話配置:spring.thymeleaf.mode=HTML5牧氮。
3. 創(chuàng)建Controller 象泵,和相應(yīng)html寞秃。
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/login")
public String login() {
return "/login";
}
}
上面返回/login
,即返回對(duì)應(yīng)login.html偶惠,
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>登錄頁(yè)面</title>
</head>
<body>
<H2>登錄測(cè)試</H2>
</body>
</html>
如果頁(yè)面需要使用thymeleaf需要添加命名空間xmlns:th="http://www.thymeleaf.org"
4.運(yùn)行測(cè)試春寿,訪問(wèn)'http://localhost:8080/user/login',效果如圖:
1.png
5.后臺(tái)用過(guò)模版引擎?zhèn)鬟f參數(shù)給頁(yè)面
- 后臺(tái)添加參數(shù)忽孽。筆者在 在上面的UserController添加方法绑改,并設(shè)置參數(shù):
@RequestMapping(value = "/login2")
public String login2(ModelMap map) {
Map<String, Object> userInfoMap = new HashMap<>();
userInfoMap.put("name", "張三");
userInfoMap.put("age", 24);
SimpleVo vo = new SimpleVo();
vo.setCode(1000);
vo.setMessage("請(qǐng)求成功");
map.put("userInfo", userInfoMap);
map.put("vo", vo);
return "/login2";
}
- 對(duì)應(yīng)login2.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>thymeleaf模版,帶數(shù)據(jù)的</title>
</head>
用戶(hù)名:<span th:text="${userInfo.name}"></span><br/>
年齡:<span th:text="${userInfo.age}"></span><p />
訪問(wèn)對(duì)象屬性:<span th:text="${vo.code}"/> ,訪問(wèn)對(duì)象方法:<span th:text="${vo.getMessage()}"/><p />
<a th:href="@{/user/login}">相對(duì)路徑頁(yè)面測(cè)試</a><p/>
<a th:href="@{http://www.baidu.com}">據(jù)對(duì)路徑測(cè)試(比如訪問(wèn):百度)</a><p/>
</body>
</html>
-
運(yùn)行效果如圖:
2.png