上一篇文章简单展现自己写的列表;
这篇文章连接mysql数据库实现数据库数据展现
主要三个文件
controller指定html界面
package com.example.appledemo.controller;
import com.example.appledemo.mapper.UserMapper;
import com.example.appledemo.pojo.User;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.Model;
import java.util.ArrayList;
import java.util.List;
@Controller
public class TestController {
@Resource
UserMapper userMapper;
@RequestMapping("/login")
public String login(Model model){
List<User> user = userMapper.findAll();
model.addAttribute("user",user);
return "login";
}
}
mapper写数据库sql查询语句
package com.example.appledemo.mapper;
import com.example.appledemo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user")
List<User> findAll();
}
pojo中的user写具体数据库中的表包含哪些字段(这部分最好的方式写出变量名字然后alt+insert自动生成getter和setter不容易出错)
package com.example.appledemo.pojo;
import lombok.Getter;
@Getter
public class User {
private Integer userId;
private String userName;
private String userPass;
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@Override
public String toString() {
return "User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", userPass='" + userPass + '\'' +
'}';
}
}
最后写个login.html展现数据
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>springboot-thymeleaf demo</title>
</head>
<body>
<table border="1" width="1000">
<tr th:each="item,eee: ${user}">
<td th:text="${item.userId}"></td>
<td th:text="${item.userName}"></td>
<td th:text="${item.userPass}"></td>
</tr>
</table>
</body>
</html>
</html>
给出文件列表:
最后给出运行结果: