簡單介紹SpringMVC RESTFul實現列表功能
SpringMVC RESTFul列表功能實現
一、增加控制器方法
在控制器類 EmployeeController 中,新增訪問列表方法。
@Controller public class EmployeeController { @Autowired private EmployeeDao employeeDao; @RequestMapping(value = "/employee", method = RequestMethod.GET) public String getAllEmployee(Model model) { CollectionemployeeList = 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 xmlns:th="員工資訊< /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> < !--迴圈後端放到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 的用法。
三、訪問列表頁
重新部署應用。
因為在首頁中,已經加了跳轉到列表頁的超連結,直接點選。
訪問成功,忽略掉好不好看的問題,起碼這是一個正常的列表。
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69901823/viewspace-2900087/,如需轉載,請註明出處,否則將追究法律責任。