Spring Boot 教程(四): Spring Boot 整合 thymeleaf MyBatis,展示用户信息

教程简介

本项目内容为Spring Boot教程样例。目的是通过学习本系列教程,读者可以从0到1掌握spring boot的知识,并且可以运用到项目中。如您觉得该项目对您有用,欢迎点击收藏和点赞按钮,给予支持!!教程连载中,欢迎持续关注!

环境

IDE: Eclipse Neon
Java: 1.8
Spring Boot: 1.5.12
数据库:MYSQL

本章简介

上一节介绍了spring boot整合mybatis,本节将在此基础上整合thymeleaf,完成前端展示用户信息。

配置

在pom.xml文件下面添加:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

修改application.properties

# THYMELEAF
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
#开发时关闭缓存
spring.thymeleaf.cache=false

编写UserMapper

在UserMapper下面添加查询User方法

@Select("SELECT * FROM T_USER")
    List<User> findAll();

编写控制器方法

在UserController下面添加getUserList方法。
由于上一节我们使用了@RestController的注解,@RestController的注解是无法通过视图解析器解析视图的,所以我们修改成@Controller, 其他方法我们使用@ResponseBody的注解。

@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

Spring Boot 教程(四): Spring Boot 整合 thymeleaf  MyBatis,展示用户信息

打开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
浏览器展示:
Spring Boot 教程(四): Spring Boot 整合 thymeleaf  MyBatis,展示用户信息

本节的目的已经完成。需要注意的是thymeleaf拥有强大语法,值得注意的是html标签需要修改成

<html xmlns:th="http://www.thymeleaf.org">

以下是官方文档,可供读者学习thymeleaf语法
https://www.thymeleaf.org/doc...

代码:gitee.com/shaojiepeng/SpringBootCourse

相关推荐