springboot搁置了好久好久,以至于都快忘了接口怎么写的了,抓紧时间拾回来~
员工信息修改
我们要实现员工修改功能,需要实现两步
1、点击修改按钮,去到编辑页面,我们可以直接使用添加员工的页面实现
2、显示原数据,修改完毕后跳回列表页面
实现
1、首先修改跳转链接的位置
<a class="btn btn-sm btn-primary" th:href="@{'/emp/'+${emp.getId()}}">编辑</a>
2、编写对应的controller
//去员工的修改页面
@GetMapping("/emp/{id}")
public String toUpdateEmp(@PathVariable("id") Integer id,Model model){
//根据id查出来员工
Employee employeeByID = employeeDao.getEmployeeByID(id);
//将员工信息返回页面
model.addAttribute("emp",employeeByID);
//查出所有部门的信息,提供修改选择
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("departments",departments);
return "emp/update";
}
3、我们需要在这里将add页面复制一份,改为update页面;需要修改页面,将我们后台查询数据回显
<form th:action="@{/updateEmp}" method="post">
<input type="hidden" name="id" th:value="${emp.getId()}">
<div class="form-group">
<label>姓名</label>
<input th:value="${emp.getLastName()}" type="text" name="lastName" class="form-control" placeholder="好汤圆">
</div>
<div class="form-group">
<label>邮箱</label>
<input th:value="${emp.getEmail()}" type="email" name="email" class="form-control" placeholder="1416555145@qq.com">
</div>
<div class="form-group">
<label>性别</label><br>
<div class="form-check form-check-inline">
<input th:checked="${emp.getGender()==1}" class="form-check-input" type="radio" name="gender" value="1">
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input th:checked="${emp.getGender()==0}" class="form-check-input" type="radio" name="gender" value="0">
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>部门</label>
<select class="form-control" name="department.id">
<option th:selected="${department.getId()==emp.getDepartment().getId()}" th:each="department:${departments}" th:text="${department.getDepartmentName()}" th:value="${department.getId()}"></option>
</select>
</div>
<div class="form-group">
<label>出生日期</label>
<input th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd')}" type="text" name="birth" class="form-control" placeholder="2000-00-00">
</div>
<button type="submit" class="btn btn-primary">修改</button>
</form>
这时我们发现日期显示不完美,可以使用日期工具,进行日期的格式化
<input th:value="${#dates.format(emp.getBirth(),'yyyy-MM-dd')}" type="text" name="birth" class="form-control" placeholder="2000-00-00">
接下来我们继续完成数据修改问题
4、修改表单提交的地址
<form th:action="@{/updateEmp}" method="post">
5、编写对应的controller
@PostMapping("updateEmp")
public String updateEmp(Employee employee){
employeeDao.add(employee);
//回到员工列表页面
return "redirect:/emps";
}
6、为了让我们每次修改信息都是在原信息上修改而不是新增一条数据,我们需要在前端对id加一个隐藏域,提交id
<input type="hidden" name="id" th:value="${emp.getId()}">
修改功能实现!