1)首先添加Thymeleaf依赖
<!--thymeleaf模板-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
2)在application.properies文件 中添加配置
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.cache=false
3)首先编写前端代码 login.html和list.html文件
login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<!-- ${result} 动态字-->
<p th:text="'' + ${result}"/>
</div>
<!-- @{/login} 会直接访问 项目下的login接口-->
<form th:action="@{/login}" method="post">
<div>
<input id="user_name" name="userName" type="text" placeholder="用户名" aria-describedby="basic-addon1"/>
</div>
<br/>
<div>
<input id="password" name="password" type="password" placeholder="密码" aria-describedby="basic-addon2"/>
</div>
<br/>
<button type="submit" style="width:190px;">登 录</button>
</form>
</body>
</html>
list.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>列表</title>
</head>
<body>
<div>
<p th:text="'欢迎:' + ${name}"/>
</div>
<table border="1" bgcolor="#f0ffff">
<thead>
<tr>
<th>借阅时间</th>
<th>标题</th>
<th>作者</th>
</tr>
</thead>
<tbody th:each="book : ${list}">
<tr>
<td th:text="${book.data}"></td>
<td th:text="${book.title}"></td>
<td th:text="${book.author}"></td>
</tr>
</tbody>
</table>
</body>
</html>
4)我们看下后端代码
@Controller
public class ThymeleafController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* @RequestMapping("/login.html") 就可以直接访问login.html了
* Model : 将传入下一个页面
*/
@RequestMapping("/login.html")
public String loginHtml(Model model) {
model.addAttribute("result", "登陆页面");
return "login";
}
@RequestMapping(value = "login", method = RequestMethod.POST)
public String login(Model model,
@RequestParam("userName") String name,
@RequestParam("password") String psw) {
logger.info("name = " +name+"; psw = " +psw);
if(name.equals("malei") && psw.equals("123456")){
List<BookInfo> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
BookInfo bookInfo = new BookInfo();
bookInfo.title = "小王子";
bookInfo.author = "老外";
bookInfo.data = "2019/09/12";
list.add(bookInfo);
}
model.addAttribute("list", list);
model.addAttribute("name", name);
return "list";
}
model.addAttribute("result","登陆失败");
return "login";
}
}