1,在注册页面通过AJAX验证用户注册ID是否已经存在
View Code
1 <script language="javascript">
2 var xmlHttp;
3 var flag2=false;
4 function creatXMLHttp()
5 {
6 if (window.XMLHttpRequset)
7 {
8 xmlHttp=new XMLHttpRequest();
9 }
10 else
11 {
12 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
13 }
14 }
15
16 function checkUserId(userid)
17 {
18 creatXMLHttp();
19 xmlHttp.open("POST","RegisterUserServlet?status=checkuserid&id="+userid);
20 xmlHttp.onreadystatechange=checkUserIdCallBack;
21 xmlHttp.send(null);
22 }
23
24 function checkUserIdCallBack()
25 {
26 if(xmlHttp.readyState==4&&xmlHttp.status==200)
27 {
28 var flag=xmlHttp.responseText;
29 if(flag=="true")
30 {
31 flag2=false;
32 document.getElementById("userid_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\"/>"+"<font color=\"red\">用户编号已经被注册!</font>"
33 }
34 else
35 {
36 flag2=true;
37 document.getElementById("userid_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\"/>"+"<font color=\"green\">恭喜,用户编号未被注册!</font>"
38 }
39 }
40 }
41 function checkRes()
42 {
43 return flag2;
44 }
45 function validateUserId(userid)
46 {
47 if(!/^\d{4}$/.test(userid))
48 {
49 document.getElementById("userid_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\"/>"+"<font color=\"red\">用户编号必须是四位数字!</font>"
50 return false;
51 }
52 else
53 {
54 checkUserId(userid);
55 return true;
56 }
57 }
58 function validateUsername(username)
59 {
60 if(username=="")
61 {
62 document.getElementById("username_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\"/>"+"<font color=\"red\">用户编号不能为空!</font>"
63 return false;
64 }
65 else
66 {
67 document.getElementById("username_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\"/>"+"<font color=\"green\">用户名输入正确!</font>"
68 return true;
69 }
70 }
71 function validatePassword(password)
72 {
73 if(password=="")
74 {
75 document.getElementById("password_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\"/>"+"<font color=\"red\">密码不能为空!</font>"
76 return false;
77 }
78 else
79 {
80 document.getElementById("password_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\"/>"+"<font color=\"green\">密码输入正确!</font>"
81 return true;
82 }
83 }
84 function validatePasswordAg(passwordag)
85 {
86 if(passwordag=="")
87 {
88 document.getElementById("passwordag_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\"/>"+"<font color=\"red\">输入密码不能为空!</font>"
89 return false;
90 }
91 else
92 {
93 if(document.getElementById("password").value!=passwordag)
94 {
95 document.getElementById("passwordag_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\"/>"+"<font color=\"red\">输入密码与上一次输入不一致!</font>"
96 return false;
97 }
98 else
99 {
100 document.getElementById("passwordag_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\"/>"+"<font color=\"green\">密码输入正确!</font>"
101 return true;
102 }
103 }
104 }
105 function validateAddress(address)
106 {
107 if(address=="")
108 {
109 document.getElementById("address_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\"/>"+"<font color=\"red\">联系地址不能为空!</font>"
110 return false;
111 }
112 else
113 {
114 document.getElementById("address_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\"/>"+"<font color=\"green\">联系地址输入正确!</font>"
115 return true;
116 }
117 }
118 function validateTelephone(telephone)
119 {
120 if(telephone=="")
121 {
122 document.getElementById("telephone_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\"/>"+"<font color=\"red\">联系方式不能为空!</font>"
123 return false;
124 }
125 else
126 {
127 document.getElementById("telephone_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\"/>"+"<font color=\"green\">联系方式输入正确!</font>"
128 return true;
129 }
130 }
131 function validateZipcode(zipcode)
132 {
133 if(zipcode=="")
134 {
135 document.getElementById("zipcode_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\"/>"+"<font color=\"red\">邮政编码不能为空!</font>"
136 return false;
137 }
138 else
139 {
140 if(!/^\d{6}$/.test(zipcode))
141 {
142 document.getElementById("zipcode_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\"/>"+"<font color=\"red\">邮政编码格式不正确!</font>"
143 return false;
144 }
145 else
146 {
147 document.getElementById("zipcode_pic").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\"/>"+"<font color=\"green\">邮政编码输入正确!</font>"
148 return true;
149 }
150 }
151 }
152 function validate(formValue)
153 {
154 return checkRes()&&validateUserId(formValue.id.value)&&
155 validateUsername(formValue.username.value)&&
156 validatePassword(formValue.password.value)&&
157 validatePasswordAg(formValue.passwordag.value)&&
158 validateAddress(formValue.address.value)&&
159 validateTelephone(formValue.telephone.value)&&
160 validateZipcode(formValue.zipcode.value);
161 }
162 </script>
RegisterUserServlet处理
View Code
1 package org.xiong.demo.servlet;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5
6 import javax.servlet.ServletException;
7 import javax.servlet.http.Cookie;
8 import javax.servlet.http.HttpServlet;
9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11
12 import org.xiong.demo.factory.DaoFactory;
13 import org.xiong.demo.util.MessageUtil;
14 import org.xiong.demo.vo.RegisterUser;
15
16 public class RegisterUserServlet extends HttpServlet
17 {
18
19 public void doGet(HttpServletRequest request, HttpServletResponse response)
20 throws ServletException, IOException
21 {
22 request.setCharacterEncoding("GBK");
23 String page = "error.jsp";
24 String status = request.getParameter("status");
25 if (!("".equals(status) || status == null))
26 {
27 if ("check".equals(status))
28 {
29 this.check(request, response);
30 }
31 if ("add".equals(status))
32 {
33 this.add(request, response);
34 }
35 if ("checkuserid".equals(status))
36 {
37 this.checkuserid(request, response);
38 }
39 }
40 else
41 {
42 request.getRequestDispatcher(page).forward(request, response);
43 }
44
45 }
46
47 public void doPost(HttpServletRequest request, HttpServletResponse response)
48 throws ServletException, IOException
49 {
50 this.doGet(request, response);
51 }
52
53 public void checkuserid(HttpServletRequest request,
54 HttpServletResponse response) throws ServletException, IOException
55 {
56 int id = 0;
57 try
58 {
59 id = Integer.parseInt(request.getParameter("id"));
60 }
61 catch (Exception ex)
62 {
63
64 }
65 try
66 {
67 PrintWriter out = response.getWriter();
68 RegisterUser user = DaoFactory.getUserDaoInstance().findById(id);
69 if (user == null)
70 {
71 response.setContentType("text/html;charset=GBK");
72 out.print("false");
73 out.close();
74 }
75 else
76 {
77 out.print("true");
78 out.close();
79 }
80 }
81 catch (Exception e)
82 {
83 e.printStackTrace();
84 }
85 }
86
87 public void add(HttpServletRequest request, HttpServletResponse response)
88 throws ServletException, IOException
89 {
90 String page = "error.jsp";
91 RegisterUser user = new RegisterUser();
92 int id = 0;
93 try
94 {
95 id = Integer.parseInt(request.getParameter("id"));
96 }
97 catch (Exception ex)
98 {
99
100 }
101 user.setId(id);
102 user.setUsername(request.getParameter("username"));
103 user.setPassword(request.getParameter("password"));
104 user.setAddress(request.getParameter("address"));
105 user.setTelephone(request.getParameter("telephone"));
106 user.setZipcode(request.getParameter("zipcode"));
107 user.setLastdate(new java.util.Date());
108 try
109 {
110 if (DaoFactory.getUserDaoInstance().doInsert(user))
111 {
112 request.setAttribute("msg",
113 MessageUtil.getMessage("register.add.true"));
114 request.setAttribute("flag", true);
115 page = "add_user_do.jsp";
116 }
117 else
118 {
119 request.setAttribute("msg",
120 MessageUtil.getMessage("register.add.fase"));
121 request.setAttribute("flag", false);
122 }
123
124 }
125 catch (Exception e)
126 {
127 e.printStackTrace();
128 }
129 request.getRequestDispatcher(page).forward(request, response);
130 }
131
132 public void check(HttpServletRequest request, HttpServletResponse response)
133 throws ServletException, IOException
134 {
135 String page = "error.jsp";
136 String rand = (String) request.getSession().getAttribute("rand");
137 String userName = request.getParameter("username");
138 String userPass = request.getParameter("password");
139 String code = request.getParameter("code");
140 boolean flag = false;
141 long cookieTime = 0;
142 try
143 {
144 cookieTime = Long.parseLong(request.getParameter("saveTime"));
145 }
146 catch (Exception ex)
147 {
148
149 }
150 if (("".equals(userName) || null == userName)
151 || ("".equals(userPass) || null == userPass))
152 {
153 request.setAttribute("errMsg",
154 MessageUtil.getMessage("check.input.null"));
155 }
156 else if ("".equals(code) || null == code)
157 {
158 request.setAttribute("errMsg",
159 MessageUtil.getMessage("code.input.null"));
160 }
161 else if (!code.equalsIgnoreCase(rand))
162 {
163 request.setAttribute("errMsg",
164 MessageUtil.getMessage("code.input.error"));
165 }
166 else
167 {
168 RegisterUser user = new RegisterUser();
169 user.setUsername(userName);
170 user.setPassword(userPass);
171 RegisterUser register = null;
172 try
173 {
174 register = DaoFactory.getUserDaoInstance().findLongin(user);
175 }
176 catch (Exception e)
177 {
178 e.printStackTrace();
179 }
180 if (register != null)
181 {
182 if (register.getId() > 0 && code.equalsIgnoreCase(rand))
183 {
184
185 request.getSession().setAttribute("username", userName);
186 request.getSession().setAttribute("userid",
187 register.getId());
188 request.getSession().setAttribute("user", register);
189 Cookie c1 = new Cookie("username", userName);
190 Cookie c2 = new Cookie("password", userPass);
191 c1.setMaxAge((int) cookieTime);
192 c2.setMaxAge((int) cookieTime);
193 response.addCookie(c1);
194 response.addCookie(c2);
195 flag = true;
196 }
197 else
198 {
199 request.setAttribute("errMsg",
200 MessageUtil.getMessage("check.input.error"));
201 }
202 }
203 }
204 if (flag)
205 {
206 page = "/register/welcome.jsp";
207 request.getRequestDispatcher(page).forward(request, response);
208 }
209 else
210 {
211 page = "login.jsp";
212 request.getRequestDispatcher(page).forward(request, response);
213 }
214 }
215
216 }
注册页面
View Code
1 <html>
2 <head>
3 <title>新用户注册页</title>
4 <body>
5 <center><h1>新用户注册</h1></center>
6 <form action="RegisterUserServlet" method="post" onsubmit="return validate(this.value)">
7 用 户 ID:<input type="text" name="id" onblur="validateUserId(this.value)"/><span id="userid_pic"><font color="red">*</font></span><br/>
8 用 户 名:<input type="text" name="username" onblur="validateUsername(this.value)"/><span id="username_pic"><font color="red">*</font></span><br/>
9 密 码:<input type="password" name="password" onblur="validatePassword(this.value)"/><span id="password_pic"><font color="red">*</font></span><br/>
10 重复输入:<input type="password" name="passowrdag" onblur="validatePasswordAg(this.value)"/><span id="passwordag_pic"><font color="red">*</font></span><br/>
11 详细地址:<input type="text" name="address" onblur="validateAddress(this.value)"/><span id="address_pic"><font color="red">*</font></span><br/>
12 联系方式:<input type="text" name="telephone" onblur="validateTelephone(this.value)"/><span id="telephone_pic"><font color="red">*</font></span><br/>
13 邮政编码:<input type="text" name="zipcode" onblur="validateZipcode(this.value)"/><span id="zipcode_pic"><font color="red">*</font></span><br/>
14 <input type="hidden" name="status" value="add"/>
15 <input type="submit" value="注册" /> <input type="reset" value="重置" />
16 </form>
17 </body>
18 </html>
2,通过AJAX生成option(生成部门列表和领导列表)
View Code
1 <script language="javascript">
2 var xmlHttp;
3 function createXMLHttp()
4 {
5 if(window.XMLHttpRequest)
6 {
7 xmlHttp=new XMLHttpRequest();
8 }
9 else
10 {
11 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
12 }
13 }
14 function findAllMgr()
15 {
16 createXMLHttp();
17 xmlHttp.open("POST", "EmpServlet?status=findallmgr");
18 xmlHttp.onreadystatechange=findAllMgrCallBack;
19 xmlHttp.send(null);
20 }
21 function findAllMgrCallBack()
22 {
23 if(xmlHttp.readystate==4&&xmlHttp.status==200)
24 {
25 var allMgr=xmlHttp.responseXML.getElementsByTagName("mgrs")[0].childNodes;
26 var select =document.getElementById("mgr");
27 select.length=1;
28 select.options[0].selected=true;
29 for(var i=0;i<allMgr.length;i++)
30 {
31 var emp=allMgr[i];
32 var option=document.createElement("option");
33 var empno=emp.getElementsByTagName("empno")[0].firstChild.nodeValue;
34 var ename=emp.getElementsByTagName("ename")[0].firstChild.nodeValue;
35 option.setAttribute("value",empno);
36 option.appendChild(document.createTextNode(ename));
37 select.appendChild(option);
38 }
39 }
40 }
41 function findAllDept()
42 {
43 createXMLHttp();
44 xmlHttp.open("POST", "EmpServlet?status=findalldept");
45 xmlHttp.onreadystatechange=findAllDeptCallBack;
46 xmlHttp.send(null);
47 }
48 function findAllDeptCallBack()
49 {
50 if(xmlHttp.readystate==4&&xmlHttp.status==200)
51 {
52 var allDept=xmlHttp.responseXML.getElementsByTagName("alldept")[0].childNodes;
53 var select =document.getElementById("deptno");
54 select.length=1;
55 select.options[0].selected=true;
56 for(var i=0;i<allDept.length;i++)
57 {
58 var dept=allDept[i];
59 var option=document.createElement("option");
60 var deptno=dept.getElementsByTagName("deptno")[0].firstChild.nodeValue;
61 var dname= dept.getElementsByTagName("dname")[0].firstChild.nodeValue;
62 option.setAttribute("value", deptno);
63 option.appendChild(document.createTextNode(dname));
64 select.appendChild(option)
65 }
66 }
67 }
68 </script>
EmpServlet处理
View Code
1 package org.xiong.demo.servlet;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.PrintWriter;
6 import java.text.SimpleDateFormat;
7 import java.util.Iterator;
8 import java.util.List;
9
10 import javax.servlet.ServletException;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14
15 import org.jdom.Document;
16 import org.jdom.Element;
17 import org.jdom.output.XMLOutputter;
18 import org.lxh.smart.SmartUpload;
19 import org.lxh.smart.SmartUploadException;
20 import org.xiong.demo.dao.IEmpDao;
21 import org.xiong.demo.factory.DaoFactory;
22 import org.xiong.demo.util.MessageUtil;
23 import org.xiong.demo.util.RandName;
24 import org.xiong.demo.vo.Dept;
25 import org.xiong.demo.vo.Emp;
26
27 public class EmpServlet extends HttpServlet
28 {
29 private SmartUpload smart;
30
31 public void doGet(HttpServletRequest request, HttpServletResponse response)
32 throws ServletException, IOException
33 {
34 this.doPost(request, response);
35 }
36
37 public void doPost(HttpServletRequest request, HttpServletResponse response)
38 throws ServletException, IOException
39 {
40 request.setCharacterEncoding("GBK");
41 String path = "error.jsp";
42 String status = request.getParameter("status");
43 if ("".equals(status) || null == status)
44 {
45 smart = new SmartUpload();
46 smart.initialize(super.getServletConfig(), request, response);
47 try
48 {
49 smart.upload();
50 status = smart.getRequest().getParameter("status");
51 }
52 catch (SmartUploadException e)
53 {
54 e.printStackTrace();
55 }
56
57 }
58 if (!("".equals(status) || null == status))
59 {
60 if ("list".equals(status))
61 {
62 this.list(request, response);
63 }
64 if ("add".equals(status))
65 {
66 this.add(request, response);
67 }
68 if ("update".equals(status))
69 {
70 this.update(request, response);
71 }
72 if ("delete".equals(status))
73 {
74 this.delete(request, response);
75 }
76 if ("deleteEmp".equals(status))
77 {
78 this.deleteEmp(request, response);
79 }
80 if ("deptinfo".equals(status))
81 {
82 this.deptinfo(request, response);
83 }
84 if ("empinfo".equals(status))
85 {
86 this.empinfo(request, response);
87 }
88 if ("findallmgr".equals(status))
89 {
90 this.findallmgr(request, response);
91 }
92 if ("findalldept".equals(status))
93 {
94 this.findalldept(request, response);
95 }
96
97 }
98 else
99 {
100 request.getRequestDispatcher(path).forward(request, response);
101 }
102 }
103
104 public void findalldept(HttpServletRequest request,
105 HttpServletResponse response) throws ServletException, IOException
106 {
107 response.setContentType("text/xml;charset=GBK");
108 PrintWriter out = response.getWriter();
109 ByteArrayOutputStream bos = new ByteArrayOutputStream();
110 try
111 {
112 List<Dept> allDept = DaoFactory.getDeptDaoInstance().findAll("");
113 Iterator<Dept> iterDept = allDept.iterator();
114 Element root = new Element("alldept");
115 Document doc = new Document(root);
116 while (iterDept.hasNext())
117 {
118 Dept d = iterDept.next();
119 Element dept = new Element("dept");
120 Element deptno = new Element("deptno");
121 Element dname = new Element("dname");
122 deptno.setText(d.getDeptno() + "");
123 dname.setText(d.getDname());
124 dept.addContent(deptno);
125 dept.addContent(dname);
126 root.addContent(dept);
127 }
128 XMLOutputter xmlout = new XMLOutputter();
129 xmlout.setFormat(xmlout.getFormat().setEncoding("GBK"));
130 xmlout.output(doc, bos);
131 out.print(bos);
132 }
133 catch (Exception e)
134 {
135 e.printStackTrace();
136 }
137 finally
138 {
139 bos.close();
140 out.close();
141 }
142
143 }
144
145 public void findallmgr(HttpServletRequest request,
146 HttpServletResponse response) throws ServletException, IOException
147 {
148 response.setContentType("text/xml;charset=GBK");
149 PrintWriter out = response.getWriter();
150 ByteArrayOutputStream bos = new ByteArrayOutputStream();
151 try
152 {
153 List<Emp> allEmp = DaoFactory.getEmpDaoInstance().findAll("");
154 Element root = new Element("mgrs");
155 Document doc = new Document(root);
156 Iterator<Emp> iter = allEmp.iterator();
157 while (iter.hasNext())
158 {
159 Emp e = iter.next();
160 Element emp = new Element("emp");
161 Element empno = new Element("empno");
162 Element ename = new Element("ename");
163 empno.setText(e.getEmpno() + "");
164 ename.setText(e.getEname());
165 emp.addContent(empno);
166 emp.addContent(ename);
167 root.addContent(emp);
168 }
169 XMLOutputter xmlout = new XMLOutputter();
170 xmlout.setFormat(xmlout.getFormat().setEncoding("GBK"));
171 xmlout.output(doc, bos);
172 out.print(bos);
173 }
174 catch (Exception e)
175 {
176 e.printStackTrace();
177 }
178 finally
179 {
180 bos.close();
181 out.close();
182 }
183
184 }
185
186 public void list(HttpServletRequest request, HttpServletResponse response)
187 throws ServletException, IOException
188 {
189 String path = "error.jsp";
190 int currentPage = 1;
191 int lineSize = 3;
192 long allRecorders = 0;
193 String keyword = null;
194 int count = 0;
195 try
196 {
197 currentPage = Integer.parseInt(request.getParameter("cp"));
198 lineSize = Integer.parseInt(request.getParameter("ls"));
199 keyword = request.getParameter("kw");
200 }
201 catch (Exception ex)
202 {
203 }
204 if (keyword == null)
205 {
206 keyword = "";
207 }
208 IEmpDao dao = DaoFactory.getEmpDaoInstance();
209 try
210 {
211 java.util.List<Emp> allList = dao.findAll(keyword, currentPage,
212 lineSize);
213 allRecorders = dao.getAllCount(keyword);
214 request.setAttribute("allList", allList);
215 request.setAttribute("allRecorders", allRecorders);
216 request.setAttribute("currentPage", currentPage);
217 request.setAttribute("lineSize", lineSize);
218 path = "fuck_page_source.jsp";
219 }
220 catch (Exception e)
221 {
222 e.printStackTrace();
223 }
224 request.getRequestDispatcher(path).forward(request, response);
225 }
226
227 public void add(HttpServletRequest request, HttpServletResponse response)
228 throws ServletException, IOException
229 {
230 String path = "error.jsp";
231 int cp = Integer.parseInt(smart.getRequest().getParameter("cp"));
232 int ls = Integer.parseInt(smart.getRequest().getParameter("ls"));
233 int empno = Integer.parseInt(smart.getRequest().getParameter("empno"));
234 String ename = smart.getRequest().getParameter("ename");
235 String job = smart.getRequest().getParameter("job");
236 int mgr = Integer.parseInt(smart.getRequest().getParameter("mgr"));
237 java.sql.Date hiredate = null;
238 try
239 {
240 hiredate = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd")
241 .parse(smart.getRequest().getParameter("hiredate"))
242 .getTime());
243 }
244 catch (Exception ex)
245 {
246
247 }
248 float sal = Float.parseFloat(smart.getRequest().getParameter("sal"));
249 float comm = Float.parseFloat(smart.getRequest().getParameter("comm"));
250 int deptno = Integer
251 .parseInt(smart.getRequest().getParameter("deptno"));
252 String note = smart.getRequest().getParameter("note");
253
254 Emp emp = new Emp();
255 emp.setEmpno(empno);
256 emp.setEname(ename);
257 emp.setJob(job);
258
259 Emp empmgr = new Emp();
260 empmgr.setEmpno(mgr);
261 emp.setEmpmgr(empmgr);
262
263 emp.setHiredate(hiredate);
264 emp.setSal(sal);
265 emp.setComm(comm);
266
267 Dept dept = new Dept();
268 dept.setDeptno(deptno);
269 emp.setDept(dept);
270 emp.setNote(note);
271
272 String extName = null;
273 String fileName = null;
274 String pathName = null;
275 if (smart.getFiles().getSize() > 0)
276 {
277 RandName rn = new RandName(request.getRemoteAddr());
278 extName = "." + smart.getFiles().getFile(0).getFileExt();// 得到上传文件的扩展名
279 fileName = rn.getRandName();// 生成文件名
280 fileName += extName;
281 pathName = this.getServletContext().getRealPath("/") + "product"
282 + java.io.File.separator + "upload"
283 + java.io.File.separator + fileName;
284 emp.setPhoto(fileName);
285 }
286 else
287 {
288 emp.setPhoto("nophoto.jpg");
289 }
290
291 try
292 {
293 if (DaoFactory.getEmpDaoInstance().doInsert(emp))
294 {
295
296 if (smart.getFiles().getSize() > 0)
297 {
298 smart.getFiles().getFile(0).saveAs(pathName);
299 }
300 request.setAttribute("cp", cp);
301 request.setAttribute("ls", ls);
302 request.setAttribute("msg",
303 MessageUtil.getMessage("emp.add.true"));
304 path = "Emp_operation_do.jsp";
305 }
306 else
307 {
308 request.setAttribute("msg",
309 MessageUtil.getMessage("emp.add.false"));
310 }
311 }
312 catch (Exception e)
313 {
314 e.printStackTrace();
315 }
316
317 request.getRequestDispatcher(path).forward(request, response);
318 }
319
320 public void update(HttpServletRequest request, HttpServletResponse response)
321 throws ServletException, IOException
322 {
323 String path = "error.jsp";
324 int cp = Integer.parseInt(smart.getRequest().getParameter("cp"));
325 int ls = Integer.parseInt(smart.getRequest().getParameter("ls"));
326 int empno = 0;
327 try
328 {
329 empno = Integer.parseInt(smart.getRequest().getParameter("empno"));
330 }
331 catch (Exception ex)
332 {
333
334 }
335 String ename = smart.getRequest().getParameter("ename");
336 String job = smart.getRequest().getParameter("job");
337 int mgr = Integer.parseInt(smart.getRequest().getParameter("mgr"));
338 java.util.Date hiredate = null;
339 try
340 {
341 hiredate = new SimpleDateFormat("yyyy-MM-dd").parse(smart
342 .getRequest().getParameter("hiredate"));
343 }
344 catch (Exception ex)
345 {
346
347 }
348 float sal = Float.parseFloat(smart.getRequest().getParameter("sal"));
349 float comm = Float.parseFloat(smart.getRequest().getParameter("comm"));
350 int deptno = Integer
351 .parseInt(smart.getRequest().getParameter("deptno"));
352 String note = smart.getRequest().getParameter("note");
353 Emp emp = new Emp();
354 emp.setEmpno(empno);
355 emp.setEname(ename);
356 emp.setJob(job);
357 Emp e = new Emp();
358 e.setEmpno(mgr);
359 emp.setEmpmgr(e);
360 emp.setHiredate(hiredate);
361 emp.setSal(sal);
362 emp.setComm(comm);
363 Dept dept = new Dept();
364 dept.setDeptno(deptno);
365 emp.setDept(dept);
366 emp.setNote(note);
367 String extName = null;
368 String fileName = null;
369 String pathName = null;
370 String oldPhoto = smart.getRequest().getParameter("oldPhoto");
371 if (smart.getFiles().getSize() > 0)
372 {
373 if ("nophoto.jpg".equals(oldPhoto))
374 {
375 RandName rn = new RandName(request.getRemoteAddr());
376 extName = "." + smart.getFiles().getFile(0).getFileExt();// 得到上传文件的扩展名
377 fileName = rn.getRandName();// 生成文件名
378 fileName += extName;
379 pathName = this.getServletContext().getRealPath("/")
380 + "emp_operation" + java.io.File.separator + "upload"
381 + java.io.File.separator + fileName;
382 emp.setPhoto(fileName);
383 }
384 else
385 {
386 pathName = this.getServletContext().getRealPath("/")
387 + "emp_operation" + java.io.File.separator + "upload"
388 + java.io.File.separator + oldPhoto;
389 emp.setPhoto(oldPhoto);
390 }
391
392 }
393 else
394 {
395 emp.setPhoto(oldPhoto);
396 }
397 try
398 {
399 if (DaoFactory.getEmpDaoInstance().doUpdate(emp))
400 {
401 if (smart.getFiles().getSize() > 0)
402 {
403 smart.getFiles().getFile(0).saveAs(pathName);
404 }
405 path = "Emp_operation_do.jsp";
406 request.setAttribute("msg",
407 MessageUtil.getMessage("emp.update.true"));
408 request.setAttribute("cp", cp);
409 request.setAttribute("ls", ls);
410 }
411 else
412 {
413 request.setAttribute("msg",
414 MessageUtil.getMessage("emp.update.false"));
415 }
416 }
417 catch (Exception e1)
418 {
419 e1.printStackTrace();
420 }
421 request.getRequestDispatcher(path).forward(request, response);
422 }
423
424 public void deleteEmp(HttpServletRequest request,
425 HttpServletResponse response) throws ServletException, IOException
426 {
427 response.setContentType("text/html;charset=GBK");
428 PrintWriter out = response.getWriter();
429 int empno = 0;
430 String pic = request.getParameter("photo");
431 try
432 {
433 empno = Integer.parseInt(request.getParameter("empno"));
434 }
435 catch (Exception ex)
436 {
437
438 }
439 try
440 {
441 boolean flag = DaoFactory.getEmpDaoInstance().doDelete(empno);
442 if (flag)
443 {
444 if (!"nophoto.jpg".equals(pic))
445 {
446 String pahtName = this.getServletContext().getRealPath("/")
447 + "emp_operation" + java.io.File.separator
448 + "upload" + java.io.File.separator + pic;
449 java.io.File file = new java.io.File(pahtName);
450 if (file.exists())
451 {
452 file.delete();
453 }
454 }
455 }
456 out.print(flag);
457 }
458 catch (Exception e)
459 {
460
461 e.printStackTrace();
462 }
463 finally
464 {
465 out.close();
466 }
467
468 }
469
470 public void delete(HttpServletRequest request, HttpServletResponse response)
471 throws ServletException, IOException
472 {
473 String path = "error.jsp";
474 int empno = 0;
475 int cp = Integer.parseInt(request.getParameter("cp"));
476 int ls = Integer.parseInt(request.getParameter("ls"));
477 try
478 {
479 empno = Integer.parseInt(request.getParameter("empno"));
480 }
481 catch (Exception ex)
482 {
483
484 }
485 String pic = request.getParameter("photo");
486 try
487 {
488 if (DaoFactory.getEmpDaoInstance().doDelete(empno))
489 {
490 if (!"nophoto.jpg".equals(pic))
491 {
492 String pahtName = this.getServletContext().getRealPath("/")
493 + "emp_operation" + java.io.File.separator
494 + "upload" + java.io.File.separator + pic;
495 java.io.File file = new java.io.File(pahtName);
496 if (file.exists())
497 {
498 file.delete();
499 }
500 }
501 request.setAttribute("msg",
502 MessageUtil.getMessage("emp.delete.true"));
503 request.setAttribute("cp", cp);
504 request.setAttribute("ls", ls);
505 path = "Emp_operation_do.jsp";
506
507 }
508 else
509 {
510 request.setAttribute("msg",
511 MessageUtil.getMessage("emp.delete.false"));
512 }
513 }
514 catch (Exception e)
515 {
516 e.printStackTrace();
517 }
518
519 request.getRequestDispatcher(path).forward(request, response);
520 }
521
522 public void deptinfo(HttpServletRequest request,
523 HttpServletResponse response) throws ServletException, IOException
524 {
525 String path = "error.jsp";
526 int currentPage = 1;
527 int lineSize = 3;
528 String keyword = null;
529 long allRecorders = 0;
530
531 int deptno = 0;
532 try
533 {
534 deptno = Integer.parseInt(request.getParameter("deptno"));
535 currentPage = Integer.parseInt(request.getParameter("cp"));
536 lineSize = Integer.parseInt(request.getParameter("ls"));
537 keyword = request.getParameter("kw");
538 }
539 catch (Exception ex)
540 {
541
542 }
543 if (keyword == null)
544 {
545 keyword = "";
546 }
547 try
548 {
549 Dept dept = DaoFactory.getDeptDaoInstance().findById(deptno,
550 keyword, currentPage, lineSize);
551 List<Emp> allEmp = dept.getAllEmp();
552 if (null != dept)
553 {
554
555 request.setAttribute("dept", dept);
556 request.setAttribute("emp", allEmp);
557 allRecorders = (Long) dept.getStats().get("allcount");
558 request.setAttribute("allRecorders", allRecorders);
559 request.setAttribute("currentPage", currentPage);
560 request.setAttribute("lineSize", lineSize);
561 request.setAttribute("allRecorders", allRecorders);
562
563 path = "emp_dept_info.jsp";
564 }
565 }
566 catch (Exception e)
567 {
568 e.printStackTrace();
569 }
570 request.getRequestDispatcher(path).forward(request, response);
571 }
572
573 public void empinfo(HttpServletRequest request, HttpServletResponse response)
574 throws ServletException, IOException
575 {
576 String path = "error.jsp";
577 int empno = Integer.parseInt(request.getParameter("empno"));
578 try
579 {
580 Emp mgEmp = DaoFactory.getEmpDaoInstance().findById(empno);
581 if (mgEmp != null)
582 {
583 request.setAttribute("emp", mgEmp);
584 path = "mgr_info.jsp";
585 }
586
587 }
588 catch (Exception e)
589 {
590 e.printStackTrace();
591 }
592
593 request.getRequestDispatcher(path).forward(request, response);
594 }
595
596 }
雇员增加表单
View Code
1 <h1>添加雇员信息</h1>
2 <form action="EmpServlet" method="post" onSubmit="return validate(this.value)" enctype="multipart/form-data">
3 <table border="1" ,width="100%">
4 <tr>
5 <td>雇员编号:</td>
6 <td><input type="text" name="empno" onBlur="validateEmpno(this.value)" /></td>
7 <td><span id="empno_picMsg"><font color="red">*</font></span></td>
8 <td rowspan="9">
9 <div id="imgPreview" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);280px;height:200px;"></div>
10 </td>
11 </tr>
12 <tr>
13 <td>雇员姓名:</td>
14 <td><input type="text" name="ename" onBlur="validateEname(this.value)"/></td>
15 <td><span id="ename_picMsg"><font color="red">*</font></span></td>
16 </tr>
17 <tr>
18 <td>雇员岗位:</td>
19 <td><input type="text" name="job" onBlur="validateJob(this.value)"/></td>
20 <td><span id="job_picMsg"><font color="red">*</font></span></td>
21 </tr>
22 <tr>
23 <td>部门领导:</td>
24 <td>
25 <select name="mgr" onclick="findAllMgr()">
26 <option value="0">没有领导</option>
27 </select>
28 </td>
29 </tr>
30 <tr>
31 <td>雇佣日期:</td>
32 <td><input type="text" name="hiredate" onBlur="validateHiredate(this.value)"/></td>
33 <td><span id="hiredate_picMsg"><font color="red">*</font></span></td>
34 </tr>
35 <tr>
36 <td>雇员工资:</td>
37 <td><input type="text" name="sal" onBlur="validateSal(this.value)"/></td>
38 <td><span id="sal_picMsg"><font color="red">*</font></span></td>
39 </tr>
40 <tr>
41 <td>雇员奖金:</td>
42 <td><input type="text" name="comm" onBlur="validateComm(this.value)"/></td>
43 <td><span id="comm_picMsg"><font color="red">*</font></span></td>
44 </tr>
45 <tr>
46 <td>部门:</td>
47 <td>
48 <select name="deptno" onclick="findAllDept()">
49 <option value="0">没有部门</option>
50 </select>
51 </td>
52 </tr>
53 <tr>
54 <td>雇员照片:</td>
55 <td><input type="file" name="photo" onChange="Preview(this)"/></td>
56 </tr>
57 <tr>
58 <td>雇员简介:</td>
59 <td colspan="3">
60 <div class="editor">
61 <textarea id="note" name="note" style="650px;height:200px;visibility:hidden;">
62 雇员简介
63 </textarea>
64 </div>
65 </td>
66 </tr>
67 <tr>
68 <input type="hidden" name="cp" value="<%=request.getParameter("cp")%>"/>
69 <input type="hidden" name="ls" value="<%=request.getParameter("ls")%>"/>
70 <input type="hidden" name="status" value="add"/>
71 <td> <input type="submit" value="添加"/> <input type="reset" value="重置"/></td>
72 </tr>
73 </table>
74 </form>
3,通过AJAX生成级联菜单
View Code
1 <script language="javascript">
2 var xmlHttp;
3 function createXMLHttp()
4 {
5 if(window.XMLHttpRequest)
6 {
7 xmlHttp=new XMLHttpRequest();
8 }
9 else
10 {
11 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
12 }
13 }
14 function findSubTypes(tid)
15 {
16 createXMLHttp();
17 xmlHttp.open("POST","ProductServlet?status=findbytypes&tid="+tid);
18 xmlHttp.onreadystatechange=findSubTypesCallBack;
19 xmlHttp.send(null);
20
21 }
22 function findSubTypesCallBack()
23 {
24 if(xmlHttp.readyState==4&&xmlHttp.status==200)
25 {
26 var allSubTypes=xmlHttp.responseXML.getElementsByTagName("subtypes")[0].childNodes;
27 var select=document.getElementById("subtypes");
28 select.length=1;
29 select.options[0].selected=true;
30 for(var i=0;i<allSubTypes.length;i++)
31 {
32 var subtype=allSubTypes[i];
33 var option=document.createElement("option");
34 var stid=subtype.getElementsByTagName("stid")[0].firstChild.nodeValue;
35 var title=subtype.getElementsByTagName("title")[0].firstChild.nodeValue;
36 option.setAttribute("value",stid);
37 option.appendChild(document.createTextNode(title));
38 select.appendChild(option);
39 }
40 }
41 }
42 function Preview(imgFile)
43 {
44 document.getElementById("imgPreview").filters. item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgFile.value;
45 }
46 function validatePid(pid)
47 {
48 if(!(/^\d{1,5}$/.test(pid)))
49 {
50 document.getElementById("pid_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\">"+"<font color=\"red\">商品编号至少是一位数字!</font>"
51 return false;
52 }
53 else
54 {
55 document.getElementById("pid_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\">"+"<font color=\"green\">商品编号输入正确!</font>"
56 return true;
57 }
58 }
59 function validateName(name)
60 {
61 if(name=="")
62 {
63 document.getElementById("name_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\">"+"<font color=\"red\">商品名称不能为空!</font>"
64 return false;
65 }
66 else
67 {
68 document.getElementById("name_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\">"+"<font color=\"green\">商品名称输入正确!</font>"
69 return true;
70 }
71 }
72 function validatePrice(price)
73 {
74 if(!(/^\d+.\d*$/.test(price)))
75 {
76 document.getElementById("price_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\">"+"<font color=\"red\">商品价格必须是数字,可以包含小数!</font>"
77 return false;
78 }
79 else
80 {
81 document.getElementById("price_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\">"+"<font color=\"green\">商品价格输入正确!</font>"
82 return true;
83 }
84 }
85 function validateAmount(amount)
86 {
87 if(!(/^\d{1,}$/.test(amount)))
88 {
89 document.getElementById("amount_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\">"+"<font color=\"red\">库存数量必须是一位或多位整数!</font>"
90 return false;
91 }
92 else
93 {
94 document.getElementById("amount_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\">"+"<font color=\"green\">库存数量输入正确!</font>"
95 return true;
96 }
97 }
98 function validateTypes(types)
99 {
100 if(types=="0")
101 {
102 document.getElementById("types_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\">"+"<font color=\"red\">请选择商品类别!</font>"
103 return false;
104 }
105 else
106 {
107 document.getElementById("types_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\">"+"<font color=\"green\">商品类别输入正确!</font>"
108 return true;
109 }
110 }
111 function validateSubTypes(subtypes)
112 {
113 if(subtypes=="0")
114 {
115 document.getElementById("subtypes_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/wrong.gif\">"+"<font color=\"red\">请选择商品子类别!</font>"
116 return false;
117 }
118 else
119 {
120 document.getElementById("subtypes_picMsg").innerHTML="<img src=\"<%=request.getContextPath()%>/images/right.gif\">"+"<font color=\"green\">商品子类别输入正确!</font>"
121 return true;
122 }
123 }
124 function validate(numValue)
125 {
126 return validatePid(numValue.pid.value)&&
127 validateName(numValue.name.value)&&
128 validatePrice(numValue.price.value)&&
129 validateAmount(numValue.amount.value)&&
130 validateTypes(numValue.types.value)&&
131 validateSubTypes(numValue.subtypes.value);
132 }
133 </script>
ProductServlet处理请求
View Code
1 package org.xiong.demo.servlet;
2
3 import java.io.ByteArrayOutputStream;
4 import java.io.IOException;
5 import java.io.PrintWriter;
6 import java.util.Iterator;
7 import java.util.List;
8 import java.util.Map;
9
10 import javax.servlet.ServletException;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14
15 import org.jdom.Document;
16 import org.jdom.Element;
17 import org.jdom.output.XMLOutputter;
18 import org.lxh.smart.SmartUpload;
19 import org.lxh.smart.SmartUploadException;
20 import org.xiong.demo.dao.IProductDao;
21 import org.xiong.demo.factory.DaoFactory;
22 import org.xiong.demo.util.MessageUtil;
23 import org.xiong.demo.util.RandName;
24 import org.xiong.demo.vo.Product;
25 import org.xiong.demo.vo.SubTypes;
26 import org.xiong.demo.vo.Types;
27
28 public class ProductServlet extends HttpServlet
29 {
30
31 private SmartUpload smart;
32
33 public void doGet(HttpServletRequest request, HttpServletResponse response)
34 throws ServletException, IOException
35 {
36
37 this.doPost(request, response);
38 }
39
40 public void doPost(HttpServletRequest request, HttpServletResponse response)
41 throws ServletException, IOException
42 {
43 String path = "error.jsp";
44 String status = request.getParameter("status");
45 if ("".equals(status) || null == status)
46 {
47 this.smart = new SmartUpload();
48 this.smart.initialize(super.getServletConfig(), request, response);
49 try
50 {
51 this.smart.upload();
52 status = this.smart.getRequest().getParameter("status");
53 }
54 catch (SmartUploadException e)
55 {
56 e.printStackTrace();
57 }
58
59 }
60 if (!("".equals(status) || null == status))
61 {
62 if ("list".equals(status))
63 {
64 this.list(request, response);
65 }
66 if ("add".equals(status))
67 {
68 this.add(request, response);
69 }
70 if ("addpre".equals(status))
71 {
72 this.addpre(request, response);
73 }
74 if ("updatepre".equals(status))
75 {
76 this.updatepre(request, response);
77 }
78 if ("update".equals(status))
79 {
80 this.update(request, response);
81 }
82 if ("delete".equals(status))
83 {
84 this.delete(request, response);
85 }
86 if ("deleteProduct".equals(status))
87 {
88 this.deleteProduct(request, response);
89 }
90 if ("productinfo".equals(status))
91 {
92 this.productinfo(request, response);
93 }
94 if ("findbytypes".equals(status))
95 {
96 this.findbytypes(request, response);
97 }
98
99 }
100 else
101 {
102 request.getRequestDispatcher(path).forward(request, response);
103 }
104 }
105
106 public void findbytypes(HttpServletRequest request,
107 HttpServletResponse response) throws ServletException, IOException
108 {
109 response.setContentType("text/xml;charset=GBK");
110 PrintWriter out = response.getWriter();
111 ByteArrayOutputStream bos = new ByteArrayOutputStream();
112 int tid = Integer.parseInt(request.getParameter("tid"));
113 try
114 {
115 List<SubTypes> all = DaoFactory.getSubTypesDaoInstance()
116 .findBySubTypes(tid);
117 Iterator<SubTypes> iter = all.iterator();
118 Element root = new Element("subtypes");
119 Document doc = new Document(root);
120 while (iter.hasNext())
121 {
122 SubTypes sub = iter.next();
123 Element subtype = new Element("subtype");
124 Element stid = new Element("stid");
125 Element id = new Element("id");
126 Element title = new Element("title");
127 Element note = new Element("note");
128 stid.setText(sub.getStid() + "");
129 id.setText(sub.getTid() + "");
130 title.setText(sub.getTitle());
131 note.setText(sub.getNote());
132 subtype.addContent(stid);
133 subtype.addContent(id);
134 subtype.addContent(title);
135 subtype.addContent(note);
136 root.addContent(subtype);
137 }
138 XMLOutputter xmlout = new XMLOutputter();
139 xmlout.setFormat(xmlout.getFormat().setEncoding("GBK"));
140 xmlout.output(doc, bos);
141 out.print(bos);
142 }
143 catch (Exception ex)
144 {
145 ex.printStackTrace();
146 }
147 finally
148 {
149 bos.close();
150 out.close();
151 }
152 }
153
154 public void list(HttpServletRequest request, HttpServletResponse response)
155 throws ServletException, IOException
156 {
157 String path = "error.jsp";
158 int currentPage = 1;
159 int lineSize = 12;
160 long allRecorders = 0;
161 String keyword = null;
162 try
163 {
164 currentPage = Integer.parseInt(request.getParameter("cp"));
165 lineSize = Integer.parseInt(request.getParameter("ls"));
166 keyword = request.getParameter("kw");
167 }
168 catch (Exception ex)
169 {
170 }
171 if (keyword == null)
172 {
173 keyword = "";
174 }
175 IProductDao dao = DaoFactory.getProductDaoInstance();
176 try
177 {
178 java.util.List<Product> allList = dao.findAll(keyword, currentPage,
179 lineSize);
180 allRecorders = dao.getAllCount(keyword);
181 request.setAttribute("allList", allList);
182 request.setAttribute("allRecorders", allRecorders);
183 request.setAttribute("currentPage", currentPage);
184 request.setAttribute("lineSize", lineSize);
185 path = "product_page_source_back.jsp";
186 }
187 catch (Exception e)
188 {
189 e.printStackTrace();
190 }
191 request.getRequestDispatcher(path).forward(request, response);
192 }
193
194 public void addpre(HttpServletRequest request, HttpServletResponse response)
195 throws ServletException, IOException
196 {
197 String page = "error.jsp";
198 int cp = Integer.parseInt(request.getParameter("cp"));
199 int ls = Integer.parseInt(request.getParameter("ls"));
200 try
201 {
202 request.setAttribute("allTypes", DaoFactory.getTypesDaoInstance()
203 .findAll(""));
204 request.setAttribute("cp", cp);
205 request.setAttribute("ls", ls);
206 page = "product_add.jsp";
207 }
208 catch (Exception ex)
209 {
210 ex.printStackTrace();
211 }
212 request.getRequestDispatcher(page).forward(request, response);
213 }
214
215 public void add(HttpServletRequest request, HttpServletResponse response)
216 throws ServletException, IOException
217 {
218 String page = "error.jsp";
219 int cp = Integer.parseInt(smart.getRequest().getParameter("cp"));
220 int ls = Integer.parseInt(smart.getRequest().getParameter("ls"));
221 int pid = Integer.parseInt(smart.getRequest().getParameter("pid"));
222 String name = smart.getRequest().getParameter("name");
223 float price = Float
224 .parseFloat(smart.getRequest().getParameter("price"));
225 int amount = Integer
226 .parseInt(smart.getRequest().getParameter("amount"));
227 String photo = smart.getRequest().getParameter("photo");
228 String note = smart.getRequest().getParameter("note");
229 int tid = Integer.parseInt(smart.getRequest().getParameter("types"));
230 int stid = Integer
231 .parseInt(smart.getRequest().getParameter("subtypes"));
232
233 Product pr = new Product();
234 pr.setPid(pid);
235 pr.setName(name);
236 pr.setAmount(amount);
237 pr.setPrice(price);
238 pr.setPhoto(photo);
239 pr.setNote(note);
240 Types types = new Types();
241 types.setTid(tid);
242 pr.setTypes(types);
243 SubTypes subtypes = new SubTypes();
244 subtypes.setStid(stid);
245 pr.setSubtypes(subtypes);
246 System.out.println(pr.getTypes());
247 System.out.println(pr.getSubtypes());
248 String extName = null;
249 String fileName = null;
250 String pathName = null;
251 if (smart.getFiles().getSize() > 0)
252 {
253 RandName rn = new RandName(request.getRemoteAddr());
254 extName = "." + smart.getFiles().getFile(0).getFileExt();// 得到上传文件的扩展名
255 fileName = rn.getRandName();// 生成文件名
256 fileName += extName;
257 pathName = this.getServletContext().getRealPath("/") + "product"
258 + java.io.File.separator + "upload"
259 + java.io.File.separator + fileName;
260 pr.setPhoto(fileName);
261 }
262 else
263 {
264 pr.setPhoto("nophoto.jpg");
265 }
266 try
267 {
268
269 if (DaoFactory.getProductDaoInstance().doInsert(pr))
270 {
271 if (smart.getFiles().getSize() > 0)
272 {
273 smart.getFiles().getFile(0).saveAs(pathName);
274 }
275 request.setAttribute("msg",
276 MessageUtil.getMessage("product.add.true"));
277 request.setAttribute("cp", cp);
278 request.setAttribute("ls", ls);
279 page = "product_operation.jsp";
280 }
281 else
282 {
283 request.setAttribute("msg",
284 MessageUtil.getMessage("product.add.true"));
285 }
286 }
287 catch (Exception e)
288 {
289 e.printStackTrace();
290 }
291 request.getRequestDispatcher(page).forward(request, response);
292 }
293
294 public void updatepre(HttpServletRequest request,
295 HttpServletResponse response) throws ServletException, IOException
296 {
297 String path = "error.jsp";
298 int pid = Integer.parseInt(request.getParameter("pid"));
299 int cp = Integer.parseInt(request.getParameter("cp"));
300 int ls = Integer.parseInt(request.getParameter("ls"));
301 try
302 {
303 Map<String, Object> mp = DaoFactory.getDaoServiceInstance()
304 .findProductAllTypes(pid);
305 if (mp != null)
306 {
307 request.setAttribute("pro", mp.get("pro"));
308 request.setAttribute("alltypes", mp.get("alltypes"));
309 request.setAttribute("subtypes", mp.get("subtypes"));
310 path = "product_update.jsp";
311 }
312 }
313 catch (Exception e)
314 {
315
316 e.printStackTrace();
317 }
318 request.getRequestDispatcher(path).forward(request, response);
319 }
320
321 public void update(HttpServletRequest request, HttpServletResponse response)
322 throws ServletException, IOException
323 {
324 String page = "error.jsp";
325 int cp = Integer.parseInt(smart.getRequest().getParameter("cp"));
326 int ls = Integer.parseInt(smart.getRequest().getParameter("ls"));
327 int pid = Integer.parseInt(smart.getRequest().getParameter("pid"));
328 String name = smart.getRequest().getParameter("name");
329 float price = Float
330 .parseFloat(smart.getRequest().getParameter("price"));
331 int amount = Integer
332 .parseInt(smart.getRequest().getParameter("amount"));
333 String photo = smart.getRequest().getParameter("photo");
334 String note = smart.getRequest().getParameter("note");
335 int tid = Integer.parseInt(smart.getRequest().getParameter("types"));
336 int stid = Integer
337 .parseInt(smart.getRequest().getParameter("subtypes"));
338
339 Product pr = new Product();
340 pr.setPid(pid);
341 pr.setName(name);
342 pr.setAmount(amount);
343 pr.setPrice(price);
344 pr.setPhoto(photo);
345 pr.setNote(note);
346 Types types = new Types();
347 types.setTid(tid);
348 pr.setTypes(types);
349 SubTypes subtypes = new SubTypes();
350 subtypes.setStid(stid);
351 pr.setSubtypes(subtypes);
352
353 String extName = null;
354 String fileName = null;
355 String path = null;
356 String oldPhoto = smart.getRequest().getParameter("oldPhoto");
357 if (smart.getFiles().getSize() > 0)
358 {
359 if ("nophoto.jpg".equals(oldPhoto))
360 {
361 RandName rn = new RandName(request.getRemoteAddr());
362 extName = "." + smart.getFiles().getFile(0).getFileExt();// 得到上传文件的扩展名
363 fileName = rn.getRandName();// 生成文件名
364 fileName += extName;
365 path = this.getServletContext().getRealPath("/") + "product"
366 + java.io.File.separator + "upload"
367 + java.io.File.separator + fileName;
368 pr.setPhoto(fileName);
369 }
370 else
371 {
372 path = this.getServletContext().getRealPath("/") + "product"
373 + java.io.File.separator + "upload"
374 + java.io.File.separator + oldPhoto;
375 pr.setPhoto(oldPhoto);
376 }
377 }
378 else
379 {
380 pr.setPhoto("nophoto.jpg");
381 }
382
383 try
384 {
385 if (DaoFactory.getProductDaoInstance().doUpdate(pr))
386 {
387 if (smart.getFiles().getSize() > 0)
388 {
389 smart.getFiles().getFile(0).saveAs(path);
390 }
391 request.setAttribute("msg",
392 MessageUtil.getMessage("product.update.true"));
393 request.setAttribute("cp", cp);
394 request.setAttribute("ls", ls);
395 page = "product_operation.jsp";
396 }
397 else
398 {
399 request.setAttribute("msg",
400 MessageUtil.getMessage("product.update.false"));
401 }
402 }
403 catch (Exception e)
404 {
405 e.printStackTrace();
406 }
407 request.getRequestDispatcher(page).forward(request, response);
408 }
409
410 public void deleteProduct(HttpServletRequest request,
411 HttpServletResponse response) throws ServletException, IOException
412 {
413
414 response.setContentType("text/html;charset=GBK");
415 PrintWriter out = response.getWriter();
416 int pid = 0;
417 try
418 {
419 pid = Integer.parseInt(request.getParameter("pid"));
420
421 }
422 catch (Exception ex)
423 {
424
425 }
426 String pic = request.getParameter("photo");
427 try
428 {
429 boolean flag = DaoFactory.getProductDaoInstance().doDelete(pid);
430 if (!"nophoto.jpg".equals(pic))
431 {
432 String pahtName = this.getServletContext().getRealPath("/")
433 + "product" + java.io.File.separator + "upload"
434 + java.io.File.separator + pic;
435 java.io.File file = new java.io.File(pahtName);
436 if (file.exists())
437 {
438 file.delete();
439 }
440 }
441 out.print(flag);
442 }
443 catch (Exception ex)
444 {
445 ex.printStackTrace();
446 }
447 finally
448 {
449 out.close();
450 }
451
452 }
453
454 public void delete(HttpServletRequest request, HttpServletResponse response)
455 throws ServletException, IOException
456 {
457 String page = "error.jsp";
458 int cp = Integer.parseInt(request.getParameter("cp"));
459 int ls = Integer.parseInt(request.getParameter("ls"));
460 int pid = 0;
461 try
462 {
463 pid = Integer.parseInt(request.getParameter("pid"));
464 }
465 catch (Exception ex)
466 {
467
468 }
469 String pic = request.getParameter("photo");
470 try
471 {
472 if (DaoFactory.getProductDaoInstance().doDelete(pid))
473 {
474 if (!"nophoto.jpg".equals(pic))
475 {
476 String pahtName = this.getServletContext().getRealPath("/")
477 + "product" + java.io.File.separator + "upload"
478 + java.io.File.separator + pic;
479 java.io.File file = new java.io.File(pahtName);
480 if (file.exists())
481 {
482 file.delete();
483 }
484 }
485 request.setAttribute("cp", cp);
486 request.setAttribute("ls", ls);
487 page = "product_operation.jsp";
488 request.setAttribute("msg",
489 MessageUtil.getMessage("product.delete.true"));
490 }
491 else
492 {
493 request.setAttribute("msg",
494 MessageUtil.getMessage("product.delete.false"));
495 }
496 }
497 catch (Exception e)
498 {
499 e.printStackTrace();
500 }
501 request.getRequestDispatcher(page).forward(request, response);
502 }
503
504 public void productinfo(HttpServletRequest request,
505 HttpServletResponse response) throws ServletException, IOException
506 {
507 String path = "error.jsp";
508 int pid = 0;
509 try
510 {
511 pid = Integer.parseInt(request.getParameter("pid"));
512 }
513 catch (Exception ex)
514 {
515 }
516 try
517 {
518 Product pr = DaoFactory.getDaoServiceInstance().findProductInfo(
519 pid, request.getSession().getAttribute(pid + "") == null);
520 if (pr != null)
521 {
522 request.setAttribute("pr", pr);
523 path = "product_info.jsp";
524 }
525 }
526 catch (Exception e)
527 {
528 e.printStackTrace();
529 }
530 request.getRequestDispatcher(path).forward(request, response);
531 }
532
533 }
商品信息修改表单
View Code
1 <h1><em>修改商品信息</em></h1>
2 <form action="ProductServlet" method="post" onSubmit="return validate(this.value)" enctype="multipart/form-data">
3 <c:if test="${pro!=null}" var="res" scope="page">
4 <table border="1" ,width="100%">
5 <tr>
6 <td>商品编号:</td>
7 <td><input type="text" name="pid" value="${pro.pid}" onBlur="validatePid(this.value)" /></td>
8 <td><span id="pid_picMsg"><font color="red">*</font></span></td>
9 <td rowspan="3"><img src="${pageContext.request.contextPath}/product/upload/${pro.photo}"></td>
10
11
12 </tr>
13 <tr>
14 <td>商品名称:</td>
15 <td><input type="text" name="name" value="${pro.name}" onBlur="validateName(this.value)"/></td>
16 <td><span id="name_picMsg"><font color="red">*</font></span></td>
17
18 </tr>
19 <tr>
20 <td>商品价格:</td>
21 <td><input type="text" name="price" value="${pro.price}" onBlur="validatePrice(this.value)"/></td>
22 <td><span id="price_picMsg"><font color="red">*</font></span></td>
23 </tr>
24 <tr>
25 <td>商品库存:</td>
26 <td><input type="text" name="amount" value="${pro.amount}" onBlur="validateAmount(this.value)"/></td>
27 <td><span id="amount_picMsg"><font color="red">*</font></span></td>
28 <td rowspan="3">
29 <div id="imgPreview" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale);128px;height:128px;"></div>
30 </td>
31
32 </tr>
33 <tr>
34 <td>商品类别:</td>
35 <c:if test="${alltypes!=null}" var="tes" scope="page">
36 <td>
37 <select name="types" onBlur="validateTypes(this.value);findSubTypes(this.value)">
38 <option value="0">请选择商品类别</option>
39 <c:forEach items="${alltypes}" var="type">
40 <option value="${type.tid}" ${pro.types.tid==type.tid?"SELECTED":""}>${type.title}</option>
41 </c:forEach>
42 </select>
43 </td>
44 </c:if>
45 <td><span id="types_picMsg"><font color="red">*</font> </span></td>
46 </tr>
47 <tr>
48 <td>商品子类别:</td>
49 <c:if test="${subtypes!=null}" var="tes" scope="page">
50 <td>
51 <select name="subtypes" onBlur="validateSubTypes(this.value)">
52 <option value="0">请选择商品子类别</option>
53 <c:forEach items="${subtypes}" var="type">
54 <option value="${type.stid}" ${pro.subtypes.stid==type.stid?"SELECTED":""}>${type.title}</option>
55 </c:forEach>
56 </select>
57 </td>
58 </c:if>
59 <td><span id="subtypes_picMsg"><font color="red">*</font>
60 </span></td>
61 </tr>
62 <tr>
63 <td>修改照片:</td>
64 <td><input type="file" name="photo" onChange="Preview(this)"/></td>
65 </tr>
66 <tr>
67 <td>商品简介:</td>
68 <td colspan="3">
69 <div class="editor">
70 <textarea id="note" name="note" style="650px;height:200px;visibility:hidden;">
71 ${pro.note}
72 </textarea>
73 </div>
74 </td>
75 </tr>
76 <tr>
77 <input type="hidden" name="oldPhoto" value="${pro.photo}" />
78 <input type="hidden" name="cp" value="<%=request.getParameter("cp")%>"/>
79 <input type="hidden" name="ls" value="<%=request.getParameter("ls")%>"/>
80 <input type="hidden" name="status" value="update"/>
81 <td> <input type="submit" value="修改"/> <input type="reset" value="重置"/></td>
82 </tr>
83 </table>
84 </c:if>
85 </form>
4,通过AJAX删除商品信息
View Code
1 <script language="javascript">
2 var xmlHttp;
3 var temp;
4 function createXMLHttp()
5 {
6 if(window.XMLHttpRequest)
7 {
8 xmlHttp=new XMLHttpRequest();
9 }
10 else
11 {
12 xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
13 }
14 }
15 function deleteProduct(pid,photo)
16 {
17 if(window.confirm("确定删除此商品吗?"))
18 {
19 deleteProductAJAX(pid,photo);
20 }
21 else
22 {
23 return false;
24 }
25 }
26 function deleteProductAJAX(pid,photo)
27 {
28 createXMLHttp();
29 temp=pid;
30 xmlHttp.open("POST", "ProductServlet?status=deleteProduct&pid="+pid+"&photo="+photo);
31 xmlHttp.onreadystatechange=deleteProductAJAXCallBack;
32 xmlHttp.send(null);
33 }
34 function deleteProductAJAXCallBack()
35 {
36 if(xmlHttp.readyState==4 && xmlHttp.status==200)
37 {
38
39 if(xmlHttp.responseText=="true")
40 {
41 alert("商品删除成功!");
42 var tr=document.getElementById("tr-"+temp);
43 tr.parentNode.removeChild(tr);
44 }
45 else
46 {
47 alert("商品删除失败!");
48 }
49 }
50 }
51 </script>
ProductServlet处理请求
View Code
1 public void deleteProduct(HttpServletRequest request,
2 HttpServletResponse response) throws ServletException, IOException
3 {
4
5 response.setContentType("text/html;charset=GBK");
6 PrintWriter out = response.getWriter();
7 int pid = 0;
8 try
9 {
10 pid = Integer.parseInt(request.getParameter("pid"));
11
12 }
13 catch (Exception ex)
14 {
15
16 }
17 String pic = request.getParameter("photo");
18 try
19 {
20 boolean flag = DaoFactory.getProductDaoInstance().doDelete(pid);
21 if (!"nophoto.jpg".equals(pic))
22 {
23 String pahtName = this.getServletContext().getRealPath("/")
24 + "product" + java.io.File.separator + "upload"
25 + java.io.File.separator + pic;
26 java.io.File file = new java.io.File(pahtName);
27 if (file.exists())
28 {
29 file.delete();
30 }
31 }
32 out.print(flag);
33 }
34 catch (Exception ex)
35 {
36 ex.printStackTrace();
37 }
38 finally
39 {
40 out.close();
41 }
42
43 }
页面
View Code
1 <c:if test="${allList!=null}" var="flag" scope="page">
2 <table border="1" width="100%">
3 <tr>
4 <th>商品编号</th>
5 <th>商品名称</th>
6 <th>简介</th>
7 <th>价格</th>
8 <th>库存数量</th>
9 <th>点击率</th>
10 <th colspan="2">操作</th>
11 </tr>
12 <c:forEach items="${allList}" var="pro">
13 <tr id="tr-${pro.pid}">
14 <th>${pro.pid}</th>
15 <th><a href="ProductServlet?status=productinfo&pid=${pro.pid}">${pro.name}</a></th>
16 <th>${pro.note}</th>
17 <th>${pro.price}</th>
18 <th>${pro.amount}</th>
19 <th>${pro.count}</th>
20 <th><a href="ProductServlet?status=updatepre&pid=${pro.pid}&cp=${currentPage}&ls=${lineSize}">修改</a></th>
21 <th><a href="#" onclick="return deleteProduct(${pro.pid},'${pro.photo}')">删除</a></th>
22 </tr>
23 </c:forEach>
24 <c:if test="${fn:length(allList)==0}" var="res" scope="page">
25 <tr>
26 <th colspan="8" >没有符合条件的数据!</th>
27 </tr>
28 </c:if>
29 </table>
30 </c:if>