上一篇学习了spring boot的基本搭建与页面模板的小知识,今天我来学习一下mysql数据库的连接与数据交互
1.首先在.pom文件里依赖mysql与jdbc
2.application.properties里加入mysql数据库配置与基本信息,这些大家做过java项目的大家应该都知道
3.数据库里建好测试所需用的表
4.工程里建好所需用的实体类,字段与数据库表对应
public class User {
private int id ;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
5.编写控制层
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private JdbcTemplate jdbcTemplate;
@RequestMapping("/list")
public String list(ModelMap map){
//service与dao层省略
String sql = "select * from tbl_user";
List<User> list = jdbcTemplate.query(sql,new Object[]{},new BeanPropertyRowMapper<>(User.class));
map.addAttribute("list",list);
//返回模板文件所在路径及文件名
return "user/list";
}
@RequestMapping("/user/{userId}")
public String getUser(@PathVariable String userId,ModelMap map){
//service与dao层省略
String sql = "select * from tbl_user where id = " + userId;
User user = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<>(User.class));
map.addAttribute("user",user);
return "user/user";
}
}
6.html页面代码
6.1 list.html
<!DOCTYPE html>
**重点内容**
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>user list</title>
</head>
<body>
<table th:each="user:${list}">
<tr th:if="${user.id == 1}">
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.password}"></td>
</tr>
</table>
</body>
</html>
此段代码颇为重要,xmlns:th=”http://www.w3.org/1999/xhtml”
th标签的运用,大家可以百度一下
6.2 user.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
<meta charset="UTF-8">
<title>user detail</title>
</head>
<body>
<table>
<tr>
<td th:text="${user.id}"></td>
<td th:text="${user.name}"></td>
<td th:text="${user.password}"></td>
</tr>
</table>
</body>
</html>