文章目录
关于Thmeleaf
Thymeleaf是一个现代服务器端Java模板引擎,适用于Web和独立环境,能够处理HTML,XML,JavaScript,CSS甚至纯文本。推荐在SpringBoot中使用Thymeleaf的原因就是因为它能不破坏原生html的结构,同时允许前端开发者随时查看网页的静态结构。
在SpringBoot项目中配置Thymeleaf
①创建工程后,导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<scope>test</scope>
</dependency>
②创建实体类User
这里需要注意,在html中以${users}的方式获取后台的数据,如果要获取user.userName那么在User类中必须有对应的get方法,否则是会报错的。
package com.example.thymeleaf;
public class User {
String userName;
String passWord;
public User(String u,String p){
this.userName=u;
this.passWord=p;
}
public String getUserName(){
return this.userName;
}
public String getPassWord(){
return this.passWord;
}
}
③创建controller
向前端返回数据,注意@RestController和Controller的区别,requestMapping和GetMapping的区别,否则可能会导致运行报错;
package com.example.thymeleaf;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class UserController {
@GetMapping("/test")
public ModelAndView testUser(){
User user=new User("root","root");
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("users",user);
return modelAndView;
}
}
④在resource的template目录下创建对应的html
需要注意的是需要引入thymeleaf的名称空间,thymeleaf的标签与html也有些区别,对于其语法,就需要另外学习了
<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<title data-l10n-id="helloWorld"></title>
</head>
<body>
<table>
<tr>
<th>用户名</th>
<th>密码</th>
</tr>
<tr th:each="users:${users}">
<td th:text="${users.userName}"></td>
<td th:text="${users.passWord}"></td>
</tr>
</tr>
</table>
</body>
</html>