1.在jsp页面写一个隐藏域<input type="updateFields" value="name,age,sex,address,phone"/>
隐藏域中的值是需要修改的属性值,分别用逗号隔开
<%@ page language="java" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>修改用户</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <form action="userAction.do" method="post"> <!-- 需要修改的属性值 --> <input type="hidden" value="name,age,sex,address,phone"> <input type="text" name="id" value="1"> <input type="text" name="name">
<input type="text" name="age"> <input type="text" name="sex"> <input type="text" name="address"> <input type="text" name="phone"> <input type="submit" value="提交"> </form> </body> </html>
public class User{
private String id;
private String name;
private String sex;
private String age;
private String address;
private String phone;
//get,set省略...
}
2. 然后在Action里面获取需要修改的属性:
String[] updateFields = request.getParameter("updateFields").split(",");
Hibernate从数据库中把User对象load上来User user = UserService.findUser(request.getParamater("id"));
使用BeanUtils工具类将这些需要修改的属性值注入user里面
然后updateUser对象
public class UserAction extends Action{
public ActionForward execute(ActionMapping mapping, SystemStyle systemStyle, HttpServletRequest request, HttpServletResponse response) {
String[] request.getParameter("updateFields").split(",");
User user = UserService.findUser(request.getParamater("id"));
Map<String String[]> m = request.getParamaterMap();
for(String field:updateFields){
BeanUtils.setProperty(user,field,m.get(field)[0]);
}
UserService.updateUser(user);
return mapping.findForward("userList");
}
}