【SpringMVC 从 0 开始】SpringMVC RESTFul 实战案例 - 实现列表功能
2021/8/18 23:36:41
本文主要是介绍【SpringMVC 从 0 开始】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> <!--循环后端放到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 从 0 开始】SpringMVC RESTFul 实战案例 - 实现列表功能的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?