网页版通讯录
1 需求分析(需求分析师)
功能分析:
1)添加联系人
2)修改联系人
3)删除联系人
4)查询所有联系人
功能流转
美工设计: 设计软件的静态原型
3.2 需求设计(系统分析师/架构师/资深开发人员)
1)设计实体(抽象实体)
联系人实体:
class Contact{
private String id;
private String name;
private String gender;
private int age;
private String phone;
private String email;
private String qq;
}
2)设计“数据库”,(xml代替"数据库")
contact.xml
<contactList>
<contact id="1">
<name>张三</name>
<gender>男</gender>
<age>20</age>
<phone>13433334444</phone>
<email>zs@qq.com</email>
<qq>43222222<qq>
</contact>
</contactList>
3)设计涉及的接口
DAO接口(数据访问对象):实体对象的CRUD方法。
项目原则: 通常一个实体对象就会对应一个DAO接口和一个DAO实现类
interface ContactDao{
public void addContact(Contact contact);//添加联系人
public void updateContact(Contact contact);//修改联系人
public void deleteContact(String id);//删除联系人
public List<Contact> findAll(); //查询所有联系人
public Contact findById(String id);//根据编号查询联系人
}
4)设计项目的目录结构
项目名称: contactSys_web
目录结构:
|- contactSys_web
|-src
|-gz.itcast.contactSys_web.entity : 存放实体对象
|-gz.itcast.contactSys_web.dao : 存放dao的接口
|-gz.itcast.contactSys_web.dao.impl: 存放dao的实现类
|-gz.itcast.contactSys_web.servlet: 存放servlet的类
|-gz.itcast.contactSys_web.test: 存放单元测试类
|-gz.itcast.contactSys_web.util: 存放工具类
|-gz.itcast.contactSys_web.exception: 存放自定义异常类
|-WebRoot
|-html文件
|-images:目录。存放图片资源
|-css:目录。存放css资源
|-js:目录。存放js资源
3.3 编码实现(软件开发工程师/攻城狮)
开发顺序:
设计数据库-> 实体 -> DAO接口,DAO实现-> Servlet+html页面
3.4 功能测试(测试攻城狮)
3.5 性能测试(测试攻城狮)
3.6 部署上线(实施攻城狮)
3.7 维护阶段(实施攻城狮)
大体流程:
工具类:使用dom4j以及xpath技术对数据库(xml)的增删改查;
访问QueryAllContact展示数据库中的用户(xml文件作为数据库);
增加用户:跳转到addContact.html提交表单到AddContacts,将表单传过来的数据封装到一个Contact对象,使用工具类中的addContact添加用户;然后再跳转到QueryAllContact;
修改用户:传递参数id跳转到AlterContactsDisplay展示界面,默认值为id用户的数据;修改后的表单提交到AlterContacts(其中id作为隐藏域提交)然后用工具类中的AlterContact修改用户,然后再跳转到QueryAllContact;
删除用户:id作为参数跳转到DropContacts,使用工具类中的dropContact删除用户;再跳转到QueryAllContact;
其中QueryAllContact界面使用工具类的queryContact来得到所有用户并展示在界面上;
contact类:
package com.base.contact; public class Contact { private String id; public String getId() { return id; } public void setId(String id) { this.id = id; } private String name; private String sex; private int age; private String phone; public Contact() { super(); } public Contact(String name, String sex, int age, String phone, String qq, String email) { super(); this.name = name; this.sex = sex; this.age = age; this.phone = phone; this.qq = qq; this.email = email; } private String qq; private String email; @Override public String toString() { return "Contact [id=" + id + ", name=" + name + ", sex=" + sex + ", age=" + age + ", phone=" + phone + ", qq=" + qq + ", email=" + email + "]"; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
工具接口:
package com.io.tool; import java.util.List; import com.base.contact.Contact; public interface ContactUtil { public boolean addContact(Contact e) throws Exception; public boolean alterContact(Contact e) throws Exception; public boolean dropContact(String id) throws Exception; public Contact findById(String id) throws Exception; public List<Contact> queryContact() throws Exception; }
接口实现类:
package com.base.contact.impl; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import com.base.contact.Contact; import com.io.tool.ContactUtil; public class ContactUtilImpl implements ContactUtil{ private String path; public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public boolean addContact(Contact e) throws Exception { // TODO Auto-generated method stub Document doc; try { doc = new SAXReader().read(path); Element list = (Element) doc.selectNodes("//contacts").get(0); Element newcontact = list.addElement("contact"); String id = UUID.randomUUID().toString().replace("-", ""); newcontact.addAttribute("id", id); newcontact.addElement("name").setText(e.getName()); newcontact.addElement("sex").setText(e.getSex()); newcontact.addElement("age").setText(e.getAge()+""); newcontact.addElement("phone").setText(e.getPhone()); newcontact.addElement("qq").setText(e.getQq()); newcontact.addElement("email").setText(e.getEmail()); OutputFormat format = new OutputFormat().createPrettyPrint(); format.setEncoding("utf-8"); FileOutputStream out = new FileOutputStream(new File(path)); XMLWriter writer = new XMLWriter(out, format); writer.write(doc); writer.close(); out.close(); } catch (DocumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return false; } @Override public boolean alterContact(Contact e) throws Exception { // TODO Auto-generated method stub String id = e.getId(); Document doc; try { doc = new SAXReader().read(path); Element contactElem = (Element) doc.selectSingleNode("//contact[@id='"+ id +"']"); contactElem.element("name").setText(e.getName()); contactElem.element("sex").setText(e.getSex()); contactElem.element("age").setText(e.getAge()+""); contactElem.element("phone").setText(e.getPhone()); contactElem.element("qq").setText(e.getQq()); contactElem.element("email").setText(e.getEmail()); OutputFormat format = new OutputFormat().createPrettyPrint(); format.setEncoding("utf-8"); FileOutputStream out = new FileOutputStream(new File(path)); XMLWriter writer = new XMLWriter(out, format); writer.write(doc); writer.close(); out.close(); } catch (DocumentException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } return false; } @Override public boolean dropContact(String id) throws Exception { // TODO Auto-generated method stub try { Document doc = new SAXReader().read(path); Element list = (Element)doc.selectNodes("//contacts").get(0); list.remove((Element) list.selectSingleNode("//contact[@id='"+id+"']")); FileOutputStream out = new FileOutputStream(new File(path)); OutputFormat format = new OutputFormat().createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter writer = new XMLWriter(out, format); writer.write(doc); writer.close(); out.close(); return true; } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } @Override public Contact findById(String id) throws Exception { // TODO Auto-generated method stub Document doc; doc = new SAXReader().read(path); Element contactElem = (Element) doc.selectSingleNode("//contact[@id='"+ id +"']"); if(contactElem == null){ return null; } Contact e = new Contact(); e.setId(contactElem.attributeValue("id")); e.setAge(Integer.parseInt(contactElem.elementText("age"))); e.setName(contactElem.elementText("name")); e.setEmail(contactElem.elementText("email")); e.setSex(contactElem.elementText("sex")); e.setPhone(contactElem.elementText("phone")); e.setQq(contactElem.elementText("qq")); return e; } @Override public List<Contact> queryContact() throws Exception { // TODO Auto-generated method stub List<Contact> contacts = new ArrayList<Contact>(); Document doc; doc = new SAXReader().read(path); List<Element>list = doc.selectNodes("//contact"); for(Element p : list){ Contact e = new Contact(); e.setId(p.attributeValue("id")); e.setAge(Integer.parseInt(p.elementText("age"))); e.setName(p.elementText("name")); e.setEmail(p.elementText("email")); e.setSex(p.elementText("sex")); e.setPhone(p.elementText("phone")); e.setQq(p.elementText("qq")); contacts.add(e); } return contacts; } }
servlet:
AddContacts:
package com.servlet.alter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.jaxen.function.ConcatFunction; import com.base.contact.Contact; import com.base.contact.impl.ContactUtilImpl; public class AddContacts extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); Contact e = new Contact(); e.setName(request.getParameter("name")); e.setSex(request.getParameter("sex")); e.setAge(Integer.parseInt(request.getParameter("age"))); e.setPhone(request.getParameter("phone")); e.setQq(request.getParameter("qq")); e.setEmail(request.getParameter("email")); String path = this.getServletContext().getRealPath("/WEB-INF/classes/contacts.xml"); ContactUtilImpl utilImpl = new ContactUtilImpl(); utilImpl.setPath(path); try { utilImpl.addContact(e); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/QueryAllContact"); } }
AlterContactsDisplay:
package com.servlet.alter; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.base.contact.Contact; import com.base.contact.impl.ContactUtilImpl; public class AlterContactsDisplay extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); PrintWriter writer = response.getWriter(); String id = request.getParameter("id"); String path = this.getServletContext().getRealPath("/WEB-INF/classes/contacts.xml"); ContactUtilImpl utilImpl = new ContactUtilImpl(); utilImpl.setPath(path); String html = ""; html += "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"; html += "<html xmlns='http://www.w3.org/1999/xhtml'>"; html += "<head>"; html += "<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"; html += "<title>修改联系人</title>"; html += "</head>"; html += ""; html += "<body>"; html += "<center><h3>修改联系人</h3></center>"; html += "<form action='"+request.getContextPath()+"/AlterContacts' method='post'>"; html += "<table align='center' border='1' width='300px'>"; try { Contact e = utilImpl.findById(id); //添加id隐藏域; html += "<input type='hidden' name='id' value='"+e.getId()+"'/>"; html += " <tr>"; html += " <th>姓名</th>"; html += " <td><input type='text' name='name' value='"+e.getName()+"'/></td>"; html += " </tr>"; html += " <tr>"; html += " <th>性别</th>"; html += " <td>"; if("男".equals(e.getSex())){ html += " <input type='radio' name='sex' value='男' checked='checked'/>男"; html += " <input type='radio' name='sex' value='女'/>女"; }else if("女".equals(e.getSex())){ html += " <input type='radio' name='sex' value='男'/>男"; html += " <input type='radio' name='sex' value='女' checked='checked'/>女"; }else{ html += " <input type='radio' name='sex' value='男' checked='checked'/>男"; html += " <input type='radio' name='sex' value='女'/>女"; } html += " </td>"; html += " </tr>"; html += " <tr>"; html += " <th>年龄</th>"; html += " <td><input type='text' name='age' value='"+e.getAge()+"'/></td>"; html += " </tr>"; html += " <tr>"; html += " <th>电话</th>"; html += " <td><input type='text' name='phone' value='"+e.getPhone()+"'/></td>"; html += " </tr>"; html += " <tr>"; html += " <th>邮箱</th>"; html += " <td><input type='text' name='email' value='"+e.getEmail()+"'/></td>"; html += " </tr>"; html += " <tr>"; html += " <th>QQ</th>"; html += " <td><input type='text' name='qq' value='"+e.getQq()+"'/></td>"; html += " </tr>"; } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } html += " <tr>"; html += " <td colspan='2' align='center'>"; html += " <input type='submit' value='保存'/> "; html += " <input type='reset' value='重置'/></td>"; html += " </tr>"; html += "</table>"; html += "</form>"; html += "</body>"; html += "</html>"; writer.write(html); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
AlterContacts:
package com.servlet.alter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.jaxen.function.ConcatFunction; import com.base.contact.Contact; import com.base.contact.impl.ContactUtilImpl; public class AddContacts extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); Contact e = new Contact(); e.setName(request.getParameter("name")); e.setSex(request.getParameter("sex")); e.setAge(Integer.parseInt(request.getParameter("age"))); e.setPhone(request.getParameter("phone")); e.setQq(request.getParameter("qq")); e.setEmail(request.getParameter("email")); String path = this.getServletContext().getRealPath("/WEB-INF/classes/contacts.xml"); ContactUtilImpl utilImpl = new ContactUtilImpl(); utilImpl.setPath(path); try { utilImpl.addContact(e); } catch (Exception e1) { // TODO Auto-generated catch block e1.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/QueryAllContact"); } }
DropContacts:
package com.servlet.alter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import com.base.contact.Contact; import com.base.contact.impl.ContactUtilImpl; public class DropContacts extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String id = request.getParameter("id"); String path = this.getServletContext().getRealPath("/WEB-INF/classes/contacts.xml"); ContactUtilImpl utilImpl = new ContactUtilImpl(); utilImpl.setPath(path); try { utilImpl.dropContact(id); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/QueryAllContact"); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
QueryAllContact:
package com.servlet.query; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.base.contact.Contact; import com.base.contact.impl.ContactUtilImpl; public class QueryAllContact extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String path = this.getServletContext().getRealPath("/WEB-INF/classes/contacts.xml"); ContactUtilImpl utilImpl = new ContactUtilImpl(); utilImpl.setPath(path); PrintWriter writer = response.getWriter(); String html = ""; html+="<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"; html+="<html xmlns='http://www.w3.org/1999/xhtml'>"; html+="<head>"; html+="<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"; html+="<title>查询所有联系人</title>"; html+="<style type='text/css'>"; html+=" table td{"; html+=" /*文字居中*/"; html+=" text-align:center;"; html+=" }"; html+=" "; html+=" /*合并表格的边框*/"; html+=" table{"; html+=" border-collapse:collapse;"; html+=" }"; html+="</style>"; html+="</head>"; html+="<body>"; html+="<center><h3>查询所有联系人</h3></center>"; html+="<table align='center' border='1' width='700px'>"; html+=" <tr>"; html+=" <th>编号</th>"; html+=" <th>姓名</th>"; html+=" <th>性别</th>"; html+=" <th>年龄</th>"; html+=" <th>电话</th>"; html+=" <th>邮箱</th>"; html+=" <th>QQ</th>"; html+=" <th>操作</th>"; html+=" </tr>"; try { List<Contact> list = utilImpl.queryContact(); for(Contact e : list){ html+=" <tr>"; html+=" <td>"+e.getId()+"</td>"; html+=" <td>"+e.getName()+"</td>"; html+=" <td>"+e.getSex()+"</td>"; html+=" <td>"+e.getAge()+"</td>"; html+=" <td>"+e.getPhone()+"</td>"; html+=" <td>"+e.getEmail()+"</td>"; html+=" <td>"+e.getQq()+"</td>"; html+=" <td><a href='/Contacts/AlterContactsDisplay?id="+e.getId()+"'>修改</a> <a href='"+request.getContextPath()+"/DropContacts?id="+e.getId()+"'>删除</a></td>"; html+=" </tr>"; } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } html+=" <tr>"; html+=" <td colspan='8' align='center'><a href='"+request.getContextPath()+"/addContact.html'>[添加联系人]</a></td>"; html+=" </tr>"; html+="</table>"; html+="</body>"; html+="</html>"; writer.write(html); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
addContact.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>添加联系人</title> </head> <body> <center><h3>添加联系人</h3></center> <form action="/Contacts/AddContacts" method="post"> <table align="center" border="1" width="300px"> <tr> <th>姓名</th> <td><input type="text" name="name"/></td> </tr> <tr> <th>性别</th> <td> <input type="radio" name="sex" value="男"/>男 <input type="radio" name="sex" value="女"/>女 </td> </tr> <tr> <th>年龄</th> <td><input type="text" name="age"/></td> </tr> <tr> <th>电话</th> <td><input type="text" name="phone"/></td> </tr> <tr> <th>邮箱</th> <td><input type="text" name="email"/></td> </tr> <tr> <th>QQ</th> <td><input type="text" name="qq"/></td> </tr> <tr> <td colspan="2" align="center"> <input type="submit" value="保存"/> <input type="reset" value="重置"/></td> </tr> </table> </form> </body> </html>
改装mvc版:
dao+service+servlet+jsp;
contactUtil + ContactUtilImpl:
package com.contact.dao; import java.util.List; import com.base.others.Contact; public interface ContactUtil { public void addContact(Contact e); public void alterContact(Contact e); public void dropContact(String id); public Contact findById(String id); public List<Contact> queryContact(); public boolean checkName(String name); }
package com.contact.dao; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import com.base.others.Contact; import com.contact.dao.*; import com.contact.util.XmlUtil; public class ContactUtilImpl implements ContactUtil{ private String path; public ContactUtilImpl() { path = "E:/Test/contacts.xml"; } @Override public void addContact(Contact e){ // TODO Auto-generated method stub Document doc; doc = XmlUtil.getDocument(path);; Element list = (Element) doc.selectNodes("//contacts").get(0); Element newcontact = list.addElement("contact"); String id = UUID.randomUUID().toString().replace("-", ""); newcontact.addAttribute("id", id); newcontact.addElement("name").setText(e.getName()); newcontact.addElement("sex").setText(e.getSex()); newcontact.addElement("age").setText(e.getAge()+""); newcontact.addElement("phone").setText(e.getPhone()); newcontact.addElement("qq").setText(e.getQq()); newcontact.addElement("email").setText(e.getEmail()); XmlUtil.writeDocument(doc, path); } @Override public void alterContact(Contact e){ // TODO Auto-generated method stub String id = e.getId(); Document doc; doc = XmlUtil.getDocument(path); Element contactElem = (Element) doc.selectSingleNode("//contact[@id='"+ id +"']"); contactElem.element("name").setText(e.getName()); contactElem.element("sex").setText(e.getSex()); contactElem.element("age").setText(e.getAge()+""); contactElem.element("phone").setText(e.getPhone()); contactElem.element("qq").setText(e.getQq()); contactElem.element("email").setText(e.getEmail()); OutputFormat format = new OutputFormat().createPrettyPrint(); format.setEncoding("utf-8"); XmlUtil.writeDocument(doc, path); } @Override public void dropContact(String id){ // TODO Auto-generated method stub Document doc = XmlUtil.getDocument(path); Element list = (Element)doc.selectNodes("//contacts").get(0); list.remove((Element) list.selectSingleNode("//contact[@id='"+id+"']")); XmlUtil.writeDocument(doc, path); } @Override public Contact findById(String id){ // TODO Auto-generated method stub Document doc; doc = XmlUtil.getDocument(path); Element contactElem = (Element) doc.selectSingleNode("//contact[@id='"+ id +"']"); if(contactElem == null){ return null; } Contact e = new Contact(); e.setId(contactElem.attributeValue("id")); e.setAge(Integer.parseInt(contactElem.elementText("age"))); e.setName(contactElem.elementText("name")); e.setEmail(contactElem.elementText("email")); e.setSex(contactElem.elementText("sex")); e.setPhone(contactElem.elementText("phone")); e.setQq(contactElem.elementText("qq")); return e; } @Override public List<Contact> queryContact(){ // TODO Auto-generated method stub List<Contact> contacts = new ArrayList<Contact>(); Document doc; doc = XmlUtil.getDocument(path); List<Element>list = doc.selectNodes("//contact"); for(Element p : list){ Contact e = new Contact(); e.setId(p.attributeValue("id")); e.setAge(Integer.parseInt(p.elementText("age"))); e.setName(p.elementText("name")); e.setEmail(p.elementText("email")); e.setSex(p.elementText("sex")); e.setPhone(p.elementText("phone")); e.setQq(p.elementText("qq")); contacts.add(e); } return contacts; } @Override public boolean checkName(String name){ Document doc = XmlUtil.getDocument(path); if(doc.selectSingleNode("//name[text()='"+name+"']") == null) return false; else return true; } }
contactService+contactServiceImpl:
package com.contact.service; import java.util.List; import com.base.others.Contact; import com.contact.exception.RepeatName; public interface ContactService { public void addContact(Contact e) throws RepeatName; public void alterContact(Contact e); public void dropContact(String id); public Contact findById(String id); public List<Contact> queryContact(); }
package com.contact.service; import java.util.List; import com.base.others.Contact; import com.contact.dao.ContactUtilImpl; import com.contact.exception.RepeatName; public class ContactServiceImpl implements ContactService{ ContactUtilImpl contactUtilImpl; public ContactServiceImpl() { contactUtilImpl = new ContactUtilImpl(); } @Override public void addContact(Contact e) throws RepeatName { if(contactUtilImpl.checkName(e.getName())){ throw new RepeatName("此用户已经被使用"); }else{ contactUtilImpl.addContact(e); } } @Override public void alterContact(Contact e){ contactUtilImpl.alterContact(e); } @Override public void dropContact(String id) { // TODO Auto-generated method stub contactUtilImpl.dropContact(id); } @Override public Contact findById(String id) { // TODO Auto-generated method stub return contactUtilImpl.findById(id); } @Override public List<Contact> queryContact() { // TODO Auto-generated method stub return contactUtilImpl.queryContact(); } }
AddContacts+AlterContacts+DropContacts+Index:
package com.contact.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.jaxen.function.ConcatFunction; import com.base.others.Contact; import com.contact.dao.ContactUtilImpl; import com.contact.exception.RepeatName; import com.contact.service.ContactServiceImpl; public class AddContacts extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); Contact e = new Contact(); e.setName(request.getParameter("name")); e.setSex(request.getParameter("sex")); e.setAge(Integer.parseInt(request.getParameter("age"))); e.setPhone(request.getParameter("phone")); e.setQq(request.getParameter("qq")); e.setEmail(request.getParameter("email")); String path = this.getServletContext().getRealPath("/WEB-INF/classes/contacts.xml"); ContactServiceImpl utilImpl = new ContactServiceImpl(); try { utilImpl.addContact(e); } catch (RepeatName e1) { request.setAttribute("msg", e1.getMessage()); request.getRequestDispatcher("/contactList/add.jsp").forward(request, response);; return; } response.sendRedirect(request.getContextPath() + "/Index"); } }
package com.contact.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import org.jaxen.function.ConcatFunction; import com.base.others.Contact; import com.contact.exception.RepeatName; import com.contact.service.ContactServiceImpl; public class AlterContacts extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); Contact e = new Contact(); e.setId(request.getParameter("id")); e.setName(request.getParameter("name")); e.setSex(request.getParameter("sex")); e.setAge(Integer.parseInt(request.getParameter("age"))); e.setPhone(request.getParameter("phone")); e.setQq(request.getParameter("qq")); e.setEmail(request.getParameter("email")); String path = this.getServletContext().getRealPath("/WEB-INF/classes/contacts.xml"); ContactServiceImpl utilImpl = new ContactServiceImpl(); utilImpl.alterContact(e); response.sendRedirect(request.getContextPath() + "/Index"); } }
package com.contact.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.Attribute; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; import com.base.others.Contact; import com.contact.service.ContactServiceImpl; public class DropContacts extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String id = request.getParameter("id"); String path = this.getServletContext().getRealPath("/WEB-INF/classes/contacts.xml"); ContactServiceImpl utilImpl = new ContactServiceImpl(); try { utilImpl.dropContact(id); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/Index"); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
package com.contact.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.SAXReader; import com.base.others.Contact; import com.contact.service.ContactServiceImpl; public class Index extends HttpServlet { /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); String path = this.getServletContext().getRealPath("/WEB-INF/classes/contacts.xml"); ContactServiceImpl utilImpl = new ContactServiceImpl(); try { List<Contact> list = utilImpl.queryContact(); request.setAttribute("list", list); request.getRequestDispatcher("/contactList/query.jsp").forward(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"); out.println("<HTML>"); out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"); out.println(" <BODY>"); out.print(" This is "); out.print(this.getClass()); out.println(", using the POST method"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
读写类XmlUtil:
package com.contact.util; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class XmlUtil { public static Document getDocument(String path){ try { Document doc = new SAXReader().read(new File(path)); return doc; } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } } public static void writeDocument(Document doc, String path){ FileOutputStream out; try { out = new FileOutputStream(new File(path)); OutputFormat format = new OutputFormat().createPrettyPrint(); format.setEncoding("utf-8"); XMLWriter writer = new XMLWriter(out, format); writer.write(doc); writer.close(); out.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } } }
自定义异常类:RePeatName:
package com.contact.exception; public class RepeatName extends Exception{ public RepeatName() { super(); // TODO Auto-generated constructor stub } public RepeatName(String message) { super(message); // TODO Auto-generated constructor stub } }
扩展块——数据库:
MySqlUtil:
package com.contact.util; import java.io.FileInputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.management.RuntimeErrorException; import com.mysql.jdbc.Driver; public class MysqlUtil { private static String url = null; private static String user = null; private static String password = null; private static String driverClass = null; static{ try { Properties properties = new Properties(); // FileInputStream fileInputStream = new FileInputStream("./src/db.properties"); InputStream in = MysqlUtil.class.getResourceAsStream("/db.properties"); properties.load(in); url = properties.getProperty("url"); user = properties.getProperty("user"); password = properties.getProperty("password"); driverClass = properties.getProperty("driverClass"); Class.forName(driverClass); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static Connection getConn() { // TODO Auto-generated method stub try { Connection conn = DriverManager.getConnection(url, user, password); return conn; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } } public static void close(Connection conn, Statement state) { if(conn != null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(state != null){ try { state.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public static void close(Connection conn, Statement state, ResultSet resultSet) { if(resultSet != null){ try { resultSet.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); throw new RuntimeException(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(state != null){ try { state.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
contactUtilMysqlImpl:
package com.contact.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.dom4j.Document; import com.base.others.Contact; import com.contact.util.MysqlUtil; import com.contact.util.XmlUtil; public class ContactUtilMysqlImpl implements ContactUtil{ @Override public void addContact(Contact e) { Connection conn = null; PreparedStatement state = null; try { conn = MysqlUtil.getConn(); String sql = "INSERT INTO contactUser VALUES(?,?,?,?,?,?,?);"; state = conn.prepareStatement(sql); String id = UUID.randomUUID().toString().replace("-", ""); state.setString(1, id); state.setString(2, e.getName()); state.setString(3, e.getSex()); state.setInt(4, e.getAge()); state.setString(5, e.getPhone()); state.setString(6, e.getQq()); state.setString(7, e.getEmail()); int count = state.executeUpdate(); System.out.println("已成功插入" + count + "条记录"); } catch (Exception e2) { throw new RuntimeException(e2); }finally{ MysqlUtil.close(conn, state); } } @Override public void alterContact(Contact e) { Connection conn = null; PreparedStatement state = null; try { conn = MysqlUtil.getConn(); String sql = "UPDATE contactUser SET NAME=?,sex=?,age=?,phone=?,qq=?,email=? WHERE id=?;"; state = conn.prepareStatement(sql); state.setString(1, e.getName()); state.setString(2, e.getSex()); state.setInt(3, e.getAge()); state.setString(4, e.getPhone()); state.setString(5, e.getQq()); state.setString(6, e.getEmail()); state.setString(7, e.getId()); int count = state.executeUpdate(); System.out.println("已成功修改" + count + "条记录"); } catch (Exception e2) { throw new RuntimeException(e2); }finally{ MysqlUtil.close(conn, state); } } @Override public void dropContact(String id) { Connection conn = null; PreparedStatement state = null; try { conn = MysqlUtil.getConn(); String sql = "DELETE FROM contactUser WHERE id=?;"; state = conn.prepareStatement(sql); state.setString(1, id); int count = state.executeUpdate(); System.out.println("已成功删除" + count + "条记录"); } catch (Exception e2) { throw new RuntimeException(e2); }finally{ MysqlUtil.close(conn, state); } } @Override public Contact findById(String id) { Connection conn = null; PreparedStatement state = null; ResultSet resultSet = null; try { conn = MysqlUtil.getConn(); String sql = "SELECT * FROM contactUser WHERE id=?;"; state = conn.prepareStatement(sql); state.setString(1, id); resultSet = state.executeQuery(); Contact e = null; while(resultSet.next()){ e = new Contact(); e.setId(resultSet.getString("id")); e.setName(resultSet.getString("name")); e.setSex(resultSet.getString("sex")); e.setAge(resultSet.getInt("age")); e.setPhone(resultSet.getString("phone")); e.setQq(resultSet.getString("qq")); e.setEmail(resultSet.getString("email")); } return e; } catch (Exception e2) { throw new RuntimeException(e2); }finally{ MysqlUtil.close(conn, state, resultSet); } } @Override public List<Contact> queryContact() { Connection conn = null; PreparedStatement state = null; ResultSet resultSet = null; try { conn = MysqlUtil.getConn(); String sql = "SELECT * FROM contactUser;"; state = conn.prepareStatement(sql); resultSet = state.executeQuery(); List<Contact> list = new ArrayList<Contact>(); while(resultSet.next()){ Contact e = new Contact(); e.setId(resultSet.getString("id")); e.setName(resultSet.getString("name")); e.setSex(resultSet.getString("sex")); e.setAge(resultSet.getInt("age")); e.setPhone(resultSet.getString("phone")); e.setQq(resultSet.getString("qq")); e.setEmail(resultSet.getString("email")); list.add(e); } return list; } catch (Exception e2) { throw new RuntimeException(e2); }finally{ MysqlUtil.close(conn, state, resultSet); } } @Override public boolean checkName(String name) { Connection conn = null; PreparedStatement state = null; ResultSet resultSet = null; try { conn = MysqlUtil.getConn(); String sql = "SELECT * FROM contactUser WHERE name=?;"; state = conn.prepareStatement(sql); state.setString(1, name); resultSet = state.executeQuery(); if(resultSet.next()) return true; else return false; } catch (Exception e2) { throw new RuntimeException(e2); }finally{ MysqlUtil.close(conn, state, resultSet); } } }