编码实战Web端联系人的增删改查

首先画出分析图

实现效果如图

项目下的包如图:

 

 


实体包

package com.contactSystem.entiey;public class Contact {private String Id;private String name;private String sex;private String age;private String phone;private String qq;private String email;public String getId() {return Id;}public void setId(String id) {Id = id;}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 String getAge() {return age;}public void setAge(String 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;}@Overridepublic String toString() {return "Contact [Id=" + Id + ", name=" + name + ", sex=" + sex+ ", age=" + age + ", phone=" + phone + ", qq=" + qq+ ", email=" + email + "]";}}

  XML的工具包(只是避免了代码的重复使用,将其放进工具包中)

package com.contactSystem.util;import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;import javax.management.RuntimeErrorException;import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;/** xml操作的工具类*/
public class XMLUtil {//写出一个xml文件public static void write2xml(Document doc) throws Exception{OutputStream out=new FileOutputStream("e:/contact.xml");OutputFormat format=OutputFormat.createPrettyPrint();format.setEncoding("utf-8");XMLWriter writer=new XMLWriter(out,format);writer.write(doc);writer.close();}//读取本地xml文件的方法public static Document getDocument(){Document doc;try {doc = new SAXReader().read("e:/contact.xml");return doc;} catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();throw new RuntimeException(e);}}}

  


抽象的接口

package com.contactSystem.dao;import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.List;import org.dom4j.DocumentException;
import com.contactSystem.entiey.Contact;public interface ContactOperate {public void addContact(Contact contact) throws Exception;public void updateContact(Contact contact) throws Exception;public void removeContact(String id) throws Exception;public Contact findContact(String id) throws Exception;public List<Contact>  allContacts();
}

  具体的实现方法和操作

package com.contactSystem.dao.daoImpl;import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;import javax.persistence.Id;import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;import com.contactSystem.dao.ContactOperate;
import com.contactSystem.entiey.Contact;
import com.contactSystem.util.XMLUtil;public class Operater implements ContactOperate {@Override//添加联系人public void addContact(Contact contact) throws Exception {// TODO Auto-generated method stubFile file=new File("e:/contact.xml");Document doc=null;Element rootElem=null;if (file.exists()) {doc=new SAXReader().read(file);rootElem=doc.getRootElement();}else {doc=DocumentHelper.createDocument();rootElem=doc.addElement("ContactList");}//开始添加个体Element element=rootElem.addElement("contact");//有系统自动生成一随机且唯一的ID,赋给联系人Id,系统提供了一个包UUID包String uuid=UUID.randomUUID().toString().replace("-", "");element.addAttribute("Id", uuid);element.addElement("姓名").setText(contact.getName());element.addElement("name").setText(contact.getName());element.addElement("sex").setText(contact.getSex());element.addElement("age").setText(contact.getAge());element.addElement("phone").setText(contact.getPhone());element.addElement("email").setText(contact.getEmail());element.addElement("qq").setText(contact.getQq());//写入到本地的xml文档中XMLUtil.write2xml(doc);}@Overridepublic void updateContact(Contact contact) throws Exception {// TODO Auto-generated method stub//通过xpath查找对应id的联系人Document document=XMLUtil.getDocument();Element element=(Element) document.selectSingleNode("//contact[@Id='"+contact.getId()+"']");//根据标签改文本System.out.println(element);element.element("name").setText(contact.getName());element.element("age").setText(contact.getAge());element.element("email").setText(contact.getEmail());element.element("phone").setText(contact.getPhone());element.element("sex").setText(contact.getSex());element.element("qq").setText(contact.getQq());XMLUtil.write2xml(document);}@Overridepublic void removeContact(String id) throws Exception {// TODO Auto-generated method stub//通过xpath去查找对应的contactDocument document=XMLUtil.getDocument();Element element=(Element) document.selectSingleNode("//contact[@Id='"+id+"']");/*** 如果是火狐浏览器,其本身有一个bug,对于一个get请求,它会重复做两次,* 第一次会把一个唯一的id给删除掉,但是在第二次的时候,它会继续去删,而这个时候查找不到,会报错,会发生错误,* 为了解决这个bug,我们在这里验证其是否为空*/if (element!=null) {element.detach();XMLUtil.write2xml(document);}}@Overridepublic Contact findContact(String id) throws Exception {// TODO Auto-generated method stubDocument document=XMLUtil.getDocument();Element e=(Element) document.selectSingleNode("//contact[@Id='"+id+"']");Contact contact=null;if (e!=null) {contact=new Contact();contact.setAge(e.elementText("age"));contact.setEmail(e.elementText("email"));contact.setId(e.attributeValue("id"));contact.setName(e.elementText("name"));contact.setPhone(e.elementText("phone"));contact.setSex(e.elementText("sex"));contact.setQq(e.elementText("qq"));}return contact;}@Overridepublic List<Contact> allContacts() {// TODO Auto-generated method stubDocument document=XMLUtil.getDocument();List<Contact> list=new ArrayList<Contact>();List<Element> conElements=(List<Element>)document.selectNodes("//contact");for (Element element : conElements) {Contact contact=new Contact();contact.setId(element.attributeValue("Id"));contact.setAge(element.elementText("age"));contact.setEmail(element.elementText("email"));contact.setName(element.elementText("name"));contact.setPhone(element.elementText("phone"));contact.setQq(element.elementText("qq"));contact.setSex(element.elementText("sex"));list.add(contact);}return list;}}

  


 

添加联系人的html页面

<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>添加联系人</title><style media="screen">#btn{width:40px;width: 50px;background: green;color: white;font-size:14px;}</style>
</head><body><center><h2>添加联系人</h2></center><form action="/ContactWeb/addServlet" method="post"><table border="1" align="center"><tbody><tr><th>姓名</th><td><input type="text" name="userName" /></td></tr><tr><th>年龄</th><td><input type="text" name="age" /></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="phone" /></td></tr><tr><th>QQ</th><td><input type="text" name="qq" /></td></tr><tr><th>邮箱</th><td><input type="text" name="email" /></td></tr><tr><td colspan="3" align="center"><input type="submit"  value="提交" id="btn"/></td></tr></tbody></table></form>
</body></html>

  


接下来则是最重要的servlet(显示首页,所有联系人)

package com.contactSystem.servlet;import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.contactSystem.dao.daoImpl.Operater;
import com.contactSystem.entiey.Contact;public class Index extends HttpServlet {/*** 显示所有联系人的逻辑方式*/private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");Operater operater=new Operater();List<Contact> contacts=operater.allContacts();PrintWriter writer=response.getWriter();/*** shift+alt+A ——>区域选择 * 正则表达式:“."表示任意字符,"*"表示多个字符*             “/1”表示一行代表匹配一行内容*/String html="";html+= "<!DOCTYPE html>";html+= "<html>";html+= "";html+= "<head>";html+= "    <meta charset='utf-8'>";html+= "    <title>查询所有联系人</title>";html+= "    <style media='screen'>";html+= "        table td {";html+= "            text-align: center;";html+= "        }";html+= "";html+= "        table {";html+= "            border-collapse: collapse;";html+= "        }";html+= "    </style>";html+= "</head>";html+= "";html+= "<body>";html+= "    <center>";html+= "        <h2>查询所有联系人</h2>";html+= "    </center>";html+= "    <table border='1' align='center'>";html+= "        <tbody>";html+= "            <thead>";html+= "                <th>编号</th>";html+= "                <th>姓名</th>";html+= "                <th>性别</th>";html+= "                <th>年龄</th>";html+= "                <th>电话</th>";html+= "                <th>QQ</th>";html+= "                <th>邮箱</th>";html+= "                <th>操作</th>";html+= "            </thead>";html+= "            ";html+= "            <tr>";if (contacts!=null) {for (Contact contact : contacts) {html+= "                <td>"+contact.getId()+"</td>";html+= "                <td>"+contact.getName()+"</td>";html+= "                <td>"+contact.getSex()+"</td>";html+= "                <td>"+contact.getAge()+"</td>";html+= "                <td>"+contact.getPhone()+"</td>";html+= "                <td>"+contact.getQq()+"</td>";html+= "                <td>"+contact.getEmail()+"</td>";html+= "                <td><a href='"+request.getContextPath()+"/FindIdServlet?id="+contact.getId()+"'>修改</a>  <a href='"+request.getContextPath()+"/DeleteServlet?id="+contact.getId()+"'>删除</a></td>";html+= "            </tr>";}}html+= "            <tr>";html+= "                <td colspan='8'>";html+= "                    <a href='"+request.getContextPath()+"/add.html'''>添加联系人</a>";html+= "                </td>";html+= "            </tr>";html+= "        </tbody>";html+= "    </table>";html+= "</body>";html+= "";html+= "</html>";writer.write(html);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}}

  添加联系人的servlet

package com.contactSystem.servlet;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 com.contactSystem.dao.daoImpl.Operater;
import com.contactSystem.entiey.Contact;public class addServlet extends HttpServlet {/*** 处理添加联系人的逻辑*/private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("utf-8");String userName=request.getParameter("userName");String age=request.getParameter("age");String sex=request.getParameter("sex");String phone=request.getParameter("phone");String qq=request.getParameter("qq");String email=request.getParameter("email");Operater operater=new Operater();Contact contact=new Contact();contact.setName(userName);contact.setAge(age);contact.setSex(sex);contact.setPhone(phone);contact.setQq(qq);contact.setEmail(email);try {operater.addContact(contact);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}response.sendRedirect(request.getContextPath()+"/Index");}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}}

 修改联系人,根据查找到的联系人,显示在其上面如图(根据显示的首页显示得内容为本页面的默认值)

首先是要去查找这个联系人的信息,即FindIdServlet

package com.contactSystem.servlet;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 com.contactSystem.dao.daoImpl.Operater;
import com.contactSystem.entiey.Contact;public class FindIdServlet extends HttpServlet {/*** 修改联系人逻辑*/private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");PrintWriter writer=response.getWriter();Operater operater=new Operater();String id=request.getParameter("id");Contact contact=null;try {contact=operater.findContact(id);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}String html="";html += "<!DOCTYPE html>";html += "<html>";html += "<head>";html += "    <meta charset='utf-8'>";html += "    <title>添加联系人</title>";html += "    <style media='screen'>";html += "      #btn{";html += "        width:40px;";html += "        width: 50px;";html += "        background: green;";html += "        color: white;";html += "        font-size:14px;";html += "      }";html += "    </style>";html += "</head>";html += "";html += "<body>";html += "    <center>";html += "        <h2>修改联系人</h2>";html += "    </center>";html += "    <form action='"+request.getContextPath()+"/UpdateServlet' method='post'>";html +="<input type='hidden' name='id' value='"+id+"' />";html += "        <table border='1' align='center'>";html += "            <tbody>";html += "                <tr>";html += "                    <th>姓名</th>";html += "                    <td><input type='text' name='userName' value='"+contact.getName()+"'/></td>";html += "                </tr>";html += "                <tr>";html += "                    <th>年龄</th>";html += "                    <td><input type='text' name='age' value='"+contact.getAge()+"' /></td>";html += "                </tr>";html += "                <tr>";html += "                  <th>性别</th>";html += "                  <td>";if (contact.getSex().equals("男")) {html += "                    <input type='radio' name='sex'  value='男'    checked='checked'/>男  ";html += "                    <input type='radio' name='sex' value='女' />女";}else {html += "                    <input type='radio' name='sex'  value='男'    />男  ";html += "                    <input type='radio' name='sex' value='女' checked='checked' />女";}html += "                  </td>";html += "                </tr>";html += "                <tr>";html += "                    <th>电话</th>";html += "                    <td><input type='text' name='phone' value='"+contact.getPhone()+"' /></td>";html += "                </tr>";html += "                <tr>";html += "                    <th>QQ</th>";html += "                    <td><input type='text' name='qq' value='"+contact.getQq()+"'  /></td>";html += "                </tr>";html += "                <tr>";html += "                    <th>邮箱</th>";html += "                    <td><input type='text' name='email' value='"+contact.getEmail()+"' /></td>";html += "                </tr>";html += "                <tr>";html += "                  <td colspan='3' align='center'>";html += "                    <input type='submit'  value='提交' id='btn'/>";html += "                  </td>";html += "                </tr>";html += "            </tbody>";html += "        </table>";html += "    </form>";html += "</body>";html += "";html += "</html>";writer.write(html);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}}

  然后则是根据提交的内容去修改本地的联系人

package com.contactSystem.servlet;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 com.contactSystem.dao.daoImpl.Operater;
import com.contactSystem.entiey.Contact;public class UpdateServlet extends HttpServlet {/*** 将修改后的数据提交*/private static final long serialVersionUID = 1L;public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");request.setCharacterEncoding("utf-8");String userName=request.getParameter("userName");System.out.println(userName);String age=request.getParameter("age");String sex=request.getParameter("sex");String phone=request.getParameter("phone");String qq=request.getParameter("qq");String email=request.getParameter("email");String id=request.getParameter("id");Operater operater=new Operater();Contact contact=new Contact();contact.setId(id);contact.setName(userName);contact.setAge(age);contact.setSex(sex);contact.setPhone(phone);contact.setQq(qq);contact.setEmail(email);try {operater.updateContact(contact);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}response.sendRedirect(request.getContextPath()+"/Index");}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}}

  最后则是删除联系人,不过要注意的是:火狐浏览器如果判断是get请求的话,会向服务器发送两次请求,可能会导致一些问题,其他的浏览器不会出出现该问题

package com.contactSystem.servlet;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 com.contactSystem.dao.daoImpl.Operater;public class DeleteServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charset=utf-8");String id=request.getParameter("id");Operater operater=new Operater();try {operater.removeContact(id);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}response.sendRedirect(request.getContextPath()+"/Index");}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doGet(request, response);}
}

  

 最后:不用jsp去写,就用servlet去写html真的好累,还是好好学jsp吧。

 

转载于:https://www.cnblogs.com/helloworldcode/p/6041130.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/270535.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

选型java程序_Java程序员自动化指南

一、背景在Java web开发中&#xff0c;虽然Spring boot已经帮助我们简化了很多工作&#xff0c;但项目中庞杂的业务仍然需要自己去编写较多的 entity&#xff0c;vo&#xff0c;Mapper&#xff0c;Service&#xff0c; Controller 代码等&#xff0c;那么我们有没有什么办法来简…

网络知识:光猫光纤宽带故障排查笔记

在日常上网过程中出现的故障&#xff0c;很大一部分是由于线路和光猫故障引起&#xff0c;现简单介绍一下&#xff0c;如何处理这些故障。 现象一&#xff1a;不能上网&#xff08;网络中断&#xff09; 故障排查&#xff1a; 1、确认您的光猫信号灯是否正常&#xff1a; ①电源…

treeview自动从表中添加标题和列值做目录的方法2

treeview自动从表中添加标题和列值做目录的方法2&#xff0c;该方法是借鉴万一老师的 http://www.cnblogs.com/del/archive/2008/05/15/1114450.html 首先界面上添加treeview组件&#xff0c;然后在treeview的onchange事件里这样写&#xff1a; 因为要用到定义个过程&#xff0…

Linux常用运维命令笔记

今天给大家整理一下Linux常用的命令&#xff0c;希望对大家能有所帮助&#xff01;MYSQL相关1、查看mysql版本status; select version()2、 mysql启动命令#01 使用 service 启动&#xff1a;service mysqld start (5.0版本) service mysql start (5.5.7版本) #02 使用 mysqld 脚…

电脑知识:如何将旧电脑文件迁移到新电脑中,包括操作系统

将旧电脑中的文件和操作系统全部转移到新电脑中&#xff0c;一般可以借助分区助手、磁盘精灵或者GHOST等磁盘工具。为了提高数据传输速度&#xff0c;可以将旧电脑的硬盘拆下安装到新电脑&#xff0c;然后使用PE工具盘引导电脑进入PE系统中&#xff0c;将旧电脑硬盘中的数据借助…

浏览器插件:一款解决谷歌浏览器吃内存神器插件

Chrome浏览器是大部分开发者必备的浏览器&#xff0c;它的主要有点有便于调试、启动快、无广告。但是谷歌浏览器也有自己的缺点&#xff0c;Chrome浏览器对系统内存的占用太大了&#xff0c;每打开一个页面都会占用系统内存。如果你的浏览器一下子打开几十个网页&#xff0c;不…

电脑软件:推荐两款好用的文件重复检测软件

❤️作者主页&#xff1a;IT技术分享社区 ❤️作者简介&#xff1a;大家好,我是IT技术分享社区的博主&#xff0c;从事C#、Java开发九年&#xff0c;对数据库、C#、Java、前端、运维、电脑技巧等经验丰富。 ❤️个人荣誉&#xff1a; 数据库领域优质创作者&#x1f3c6;&#x…

APP技巧:微信中这6个设置建议关闭,可以防止个人信息或将全暴露

目录 01、 开启添加好友验证功能 02、 添加“我”的方式 03、不让他&#xff08;她&#xff09;看 04、允许陌生人查看10条朋友圈 05、 设置查看朋友圈范围 06、微信授权管理 相信提到微信&#xff0c;大家基本每天都在用&#xff0c;如今微信已经成为了我们社交软件中的第一大…

硬件知识:内存单根16G和两根8G差别有多大?

关于内存单根16G和两根8G的差别&#xff0c;小编觉得这些事实&#xff0c;你得知道&#xff01; 论单根16G和两根8G的区别&#xff01; 内存单通道和双通道&#xff0c;大家都有听过吧&#xff01; 理解起来很简单&#xff0c;一个单通道&#xff0c;只能进行单向传输数据&…

操作系统:Win10的沙盒是什么,如何使用,看完你就懂了

Win10操作系统新增的windows沙盒是一种安全机制&#xff0c;为执行中的程式提供的隔离环境。通常是作为一些来源不可信、具有破坏力或无法判定程序意图的应用程序提供实验之用。很多网友想要通过沙盒运行一些未知的程序&#xff0c;但是不知道windows沙盒如何开启使用&#xff…

操作系统:电脑系统盘常见文件夹的功能详解

目录 一、C盘根目录常见文件夹 二、隐藏文件夹 相信很多电脑小白对于系统C盘每个文件夹的功能不是很清楚&#xff0c;今天小编给大家介绍一下电脑系统盘文件的功能详解&#xff0c;希望对大家能有所帮助&#xff01; 一、C盘根目录常见文件夹 1、debug 是系统调试文件夹&#x…

手机技巧:手机只剩20%电量?有了这几招,多用2小时

如今越来越多的小伙伴在旅途中和上班路上 免不了要用手机打发时间 看直播、打游戏、听音乐 有了手机&#xff0c;仿佛就有了全世界 可是&#xff0c;手机的电不够用怎么办&#xff1f; 不怕&#xff01; 今天小编为您送上 最强省电攻略和充电指南&#xff01; 省电攻略 iphone篇…

网络知识:电脑无线网连接不上问题汇总

在使用电脑的时候&#xff0c;有时候电脑可能连接不上无线网络。那么电脑无线网络连接不上怎么办呢?下面就让小编来告诉大家吧&#xff0c;欢迎阅读。 第一步&#xff1a;应检查无线网卡的驱动是否安装正确。 右键点击“我的电脑”-属性-硬件-设备管理器&#xff0c;查看是否存…