SpringBoot 中增删查改功能与以往的SpringMVC或者SSM框架相比,查询和添加功能没有变化,主要是修改和删除功能的 提交方式变了 ,但 总体思路不变。
一、查询功能
将所有数据查询到列表上,需要用到getAll()方法将所有数据查询出来。
查询的相关代码:
//查询所有员工返回列表页面,查询是去获取数据,所以用的是GetMapping
@GetMapping("/emps")
public String list(Model model){
Collection<Employee> employees = employeeDao.getAll();
//放在请求域中
model.addAttribute("emps",employees);
// thymeleaf默认就会拼串
// classpath:/templates/xxxx.html
return "list";//list是列表页面
}
查询页面:
(注意这里的日期格式要按照自己自定义的格式进行指定,不然会出现数据格式不对错误提示。)
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
<h2><button class="btn btn-sm btn-success" >员工添加</button></h2>
<div class="table-responsive">
<table class="table table-striped table-sm">
<thead>
<tr>
<th>员工编号</th>
<th>姓名</th>
<th>邮箱</th>
<th>性别</th>
<th>部门</th>
<th>出生日期</th>
<td>操作</td>
</tr>
</thead>
<tbody>
<!-- 遍历所有数据用thymeleaf中的 th:each 去显示,emp 是接收从请求域 emps 中取出来的数据-->
<tr th:each="emp:${emps}">
<td th:text="${emp.id}"></td>
<td th:text="${emp.lastName}"></td>
<td >[[${emp.email}]]</td>
<td th:text="${emp.gender}==0?'女':'男'"></td>
<td th:text="${emp.department.departmentName}"></td>
<td th:text="${#dates.format(emp.birth,'yyyy-MM-dd hh:mm:ss')}"></td>
<td>
<button class="btn btn-sm btn-primary" >编辑</button>
<button class="btn btn-sm btn-danger " >删除</button>
</td>
</tr>
</tbody>
</table>
</div>
</main>
二、添加功能
进入到添加页面,添加一条数据,然后将所有数据回显在列表上。
添加的相关代码:
//来到员工添加页面
@GetMapping("/emp")
public String toAddPage(Model model){
//来到添加页面,查出所有的部门,在页面显示
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("depts",departments);
return "add";
}
//员工添加
//SpringMVC自动将请求参数和入参对象的属性进行一一绑定;要求请求参数的名字和javaBean入参的对象里面的属性名是一样的
@PostMapping("/emp")
public String addEmp(Employee employee){
//来到员工列表页面
System.out.println("保存的员工信息:"+employee);