SpringMVC?RESTFul實現列表功能
更新時間:2022年05月28日 15:07:06 作者:把蘋果咬哭的測試筆記
這篇文章主要為大家介紹了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" style="text-align: center;">
<tr>
<th colspan="5">員工列表</th>
</tr>
<tr>
<th>id</th>
<th>lastName</th>
<th>email</th>
<th>gender</th>
<th>options</th>
</tr>
<!--循環(huán)后端放到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>- 這里使用了簡單的樣式,使其看起來更像個列表。
- 每一行的數據,要通過循環(huán)后端放到 request 域中的數據 employeeList,得到單個對象 employee,然后就可以將對象的屬性獲取出來展示, 比如 employee.id 。
- th:each,${}這些都是 thymeleaf 的用法。
三、訪問列表頁
重新部署應用。

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

訪問成功,忽略掉好不好看的問題,起碼這是一個正常的列表。
感謝《尚硅谷》的學習資源,更多關于SpringMVC RESTFul列表的資料請關注腳本之家其它相關文章!
相關文章
Spring?Boot+RabbitMQ?通過fanout模式實現消息接收功能(支持消費者多實例部署)
這篇文章主要介紹了Spring?Boot+RabbitMQ?通過fanout模式實現消息接收(支持消費者多實例部署),本文通過案例場景分析給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-03-03
Spring?Boot?實現?WebSocket?的代碼示例
WebSocket?協議是獨立的基于?TCP?協議。它與?HTTP?的唯一關系是,它的握手會被?HTTP?服務器解釋為?Upgrade?請求,接下來通過本文給大家介紹Spring?Boot?實現?WebSocket?示例詳解,需要的朋友可以參考下2022-04-04
SpringBoot整合TKMyBatis實現單表增刪改查操作
據說tk.mybatis能夠讓我不寫sql代碼就可以所有單表操作問題,作為熱愛偷懶的我,怎么能放過這種機會。talk is cheap, show me the code。趕緊搞個例子爽一把先2023-01-01

