您的位置:首页 > 编程语言 > Java开发

基于SpringMVC的Restful风格的增删改查--④更新员工信息

2015-08-18 16:39 513 查看
基本思想:点击某一个员工的更新链接,进入Spring的from表单,回显该员工数据 =》 submit后,交给handler做save处理 =》重定向至员工列表界面

注意的点:(1) 员工的lastName不可以被修改(需要使用modelattribute技术) (2) 需要将post请求转为PUT请求(需要借助HiddenHttpMethodFilter)

具体流程以及核心代码:

(1) 链接进入form:

<td><a  class="update" href="input/${emp.id}">Edit</a></td>


(2) form表单以及帮助回显的handler:

<body>
<form:form action="emp" method="post" modelAttribute="employee">
<c:if test="${ employee.id == null }">
lastName: <form:input path="lastName" /> <br>
</c:if>
<c:if test="${ employee.id != null }">
<form:hidden path="id"/>
<input type="hidden" name="_method" value="PUT">
</c:if>
email: <form:input path="email" /> <br>
<%
Map<Integer, String> genders = new HashMap<Integer, String>();
genders.put(1, "Femal");
genders.put(0, "Male");
request.setAttribute("genders", genders);
%>
gender: <form:radiobuttons path="gender" items="${genders}" /> <br>
department: <form:select path="department.id" itemLabel="departmentName"
items="${departments}" itemValue="id"> <br>
</form:select>
<input value="submit" type="submit">
</form:form>
</body>


@RequestMapping(value="input/{id}" ,method=RequestMethod.GET)
public String inputemp(@PathVariable(value="id") Integer id,Employ employee,Map<String,Object> map){
employee = employDao.getEmploy(id);
map.put("employee",employee );
map.put("departments", departmentDao.getAll());
return "input";
}


(3) 更新的handler(包括@modelAttribute)

@ModelAttribute
public void getemploy(@RequestParam(value="id",required=false) Integer id ,Map<String,Object> map ){
if(id != null){
map.put("employee", employDao.getEmploy(id));
}
System.out.println(employDao.getEmploy(id));
}

@RequestMapping(value="input/emp",method=RequestMethod.PUT)
public String putEmployee(@ModelAttribute(value="employee") Employ employee,Map<String,Object> map){
map.put("departments", departmentDao.getAll());
map.put("employee", employee);
employDao.save(employee);
return "redirect:/springmvc/testAllEmploy";
}


资料(SpringMVC注解@RequestParam全面解析):

http://825635381.iteye.com/blog/2196911
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring spring mvc