springboot第六天---SpringBoot使用spring data jpa,並將數據顯示到頁面上


spring boot 整合spring Data JPA 頁面 yaml

做測試或者項目之前先捋一遍思路在下手,這樣出錯可以迅速查找到哪一步代碼出錯

1.1 需求 :查詢數據庫 ---》數據------》展示到頁面上

1.2 分析

1 創建數據庫 user表

2 持久層框架 spring data jpa

3 json jsp 靜態html freemarker

1.3頁面展示

HTML展示數據 vue.js angular.js

動態頁面顯示 :每次請求都生成一次頁面

jsp 本質上就是servlet 工程web 工程-

springbooot 項目工程中不推薦使用jsp

模板技術 freemarker

tymeleaf

velocity

使用步驟:

a : 添加依賴

b: 創建模板文件 保存位置resources/templates 目錄下 文件后綴名.ftl

c 編寫controller 把結果傳遞給模板

1.4 yaml 文件格式

key --value

1.4.1 語法 key: value

key1:

key2:

key3: value

1.4.2 取屬性值

@Value("${key2}")

按照思路走:

1.添加依賴:

https://www.cnblogs.com/xinghaonan/p/11798238.html

前邊博客已寫,請自行添加

2: 創建模板文件 (必須:springboot約束大於配置)保存位置resources/templates 目錄下 文件后綴名.ftl

 

 

代碼書寫

 

 

<html>
    <head>
        <title> spring boot</title>
    </head>
    <body>
        <table border="3px">
            <thead>
                <tr>
                    <th>id</th>
                    <th>賬號</th>
                    <th>密碼</th>
                    <th>名字</th>
                </tr>
            </thead>
            <#list userList as user >    <!--userList為controller中添加到域對象中的數據-->
                <tbody>
                <tr>
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td>${user.password}</td>
                    <td>${user.name}</td>
                </tr>
                </tbody>
            </#list>
        </table>
    </body>
</html>

 

創建Controller接口

package com.xhn.controller;

import com.xhn.dao.UserDao;
import com.xhn.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/page")
public class PageUserController {

    @Autowired
    private UserDao userDao;

    //查詢數據庫數據
    @RequestMapping("/user/list")
    public String getUserList(ModelMap map){
        List<User> userList = userDao.findAll();
        map.addAttribute("userList",userList);
        return "user"; //類似於springmvc中的內部視圖解析器,前后綴都不用寫
    }
}

 

 

 

 UserDao層:

https://www.cnblogs.com/xinghaonan/p/11799854.html

前一天筆記中有寫,不再重復

運行結果圖:

 

 完成

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM