SpringMVC框架
7.8 RESTRUL_CRUD_修改操作
7.8.1 根据id查询员工对象,表单回显
- 页面链接
<td><a href="empEdit/${emp.id }">Edit</a></td> |
- 控制器方法
//修改员工 - 表单回显 @RequestMapping(value="/empEdit/{id}",method=RequestMethod.GET) public String empEdit(@PathVariable("id") Integer id,Map<String,Object> map){ map.put("employee", employeeDao.get(id)); map.put("deptList",departmentDao.getDepartments()); return "edit"; } |
- 修改页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <!-- 1.为什么使用SpringMVC的form标签 ① 快速开发 ② 表单回显 2.可以通过modelAttribute指定绑定的模型属性, 若没有指定该属性,则默认从request域中查找command的表单的bean 如果该属性也不存在,那么,则会发生错误。 修改功能需要增加绝对路径,相对路径会报错,路径不对 --> <form:form action="${pageContext.request.contextPath }/empUpdate" method="POST" modelAttribute="employee"> <%-- LastName : <form:input path="lastName" /><br><br> --%> <form:hidden path="id"/> <input type="hidden" name="_method" value="PUT"> <%-- 这里不要使用form:hidden标签,否则会报错。 <form:hidden path="_method" value="PUT"/> Spring的隐含标签,没有value属性,同时,path指定的值,在模型对象中也没有这个属性(_method),所以回显时会报错。 org.springframework.beans.NotReadablePropertyException: Invalid property '_method' of bean class [com.atguigu.springmvc.crud.entities.Employee]: Bean property '_method' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? --%> Email : <form:input path="email" /><br><br> <% Map<String,String> map = new HashMap<String,String>(); map.put("1", "Male"); map.put("0","Female"); request.setAttribute("genders", map); %> Gender : <br><form:radiobuttons path="gender" items="${genders }" delimiter="<br>"/><br><br> DeptName : <form:select path="department.id" items="${deptList }" itemLabel="departmentName" itemValue="id"></form:select><br><br> <input type="submit" value="Submit"><br><br> </form:form> </body> </html> |
7.8.2 提交表单,修改数据
- 控制器方法
@RequestMapping(value="/empUpdate",method=RequestMethod.PUT) public String empUpdate(Employee employee){ employeeDao.save(employee); return "redirect:/empList"; } |