linux idea spring boot 學習筆記2-mysql數據庫

上一篇學習了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){

        //servicedao層省略
        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){

        //servicedao層省略
        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>

7.頁面展示效果

7.1 list

這裏寫圖片描述

7.2 user

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章