构建员工修改请求
com\springboot\controller\EmployeeController.java
/*调转到员工修改页 携带员工信息 restful风格*/
@GetMapping("/emp/{id}")
public String toUpdatePage(@PathVariable("id") Integer id,Model model){
//获取指定员工的信息
Employee employee = employeeDao.get(id);
model.addAttribute("emp",employee);
//获取所有的部门
Collection<Department> departments = departmentDao.getDepartments();
model.addAttribute("departments",departments);
return "add";
}
/*修改员工 restful风格*/
@PutMapping("/emp")
public String updateEmp(Employee emp){
employeeDao.save(emp);
//重定向到员工列表请求
return "redirect:/employee";
}
在list.html增加编辑员工按钮
resources\templates\list.html
<a class="btn btn-sm btn-primary" th:href="@{/emp/} + ${emp.id}">编辑</a>
构建修改页面
resources\templates\add.html(公用添加页,显示需要修改的信息以及定义put提交请求)
form表单:
<form th:action="@{/emp}" method="post">
<!--put请求:如果emp不等于空就走put请求-->
<input type="hidden" name="_method" value="put" th:if="${emp!=null}" />
<!--隐藏域:员工编号 用于修改用户信息-->
<input type="hidden" th:if="${emp != null}" name="id" th:value="${emp.getId()}">
<input type="hidden" name="id" />
<div class="form-group">
<label>姓名</label>
<input type="text" name="lastName" class="form-control" placeholder="zhangsan"
th:value="${emp != null}?${emp.getLastName()}"><!--如果emp不等于空 显示姓名-->
</div>
<div class="form-group">
<label>邮箱</label>
<input type="email" name="email" class="form-control" placeholder="[email protected]"
th:value="${emp != null}?${emp.getEmail()}"><!--如果emp不等于空 显示邮箱-->
</div>
<div class="form-group">
<label>性别</label><br/>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="1"
th:checked="${emp != null}?${emp.getGender()==1}"><!--如果emp不等于空 1=1为true 则选中-->
<label class="form-check-label">男</label>
</div>
<div class="form-check form-check-inline">
<input class="form-check-input" type="radio" name="gender" value="0"
th:checked="${emp != null}?${emp.getGender()==0}"><!--如果emp不等于空 0=0为true 则选中-->
<label class="form-check-label">女</label>
</div>
</div>
<div class="form-group">
<label>部门</label>
<select class="form-control" name="department.id">
<!--获取部门信息-->
<option th:each="dept:${departments}"
th:value="${dept.getId()}"
th:text="${dept.getDepartmentName()}"
th:selected="${emp != null}?${dept.getId() == emp.getDepartment().getId()}">
<!--如果emp不等于空 1=1为true 则选中-->
</option>
</select>
</div>
<div class="form-group">
<label>生日</label>
<input type="text" name="birth" class="form-control" placeholder="1986/02/22"
th:value="${emp != null}?${#dates.format(emp.getBirth(), 'yyyy-MM-dd HH:mm:ss')}">
<!--如果emp不等于空 显示生日-->
</div>
<button type="submit" class="btn btn-primary"
th:text="${emp != null}?'修改':'添加'">
<!--如果emp不等于空 则显示修改-->
</button>
</form>
测试访问:
修改:
列表显示: