spring boot 使用thymeleaf模板
maven工程项目结构
引入thymeleaf模板
pom.xml文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-thymeleaf模板->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
修改application.yml
spring:
thymeleaf:
cache: false
mode: HTML5
content-type: text/html
encoding: UTF-8
ThymeLeafController.java
文件
@Controller
public class ThymeLeafController {
@RequestMapping("/index")
public String index(Model model){
List<User> userList = new ArrayList<>();
for (int i=0; i < 9; i++){
User user = new User();
user.setFirstName("Mark-"+i);
user.setLastName("Otto-"+i);
user.setEmail(i+"-@mdo");
userList.add(user);
}
model.addAttribute("userList", userList);
model.addAttribute("tableName","用户信息表");
return "home/index";
}
}
User.java
文件
public class User implements Serializable {
private static final long serialVersionUID = -8247895014315042187L;
private String firstName;
private String lastName;
private String email;
//getter and setter...
}
index.html
文件
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>spring boot 使用thymeleaf模板</title>
<!-- Bootstrap -->
<link th:href="@{/assets/bootstrap-3.3.5-dist/css/bootstrap.css}" rel="stylesheet" />
<script th:src="@{/js/jquery-3.2.1.js}"></script>
<script th:src="@{/assets/bootstrap-3.3.5-dist/js/bootstrap.js}"></script>
</head>
<body>
<div style="width: 400px; height: 300px; margin-left: 300px; margin-top: 100px;">
<h1 th:text="${tableName}"></h1>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>#</th>
<th>id</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
<tr th:each="user, iterRow: ${userList}">
<td th:text="${iterRow.odd} ? '奇数': '偶数'"></td>
<td th:text="${iterRow.index}"></td>
<td th:text="${user.firstName}"></td>
<td th:text="${user.lastName}"></td>
<td th:text="${user.email}"></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
注意:修改html标签头:<html xmlns:th="http://www.thymeleaf.org">
访问
http://localhost:8080/index
效果截图:
问题
使用thymeleaf模板时变量下会有波浪线
解决方案
在file->settings->inspection
中找到thymeleaf
项,取消选中的钩即可