MVC案例之修改代码实现
<%@page import="com.xs.mvc_crud.domain.Customer"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
Object message = request.getAttribute("message");
%>
<font color="red"><%=request.getAttribute("message") == null ? "" : request.getAttribute("message")%></font>
<%
String id = null;
String oldName = null;
String newName = null;
String newAddress = null;
String newPhone = null;
Customer customer = (Customer)request.getAttribute("customer");
if(customer != null){
id = customer.getId() + "";
oldName = customer.getName();
newName = customer.getName();
newAddress = customer.getAddress();
newPhone = customer.getPhone();
}else{
id = request.getParameter("id");
oldName = request.getParameter("oldName");
newName = request.getParameter("oldName");
newAddress = request.getParameter("newAddress");
newPhone = request.getParameter("newPhone");
}
%>
<form action="update.do" method="post">
<input name="id" type="hidden" value="<%=id%>" />
<input name="oldName" type="hidden" value="<%=oldName%>" />
<table border="1" cellpadding="10" cellspacing="0">
<tr>
<td>CustomerName</td>
<td><input name="newName" type="text"
value="<%=newName%>" /></td>
</tr>
<tr>
<td>Address</td>
<td><input name="newAddress" type="text"
value="<%=newAddress%>" /></td>
</tr>
<tr>
<td>Phone</td>
<td><input name="newPhone" type="text"
value="<%=newPhone%>" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Update" /></td>
</tr>
</table>
</form>
</body>
</html>
- 2.CustomerServlet中edit方法代码:
private void edit(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
String forwardPath = "/error.jsp";
String idStr = request.getParameter("id");
try {
Customer customer = customerDAO.get(Integer.parseInt(idStr));
if(customer != null){
forwardPath = "/updatecustomer.jsp";
request.setAttribute("customer", customer);
}
} catch (NumberFormatException e) {}
request.getRequestDispatcher(forwardPath).forward(request, response);
}
- 2.CustomerServlet中update方法代码:
private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
String oldName = request.getParameter("oldName");
String newName = request.getParameter("newName");
String newAddress = request.getParameter("newAddress");
String newPhone = request.getParameter("newPhone");
if (!oldName.equals(newName)) {
String nameStr = customerDAO.getCountWithName(newName).toString();
int count = Integer.parseInt(nameStr);
if (count > 0) {
request.setAttribute("message", "对不起,用户名" + newName + "已经被占用,请重新选择!");
request.getRequestDispatcher("/updatecustomer.jsp").forward(request, response);
return;
}
}
Customer customer = new Customer(newName, newAddress, newPhone);
customer.setId(Integer.parseInt(id));
customerDAO.update(customer);
response.sendRedirect("query.do");
}