首先我们应该用对其分包,如下图
首先,我们先创建一个Contact实体类
package cn.qblank.entity;
public class Contact {
private String id;
private String name;
private int age;
private String gender;
private String qq;
private String phone;
private String address;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Contact(String id, String name, int age, String gender, String qq,
String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
this.qq = qq;
this.address = address;
}
public Contact() {
super();
}
@Override
public String toString() {
return "Contact [id=" + id + ", name=" + name + ", age=" + age
+ ", gender=" + gender + ", qq=" + qq + ", address=" + address
+ "]";
}
}
然后建立一个contact.xml在F盘
写一个XMLUtil类对xml的优化xml的读取和修改
package cn.qblank.utl;
import java.io.File;
import java.io.FileOutputStream;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class XMLUtil {
/**
* 获取结点
* @return
* @throws Exception
*/
public static Document getDocuement() throws Exception{
return new SAXReader().read(new File("F:/contact.xml"));
}
/**
* 写入文档
*/
public static void writeXml(Document doc){
try {
FileOutputStream out = new FileOutputStream("F:/contact.xml");
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("utf-8");
XMLWriter writer = new XMLWriter(out,format);
writer.write(doc);
writer.close();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
下面开始写dao层的代码
先实现一个查询所有联系人的功能
@Override
public List<Contact> listAllContact() throws Exception {
Document doc = XMLUtil.getDocuement();
List<Contact> list = new ArrayList<>();
@SuppressWarnings("unchecked")
List<Element> contactList= (List<Element>)doc.selectNodes("//contact");
for (Element elem : contactList) {
Contact contact = new Contact();
contact.setId(elem.attributeValue("id"));
contact.setName(elem.elementText("name"));
contact.setAge(Integer.parseInt(elem.elementText("age")));
contact.setGender(elem.elementText("gender"));
contact.setQq(elem.elementText("qq"));
contact.setPhone(elem.elementText("phone"));
contact.setAddress(elem.elementText("address"));
list.add(contact);
}
return list;
}
对应的Servlet(接收数据)代码和Jsp(显示界面)代码如下
public class AddContactServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("utf-8");
//获取参数
String name = req.getParameter("c_name");
int age = Integer.parseInt(req.getParameter("c_age"));
String gender = req.getParameter("c_gender");
String qq = req.getParameter("c_qq");
String phone = req.getParameter("c_phone");
String address = req.getParameter("c_address");
Contact contact = new Contact();
contact.setName(name);
contact.setAge(age);
contact.setGender(gender);
contact.setQq(qq);
contact.setPhone(phone);
contact.setAddress(address);
ContactDaoImpl contactDaoImpl = new ContactDaoImpl();
contactDaoImpl.addContact(contact);
resp.sendRedirect(req.getContextPath() + "/ListContactServlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
JSP代码如下:
<%@ page language="java"
import="java.util.*,cn.qblank.entity.*"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>联系人列表</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<style>
body{
text-align:center;
}
table{
width:1000px;
text-align:center;
margin: 0 auto;
}
</style>
<body>
<h1>查询所有联系人</h1>
<table border="1" cellspacing="0">
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
<th>qq</th>
<th>phone</th>
<th>address</th>
<th colspan="2">操作</th>
</tr>
<!-- 接收到ListContactServlet发过来的信息 -->
<c:forEach items="${contacts}" var="contact">
<c:if test="${!empty contact}">
<tr>
<td>${contact.id}</td>
<td>${contact.name }</td>
<td>${contact.age }</td>
<td>${contact.gender}</td>
<td>${contact.qq}</td>
<td>${contact.phone}</td>
<td>${contact.address}</td>
<td><a href="/ContactProject/QueryContactServlet?id=${contact.id}">修改</a></td>
<td><a href="/ContactProject/DeleteContactServlet?id= ${contact.id}">删除</a></td>
</tr>
</c:if>
</c:forEach>
<tr>
<td colspan="9" align="center"><a href="add_contact.html">[添加联系人]</a></td>
</tr>
</table>
</body>
</html>
然后再实现一个增加联系人的功能,我们使用UUID的randomUUID方法产生唯一id
public void addContact(Contact contact) {
File file = new File("F://contact.xml");
Document doc = null;
Element rootElem = null;
try {
if (!file.exists()) {
doc = DocumentHelper.createDocument();
rootElem = doc.addElement("contactList");
}else{
doc = XMLUtil.getDocuement();
rootElem = doc.getRootElement();
}
//添加联系人
Element contactElem = rootElem.addElement("contact");
/**
* UUid
*/
String uuid = UUID.randomUUID().toString().replace("-", "");
contactElem.addAttribute("id", uuid);
contactElem.addElement("name").setText(contact.getName());
contactElem.addElement("age").setText(contact.getAge()+"");
contactElem.addElement("gender").setText(contact.getGender());
contactElem.addElement("qq").setText(contact.getQq());
contactElem.addElement("phone").setText(contact.getPhone());
contactElem.addElement("address").setText(contact.getAddress());
//写入文档
XMLUtil.writeXml(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
然后写一个add_contact.html页面,显示添加联系人的界面
<style>
table{
margin:0 auto;
}
table tr td{
margin-left:20px;
}
h1{
text-align:center;
}
</style>
<body>
<h1>添加联系人</h1>
<form action="/ContactProject/AddContactServlet" method="post">
<table border="1">
<tr>
<td>姓名</td>
<td><input type="text" name="c_name"/></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="c_age"/></td>
</tr>
<tr>
<td>性别</td>
<td>
男<input type="radio" name="c_gender"/>
女<input type="radio" name="c_gender"/>
</td>
</tr>
<tr>
<td>qq</td>
<td><input type="text" name="c_qq"/></td>
</tr>
<tr>
<td>电话</td>
<td><input type="text" name="c_phone"/></td>
</tr>
<tr>
<td>地址</td>
<td><input type="text" name="c_address"/></td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="保存"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
</body>
然后对应的写一个Servlet用于接收用户输入的信息,并调用dao层的添加方法,将其输入的信息导入xml中
public class AddContactServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("utf-8");
//获取参数
String name = req.getParameter("c_name");
int age = Integer.parseInt(req.getParameter("c_age"));
String gender = req.getParameter("c_gender");
String qq = req.getParameter("c_qq");
String phone = req.getParameter("c_phone");
String address = req.getParameter("c_address");
Contact contact = new Contact();
contact.setName(name);
contact.setAge(age);
contact.setGender(gender);
contact.setQq(qq);
contact.setPhone(phone);
contact.setAddress(address);
ContactDaoImpl contactDaoImpl = new ContactDaoImpl();
contactDaoImpl.addContact(contact);
resp.sendRedirect(req.getContextPath() + "/ListContactServlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
下面是删除功能,删除功能最重要的一点是获取id,那么怎么才能获取到id呢,我们可以在主界面contact_list.jsp的删除链接跳转时将id这个参数传入过去,如上contact_list.jsp
<td><a href="/ContactProject/DeleteContactServlet?id= <%=contact.getId().trim() %>">删除</a></td>
然后对应的Servlet接收这个id
public class DeleteContactServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ContactDaoImpl contactDaoImpl = new ContactDaoImpl();
String id = req.getParameter("id");
contactDaoImpl.deleteContact(id);
resp.sendRedirect(req.getContextPath() + "/ListContactServlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
然后在dao层,将对应的联系人删除
@Override
public void deleteContact(String id) {
Document doc = null;
try {
doc = XMLUtil.getDocuement();
Element contactElem = (Element) doc.selectSingleNode("//contact[@id='"+id.trim()+"']");
if (contactElem != null) {
contactElem.detach();
}
XMLUtil.writeXml(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
接下来,就是修改的操作,该操作同样需要拿到id,我们也可以用同样的方式接收id
<td><a href="/ContactProject/QueryContactServlet?id=<%=contact.getId()%>">修改</a></td>
由于原本的数据不能变,所以我们需要将原本的数据先查出来,然后才能继续进行修改
@Override
public Contact findById(String id) {
Document doc = null;
Contact c = null;
try {
doc = XMLUtil.getDocuement();
Element contactElem = (Element)doc.selectSingleNode("//contact[@id='"+id+"']");
if (contactElem != null) {
c = new Contact();
c.setId(contactElem.attributeValue("id"));
c.setName(contactElem.elementText("name"));
c.setAge(Integer.parseInt(contactElem.elementText("age")));
c.setGender(contactElem.elementText("gender"));
c.setQq(contactElem.elementText("qq"));
c.setPhone(contactElem.elementText("phone"));
c.setAddress(contactElem.elementText("address"));
}
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
然后写一个QueryContactServlet用于接收查到的数据
public class QueryContactServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("utf-8");
String id = req.getParameter("id").trim();
//通过id查询到联系人
ContactDaoImpl contactDaoImpl = new ContactDaoImpl();
Contact contact = contactDaoImpl.findById(id);
req.setAttribute("contact", contact);
req.getRequestDispatcher("update_contact.jsp").forward(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
接下来就是用update_contact.jsp,显示原来的数据
<style>
table{
margin:0 auto;
}
table tr td{
margin-left:20px;
}
h1{
text-align:center;
}
</style>
<body>
<h1>修改联系人</h1>
<form action="/ContactProject/UpdateContactServlet" method="post">
<%
Contact contact = (Contact)request.getAttribute("contact");
%>
<input type="hidden" name="id" value="${contact.id}">
<table border="1">
<tr>
<td>姓名</td>
<td><input type="text" name="c_name" value="${contact.name}"/></td>
</tr>
<tr>
<td>年龄</td>
<td><input type="text" name="c_age" value="${contact.age}"/></td>
</tr>
<tr>
<td>性别</td>
<td>
男<input type="radio" name="c_gender" value="男" <c:if test="${contact.gender == '男'}">checked</c:if> />
女<input type="radio" name="c_gender" value="女" <c:if test="${contact.gender == '女'}">checked</c:if> />
</td>
</tr>
<tr>
<td>qq</td>
<td><input type="text" name="c_qq" value="${contact.qq}"/></td>
</tr>
<tr>
<td>电话</td>
<td><input type="text" name="c_phone" value="${contact.phone}"/></td>
</tr>
<tr>
<td>地址</td>
<td><input type="text" name="c_address" value="${contact.address}"/></td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<input type="submit" value="保存"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
</body>
接下来根据 用户修改的数据进行修改,方法和添加类似
public class UpdateContactServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
resp.setCharacterEncoding("utf-8");
//获取参数
String id = req.getParameter("id");
String name = req.getParameter("c_name");
int age = Integer.parseInt(req.getParameter("c_age"));
String gender = req.getParameter("c_gender");
String qq = req.getParameter("c_qq");
String phone = req.getParameter("c_phone");
String address = req.getParameter("c_address");
Contact contact = new Contact();
contact.setId(id);
contact.setName(name);
contact.setAge(age);
contact.setGender(gender);
contact.setQq(qq);
contact.setPhone(phone);
contact.setAddress(address);
ContactDaoImpl contactDaoImpl = new ContactDaoImpl();
contactDaoImpl.updateContact(contact);
//3.跳转到查询联系人的页面
resp.sendRedirect(req.getContextPath()+"/ListContactServlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
对应的dao层修改数据
@Override
public void updateContact(Contact contact) {
Document doc = null;
try {
doc = XMLUtil.getDocuement();
Element contactElem = (Element) doc.selectSingleNode("//contact[@id='"+contact.getId()+"']");
contactElem.element("name").setText(contact.getName());
contactElem.element("age").setText(contact.getAge()+"");
contactElem.element("gender").setText(contact.getGender());
contactElem.element("qq").setText(contact.getQq());
contactElem.element("phone").setText(contact.getPhone());
contactElem.element("address").setText(contact.getAddress());
//写入文档
XMLUtil.writeXml(doc);
} catch (Exception e) {
e.printStackTrace();
}
}
这样,我们利用xml实现增删改查的功能就实现了,总结一点
在这个我们用到了Servlet,JSP,XMl技术,EL表达式
Servlet:用于接收数据,并处理逻辑
JSP : 用于显示界面,和用户进行交互,在jsp中尽量少写java代码
XML : 用于存储数据,实现持久化数据,类似于数据库。