本项目内容为Spring Boot教程样例。目的是经过学习本系列教程,读者能够从0到1掌握spring boot的知识,而且能够运用到项目中。如您以为该项目对您有用,欢迎点击收藏和点赞按钮,给予支持!!教程连载中,欢迎持续关注!html
IDE: Eclipse Neon
Java: 1.8
Spring Boot: 1.5.12
数据库:MYSQL前端
上一节介绍了spring boot整合mybatis,本节将在此基础上整合thymeleaf,完成前端展现用户信息。git
在pom.xml文件下面添加:spring
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
# THYMELEAF spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html spring.thymeleaf.mode=HTML5 spring.thymeleaf.encoding=UTF-8 #开发时关闭缓存 spring.thymeleaf.cache=false
在UserMapper下面添加查询User方法数据库
@Select("SELECT * FROM T_USER") List<User> findAll();
在UserController下面添加getUserList方法。
因为上一节咱们使用了@RestController的注解,@RestController的注解是没法经过视图解析器解析视图的,因此咱们修改为@Controller, 其余方法咱们使用@ResponseBody的注解。segmentfault
@Controller public class UserController { @Autowired private UserMapper userMapper; @RequestMapping("/saveUser") @ResponseBody public void save() { userMapper.save("ajay", "123456"); } @RequestMapping("/findByName") @ResponseBody public User findByName(String name) { return userMapper.findByName(name); } @RequestMapping("/userList") public String getUserList(Model model){ model.addAttribute("users", userMapper.findAll()); return "user/list"; } }
在src/main/resources/templates下添加user文件夹,再添加list.html浏览器
打开list.html,添加以下代码:缓存
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"> <head> <meta name="viewport" content="width=device-width,initial-scale=1"/> <meta charset="UTF-8"/> <title>用户信息</title> </head> <body> <table border="1"> <tr> <th>id</th> <th>姓名</th> <th>密码</th> </tr> <tr th:each="user:${users}"> <td><span th:text="${user.id}"></span></td> <td><span th:text="${user.name}"></span></td> <td><span th:text="${user.pass}"></span></td> </tr> </table> </body> </html>
在Application类中,启动程序。浏览器输入 http://localhost:8080/userList
浏览器展现:mybatis
本节的目的已经完成。须要注意的是thymeleaf拥有强大语法,值得注意的是html标签须要修改为app
<html xmlns:th="http://www.thymeleaf.org">
如下是官方文档,可供读者学习thymeleaf语法
https://www.thymeleaf.org/doc...
代码:gitee.com/shaojiepeng/SpringBootCourse