溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringMVC?RESTFul如何實現列表功能

發布時間:2022-05-30 09:48:20 來源:億速云 閱讀:250 作者:iii 欄目:開發技術

本文小編為大家詳細介紹“SpringMVC RESTFul如何實現列表功能”,內容詳細,步驟清晰,細節處理妥當,希望這篇“SpringMVC RESTFul如何實現列表功能”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。

SpringMVC RESTFul列表功能實現

一、增加控制器方法

在控制器類 EmployeeController 中,添加訪問列表方法。

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeDao employeeDao;
    @RequestMapping(value = "/employee", method = RequestMethod.GET)
    public String getAllEmployee(Model model) {
        Collection<Employee> employeeList = employeeDao.getAll();
        model.addAttribute("employeeList", employeeList);
        return "employee_list";
    }
}
  • 這里就沒寫 service 層了,直接在 getAllEmployee() 方法中操作 dao 層,也就是調用 employeeDao.getAll()來獲取所有員工信息,返回是一個列表集合。

  • 接著把數據放到 request 域里,供前端頁面使用,這里使用前面講過的 Model 方法。

  • 在model.addAttribute("employeeList", employeeList); 中,2個分別對應 key - value,頁面里使用 key 可以獲取到 value 。

  • 最后返回 employee_list 頁面。

二、編寫列表頁 employee_list.html

控制器里返回了 employee_list ,這是一個 html 頁面,依然寫在 templates 下面:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>員工信息</title>
</head>
<body>
    <table border="1" cellspacing="0" cellpadding="0" >
        <tr>
            <th colspan="5">員工列表</th>
        </tr>
        <tr>
            <th>id</th>
            <th>lastName</th>
            <th>email</th>
            <th>gender</th>
            <th>options</th>
        </tr>
        <!--循環后端放到request域中的數據 employeeList-->
        <tr th:each="employee : ${employeeList}">
            <td th:text="${employee.id}"></td>
            <td th:text="${employee.lastName}"></td>
            <td th:text="${employee.email}"></td>
            <td th:text="${employee.gender}"></td>
            <td>
                <a href="">刪除</a>
                <a href="">更新</a>
            </td>
        </tr>
    </table>
</body>
</html>
  • 這里使用了簡單的樣式,使其看起來更像個列表。

  • 每一行的數據,要通過循環后端放到 request 域中的數據 employeeList,得到單個對象 employee,然后就可以將對象的屬性獲取出來展示, 比如 employee.id 。

  • th:each,${}這些都是 thymeleaf 的用法。

三、訪問列表頁

重新部署應用。

SpringMVC?RESTFul如何實現列表功能

因為在首頁中,已經加了跳轉到列表頁的超鏈接,直接點擊。

SpringMVC?RESTFul如何實現列表功能

訪問成功,忽略掉好不好看的問題,起碼這是一個正常的列表。

讀到這里,這篇“SpringMVC RESTFul如何實現列表功能”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女