Java高级交流

通讯录案例

2018-05-07  本文已影响1人  Java小生

其实上面就是我们日常生活中常见通讯录的简缩版,主要功能就是实现增、删、改查。首先,我们要了解实现它的大体步骤:从底层往上层开发。即,从数据库到实体对象再到Dao类再到Servlet类最后到用户。然后具体来实现它,先整体了解一下它在开发工具中的目录结构如下图:                             

1.开发数据库

这里是用Mysql数据库,具体代码如下:

-- 创建通讯录数据库
CREATE DATABASE contacts;
USE contacts;
-- 联系人表
CREATE TABLE contact_list(
 id VARCHAR(50) PRIMARY KEY,
 NAME VARCHAR(20),
 gender VARCHAR(2),
 phone VARCHAR(11),
 email VARCHAR(20),
 address VARCHAR(50)
)
SELECT * FROM contact_list;

 结果如下图:

2.实体对象(Contact)

package anli.contacts.entity;
/**
* 联系人对象  编号   姓名   性别   电话   邮箱   地址
*
*/

public class Contact {
 private String id;
 private String name;
 private String gender;
 private String phone;
 private String email;
 private String address;
 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 String getGender() {
   return gender;
 }
 public void setGender(String gender) {
   this.gender = gender;
 }
 public String getPhone() {
   return phone;
 }
 public void setPhone(String phone) {
   this.phone = phone;
 }
 public String getEmail() {
   return email;
 }
 public void setEmail(String email) {
   this.email = email;
 }
 public String getAddress() {
   return address;
 }
 public void setAddress(String address) {
   this.address = address;
 }
 @Override
 public String toString() {
   return "Contact [address=" + address + ", email=" + email + ", gender="
       + gender + ", id=" + id + ", name=" + name + ", phone=" + phone
       + "]";
 }
}

3.Dao

3.1 ContactDao

package anli.contacts.dao;
import java.util.List;
import anli.contacts.entity.Contact;
/**
* 联系的dao接口
*
*/

public interface ContactDao {
 public void addContact(Contact contact);
 public void updateContact(Contact contact);  //包含修改的id
 public void deleteContact(String id);
 public List<Contact> findAll();
 public Contact findById(String id)//根据id查询对应的联系人
 //检查姓名是否重复
 public boolean checkNameExist(String name)
}

3.2 ContactDaoImpl

package anli.contacts.dao.impl;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import org.dom4j.Document;
import org.dom4j.Element;

import anli.contacts.dao.ContactDao;
import anli.contacts.entity.Contact;
import anli.contacts.util.XMLUtil;
/**
* dao实现类
*
*/

public class ContactDaoImpl implements ContactDao {

 public void addContact(Contact contact) {
   try {
     //把联系人信息保存到xml文件中去
     //1)读取原来的xml文件,返回document对象
     Document doc = XMLUtil.getDocument();
     //2)修改document对象
     Element rootElem = doc.getRootElement();
     //添加标签
     Element conElem = rootElem.addElement("contact");
     //添加属性
     //编号使用UUID算法生成一个随机且唯一的字符串
     conElem.addAttribute("id", UUID.randomUUID().toString());
     //添加子标签
     conElem.addElement("name").setText(contact.getName());
     conElem.addElement("gender").setText(contact.getGender());
     conElem.addElement("phone").setText(contact.getPhone());
     conElem.addElement("email").setText(contact.getEmail());
     conElem.addElement("address").setText(contact.getAddress());
     //3)把修改后的document对象写出到原来的xml文件中(覆盖原来的xml)
     XMLUtil.write2xml(doc);
   } catch (Exception e) {
     e.printStackTrace();
     throw new RuntimeException(e);
   }
 }

 /**
  * 删除联系人
  */

 public void deleteContact(String id) {
   //1)读取原来的xml
   Document doc = XMLUtil.getDocument();
   
   //2)删除contact标签
   //2.1 根据id查询对应的contact标签
   Element conElem = (Element)doc.selectSingleNode("//contact[@id='"+id+"']");
   
   if(conElem!=null){
     //2.2删除
     conElem.detach();
   }
   
   //3)把修改的document写出到xml文件
   XMLUtil.write2xml(doc);
 }

 public List<Contact> findAll() {
   //1)读取xml文件
   Document doc = XMLUtil.getDocument();
   
   //2)获取所有的contact标签
   List<Element> conList = (List<Element>)doc.getRootElement().elements("contact");
   
   List<Contact> list = new ArrayList<Contact>();
   for (Element conElem : conList) {
     //2.1 创建Contact对象
     Contact contact = new Contact();
     //2.2 把contact标签信息封装到COntact对象中
     contact.setId(conElem.attributeValue("id"));
     contact.setName(conElem.elementText("name"));
     contact.setGender(conElem.elementText("gender"));
     contact.setPhone(conElem.elementText("phone"));
     contact.setEmail(conElem.elementText("email"));
     contact.setAddress(conElem.elementText("address"));
     //2.3 把Contact对象放入List
     list.add(contact);
   }
   return list;
 }

 /**
  * 根据id查询对应的联系人
  */

 public Contact findById(String id) {
   //1)读取xml文件
   Document doc = XMLUtil.getDocument();
   //2)查询对应的contact标签
   Element conElem = (Element)doc.selectSingleNode("//contact[@id='"+id+"']");
   Contact contact = null;
   if(conElem!=null){
     //创建COntact对象
     contact = new Contact();
     //把contact标签内容封装到Contact对象中
     contact.setId(conElem.attributeValue("id"));
     contact.setName(conElem.elementText("name"));
     contact.setGender(conElem.elementText("gender"));
     contact.setPhone(conElem.elementText("phone"));
     contact.setEmail(conElem.elementText("email"));
     contact.setAddress(conElem.elementText("address"));
   }
   return contact;
 }

 public void updateContact(Contact contact) {
   try {
     //1)读取原理的xml文件
     Document doc = XMLUtil.getDocument();
     //2)修改document对象
     
     //2.1 根据id查询对应的contact标签
     Element conElem = (Element)doc.selectSingleNode("//contact[@id='"+contact.getId()+"']");
      
     //2.2 修改对应的contact标签内容
     conElem.element("name").setText(contact.getName());
     conElem.element("gender").setText(contact.getGender());
     conElem.element("phone").setText(contact.getPhone());
     conElem.element("email").setText(contact.getEmail());
     conElem.element("address").setText(contact.getAddress());
     
     //3)修改的document对象写出xml文件中
     XMLUtil.write2xml(doc);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 
 public boolean checkNameExist(String name) {
   //1)获取xml文件
   Document doc = XMLUtil.getDocument();
   
   //2)查询是否某个文本内容的name标签
   Element nameElem = (Element)doc.selectSingleNode("//name[text()='"+name+"']");
   return nameElem!=null?true:false;
 }

 public static void main(String[] args) {
   ContactDao dao = new ContactDaoImpl();
 }
}

3.3 ContactDaoMySQLImpl

package anli.contacts.dao.impl;
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 anli.contacts.dao.ContactDao;
import anli.contacts.entity.Contact;
import anli.contacts.util.JdbcUtil;
/**
* mysql+jdbc的dao实现
*
*/

public class ContactDaoMySQLImpl implements ContactDao {

 public void addContact(Contact contact) {
   Connection conn = null;
   PreparedStatement stmt = null;
   try{
     conn = JdbcUtil.getConnection();
     String sql = "insert into contact_list(id,name,gender,phone,email,address) values(?,?,?,?,?,?)";
      stmt = conn.prepareStatement(sql);
     stmt.setString(1, UUID.randomUUID().toString());
     stmt.setString(2, contact.getName());
     stmt.setString(3, contact.getGender());
     stmt.setString(4, contact.getPhone());
     stmt.setString(5, contact.getEmail());
     stmt.setString(6, contact.getAddress());
     //执行
     stmt.executeUpdate();
   }catch(Exception e){
     e.printStackTrace();
     throw new RuntimeException(e);
   }finally{
     JdbcUtil.close(stmt, conn);  
   }
 }

 public boolean checkNameExist(String name) {
   Connection conn = null;
   PreparedStatement stmt = null;
   ResultSet rs = null;
   try{
     conn = JdbcUtil.getConnection();
     String sql = "select * from contact_list where name=?";
     stmt = conn.prepareStatement(sql);
     stmt.setString(1, name);
     //执行
     rs = stmt.executeQuery();
     
     return rs.next();
   }catch(Exception e){
     e.printStackTrace();
     throw new RuntimeException(e);
   }finally{
     JdbcUtil.close(rs,stmt, conn);  
   }
 }

 public void deleteContact(String id) {
   Connection conn = null;
   PreparedStatement stmt = null;
   try{
     conn = JdbcUtil.getConnection();
     String sql = "delete from contact_list where id=?";
     stmt = conn.prepareStatement(sql);
     stmt.setString(1, id);
     //执行
     stmt.executeUpdate();
   }catch(Exception e){
     e.printStackTrace();
     throw new RuntimeException(e);
   }finally{
     JdbcUtil.close(stmt, conn);  
   }
 }

 public List<Contact> findAll() {
   Connection conn = null;
   PreparedStatement stmt = null;
   ResultSet rs = null;
   try{
     conn = JdbcUtil.getConnection();
     String sql = "select * from contact_list";
     stmt = conn.prepareStatement(sql);
     //执行
     rs = stmt.executeQuery();
     
     List<Contact> list = new ArrayList<Contact>();
     while(rs.next()){
       Contact con = new Contact();
       con.setId(rs.getString("id"));
       con.setName(rs.getString("name"));
       con.setGender(rs.getString("gender"));
       con.setPhone(rs.getString("phone"));
       con.setEmail(rs.getString("email"));
       con.setAddress(rs.getString("address"));
       
       list.add(con);
     }
     return list;
   }catch(Exception e){
     e.printStackTrace();
     throw new RuntimeException(e);
   }finally{
     JdbcUtil.close(rs,stmt, conn);  
   }
 }

 public Contact findById(String id) {
   Connection conn = null;
   PreparedStatement stmt = null;
   ResultSet rs = null;
   try{
     conn = JdbcUtil.getConnection();
     String sql = "select * from contact_list where id=?";
     stmt = conn.prepareStatement(sql);
     stmt.setString(1, id);
     //执行
     rs = stmt.executeQuery();
     
     Contact con = null;
     if(rs.next()){
       con = new Contact();
       con.setId(rs.getString("id"));
       con.setName(rs.getString("name"));
       con.setGender(rs.getString("gender"));
       con.setPhone(rs.getString("phone"));
       con.setEmail(rs.getString("email"));
       con.setAddress(rs.getString("address"));
     }
     return con;
   }catch(Exception e){
     e.printStackTrace();
     throw new RuntimeException(e);
   }finally{
     JdbcUtil.close(rs,stmt, conn);  
   }
 }

 public void updateContact(Contact contact) {
   Connection conn = null;
   PreparedStatement stmt = null;
   try{
     conn = JdbcUtil.getConnection();
     String sql = "update contact_list set name=?,gender=?,phone=?,email=?,address=? where id=?";
      stmt = conn.prepareStatement(sql);
     stmt.setString(1, contact.getName());
     stmt.setString(2, contact.getGender());
     stmt.setString(3, contact.getPhone());
     stmt.setString(4, contact.getEmail());
     stmt.setString(5, contact.getAddress());
     stmt.setString(6, contact.getId());
     //执行
     stmt.executeUpdate();
   }catch(Exception e){
     e.printStackTrace();
     throw new RuntimeException(e);
   }finally{
     JdbcUtil.close(stmt, conn);  
   }

 }

}

4.service类

4.1 ContactService

package anli.contacts.service;
import java.util.List;
import anli.contacts.entity.Contact;
import anli.contacts.exception.NameExistException;
/**
* 联系人的service接口
@author APPle
*
*/

public interface ContactService {
 public void addContact(Contact contact)throws NameExistException;
 public void updateContact(Contact contact);  //包含修改的id
 public void deleteContact(String id);
 public List<Contact> findAll();
 public Contact findById(String id)//根据id查询对应的联系人
}

4.2 ContactServiceImpl

package anli.contacts.service.impl;
import java.util.List;
import anli.contacts.dao.ContactDao;
import anli.contacts.dao.impl.ContactDaoMySQLImpl;
import anli.contacts.entity.Contact;
import anli.contacts.exception.NameExistException;
import anli.contacts.service.ContactService;
/**
* 联系人的service实现类
*
*/

public class ContactServiceImpl implements ContactService {
 //创建dao对象
 //ContactDao conDao = new ContactDaoImpl();
 ContactDao conDao = new ContactDaoMySQLImpl();
 /**
  * 保存联系人
  * @throws NameExistException 
  */

 public void addContact(Contact contact) throws NameExistException {
   //添加业务逻辑: 当姓名出现重复的时候,提示用户不能添加
   //检查用户名是否存在的
   if(conDao.checkNameExist(contact.getName())){
     //重复了,怎么办?  抛出自定义异常
     throw new NameExistException("姓名重复,请重复输入");
   }
   conDao.addContact(contact);
 }
 public void deleteContact(String id) {
   conDao.deleteContact(id);
 }
 /**
  * 查询所有联系人
  */

 public List<Contact> findAll() {
   //如果有业务逻辑,把业务逻辑写在这里
   List<Contact> list = conDao.findAll();
   return list;
 }

 public Contact findById(String id) {
   return conDao.findById(id);
 }

 public void updateContact(Contact contact) {
   //可以在以后补充业务逻辑
   conDao.updateContact(contact);
 }
}

5. util

5.1 JdbcUtil

package anli.contacts.util;
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;
/**
* jdbc工具类
*
*/

public class JdbcUtil {
 private static String url = null;
 private static String user = null;
 private static String password = null;
 private static String driverClass = null;
 
 static{
   try {
     //读取jdbc.properties文件
     Properties prop = new Properties();
     //使用类路径方式读取配置文件
     InputStream in = JdbcUtil.class.getResourceAsStream("/jdbc.properties"); 
     //加载文件
     prop.load(in);
     //读取配置文件的内容
     url = prop.getProperty("url");
     user = prop.getProperty("user");
     password = prop.getProperty("password");
     driverClass = prop.getProperty("driverClass");
     
     //注册驱动程序
     Class.forName(driverClass);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 
 
 /**
  * 获取连接方法
  */

 public static Connection getConnection(){
   try {
     Connection conn = DriverManager.getConnection(url, user, password);
     return conn;
   } catch (SQLException e) {
     e.printStackTrace();
     throw new RuntimeException(e);
   }
 }
 
 /**
  * 释放资源方法
  */

 public static void close(ResultSet rs,Statement stmt,Connection conn){
   if(rs!=null){
     try {
       rs.close();
     } catch (SQLException e) {
       e.printStackTrace();
       throw new RuntimeException(e);
     }
   }
   if(stmt!=null){
     try {
       stmt.close();
     } catch (SQLException e) {
       e.printStackTrace();
       throw new RuntimeException(e);
     }
   }
   if(conn!=null){
     try {
       conn.close();
     } catch (SQLException e) {
       e.printStackTrace();
       throw new RuntimeException(e);
     }
   }
 }
 
 /**
  * 释放资源方法
  */

 public static void close(Statement stmt,Connection conn){
   if(stmt!=null){
     try {
       stmt.close();
     } catch (SQLException e) {
       e.printStackTrace();
       throw new RuntimeException(e);
     }
   }
   if(conn!=null){
     try {
       conn.close();
     } catch (SQLException e) {
       e.printStackTrace();
       throw new RuntimeException(e);
     }
   }
 }
 
 
}

5.2 WebUtil

package anli.contacts.util;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;

import anli.contacts.entity.Contact;

public class WebUtil {

 public static <T> copyRequestToBean(HttpServletRequest request,Class<T> clazz){
   /**
    * 把request对象中的参数,逐个封装到javabean(Contact)对象中
    */

   //1)得到request的所有参数
   
   try {
     Map map = request.getParameterMap();
     //构造对象
     T t = clazz.newInstance();
     //约定前提: 参数名称和javabean的属性名称保持一致!!!!
     BeanUtils.copyProperties(t, map);
     return t;
   } catch (Exception e1) {
     e1.printStackTrace();
     throw new RuntimeException(e1);
   }
   
 }
}

5.3 XMLUtil

package anli.contacts.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

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文件,返回document对象
  */

 public static Document getDocument(){
   try {
     Document doc = new SAXReader().read(new File("e:/contact.xml"));
     return doc;
   } catch (DocumentException e) {
     e.printStackTrace();
     //把转换为运行时异常抛出即可!
     throw new RuntimeException(e);
   }
 }
 
 /**
  * 传如docuemnt对象,写出到xml文件中
  */

 public static void write2xml(Document doc){
   try {
     OutputStream out = new FileOutputStream("e:/contact.xml");
     OutputFormat format = OutputFormat.createPrettyPrint();
     XMLWriter writer = new XMLWriter(out,format);
     writer.write(doc);
     writer.close();
   } catch (Exception e) {
     e.printStackTrace();
     //把转换为运行时异常抛出即可!
     throw new RuntimeException(e);
   }
 }
}

6.exception

package anli.contacts.exception;
/**
* 自定义异常(姓名是否重复)
*
*/

public class NameExistException extends Exception{

 public NameExistException(String msg){
   super(msg);
 }
}

7.web

7.1 ConAddServlet

package anli.contacts.web;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import anli.contacts.entity.Contact;
import anli.contacts.exception.NameExistException;
import anli.contacts.service.ContactService;
import anli.contacts.service.impl.ContactServiceImpl;
import anli.contacts.util.WebUtil;
/**
* 添加联系人的servlet
*
*/

public class ConAddServlet extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   //解决post提交数据的中文乱码
   request.setCharacterEncoding("utf-8");
   
   /*//1)接收表单的数据
   String name = request.getParameter("name");
   String gender = request.getParameter("gender");
   String phone = request.getParameter("phone");
   String email = request.getParameter("email");
   String address = request.getParameter("address");
   
   //把数据封装到Contact对象
   Contact contact = new Contact();
   contact.setName(name);
   contact.setGender(gender);
   contact.setEmail(email);
   contact.setPhone(phone);
   contact.setAddress(address);*/

   
   /**
    * 把request对象中的参数,逐个封装到javabean(Contact)对象中
    */

   //1)得到request的所有参数
   /**
    * <key,value>
    *     <参数名称,String[]> 
    */

   Contact contact = WebUtil.copyRequestToBean(request,Contact.class);
   
   //2)把数据保存到xml中
   ContactService service = new ContactServiceImpl();
   try {
     service.addContact(contact);
   } catch (NameExistException e) { //姓名重复了,才会出现这个异常
     //e.printStackTrace();
     //处理这个自定义异常
     request.setAttribute("msg", e.getMessage() );
     //转到addCon.jsp
     request.getRequestDispatcher("/addCon.jsp").forward(request, response);
     return;
   }
   
   //3)跳转到查询联系人页面
   //重定向
   response.sendRedirect(request.getContextPath()+"/ConListServlet");
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   doGet(request, response);
 }

}

7.2 ConBatchDelServlet

package anli.contacts.web;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import anli.contacts.service.ContactService;
import anli.contacts.service.impl.ContactServiceImpl;
/**
* 批量删除的servlet
*
*/

public class ConBatchDelServlet extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   //1)得到需要删除的联系人
   String[] ids = request.getParameterValues("item");
   
   ContactService service = new ContactServiceImpl();
   //2)批量删除
   for(String id:ids){
     service.deleteContact(id);
   }
   
   //3)跳转列表页面
   response.sendRedirect(request.getContextPath()+"/ConListServlet");
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   doGet(request, response);
 }

}

7.3 ConDelServlet

package anli.contacts.web;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import anli.contacts.service.ContactService;
import anli.contacts.service.impl.ContactServiceImpl;
/**
* 删除联系人的servlet
*
*/

public class ConDelServlet extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   //1)接收需要删除的id
   String id = request.getParameter("id");
   
   //2)在xml文件中删除联系人
   ContactService service = new ContactServiceImpl();
   service.deleteContact(id);
   
   //3)跳转到查询联系人页面
   //重定向
   response.sendRedirect(request.getContextPath()+"/ConListServlet");
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   doGet(request, response);
 }

}

7.4 ConListServlet

package anli.contacts.web;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import anli.contacts.entity.Contact;
import anli.contacts.service.ContactService;
import anli.contacts.service.impl.ContactServiceImpl;
/**
* 查询联系人的servlet
*
*/

public class ConListServlet extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   //1)读取所有联系人数据
   ContactService service = new ContactServiceImpl();
   List<Contact> conList = service.findAll();
   
   //2)把数据放入域对象中
   request.setAttribute("conList", conList);
   
   //3)转发到jsp页面中
   request.getRequestDispatcher("/listCon.jsp").forward(request, response);
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   doGet(request, response);
 }

}

7.5 ConQueryServlet

package anli.contacts.web;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import anli.contacts.entity.Contact;
import anli.contacts.service.ContactService;
import anli.contacts.service.impl.ContactServiceImpl;
/**
* 查询联系人的servlet
*
*/

public class ConQueryServlet extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   //1)接收需要修改的id
   String id = request.getParameter("id");
   
   //2)查询对应的联系人
   ContactService service = new ContactServiceImpl();
   Contact contact = service.findById(id);
   
   //3)把数据转发到jsp页面
   request.setAttribute("contact", contact);
   request.getRequestDispatcher("/editCon.jsp").forward(request, response);
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   doGet(request, response);
 }

}

7.6 ConUpdateServlet

package anli.contacts.web;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import anli.contacts.entity.Contact;
import anli.contacts.service.ContactService;
import anli.contacts.service.impl.ContactServiceImpl;
import anli.contacts.util.WebUtil;
/**
* 修改联系人的servlet
*
*/

public class ConUpdateServlet extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   request.setCharacterEncoding("utf-8");
   
   Contact contact = WebUtil.copyRequestToBean(request,Contact.class);
   
   //2)把数据保存到xml
   ContactService service = new ContactServiceImpl();
   service.updateContact(contact);
   
   //3)跳转到查询联系人页面
   response.sendRedirect(request.getContextPath()+"/ConListServlet");
 }

 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException 
{
   doGet(request, response);
 }
}

8. jdbc.properties

#mysql
url=jdbc:mysql://localhost:3306/contacts
user=root
password=root
driverClass=com.mysql.jdbc.Driver

9.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
 xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
>

 <servlet>
   <servlet-name>ConListServlet</servlet-name>
   <servlet-class>anli.contacts.web.ConListServlet</servlet-class>
 </servlet>
 <servlet>
   <servlet-name>ConAddServlet</servlet-name>
   <servlet-class>anli.contacts.web.ConAddServlet</servlet-class>
 </servlet>
 <servlet>
   <servlet-name>ConDelServlet</servlet-name>
   <servlet-class>anli.contacts.web.ConDelServlet</servlet-class>
 </servlet>
 <servlet>
   <servlet-name>ConQueryServlet</servlet-name>
   <servlet-class>anli.contacts.web.ConQueryServlet</servlet-class>
 </servlet>
 <servlet>
   <servlet-name>ConUpdateServlet</servlet-name>
   <servlet-class>anli.contacts.web.ConUpdateServlet</servlet-class>
 </servlet>
 <servlet>
   <servlet-name>ConBatchDelServlet</servlet-name>
   <servlet-class>anli.contacts.web.ConBatchDelServlet</servlet-class>
 </servlet>


 <servlet-mapping>
   <servlet-name>ConListServlet</servlet-name>
   <url-pattern>/ConListServlet</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
   <servlet-name>ConAddServlet</servlet-name>
   <url-pattern>/ConAddServlet</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
   <servlet-name>ConDelServlet</servlet-name>
   <url-pattern>/ConDelServlet</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
   <servlet-name>ConQueryServlet</servlet-name>
   <url-pattern>/ConQueryServlet</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
   <servlet-name>ConUpdateServlet</servlet-name>
   <url-pattern>/ConUpdateServlet</url-pattern>
 </servlet-mapping>
 <servlet-mapping>
   <servlet-name>ConBatchDelServlet</servlet-name>
   <url-pattern>/ConBatchDelServlet</url-pattern>
 </servlet-mapping>
 <welcome-file-list>
   <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

10.jsp页面

10.1 addCon.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<!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="${pageContext.request.contextPath }/ConAddServlet" method="post">
<table border="1" align="center" width="210px">
 <tr>
     <th>姓名</th>
       <td><input type="text" name="name"/><font color="red">${msg }</font></td>
   </tr>
   <tr>
     <th>性别</th>
       <td>
       <input type="radio" name="gender" value="男"/>
       <input type="radio" name="gender" value="女"/>
       </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>地址</th>
       <td><input type="text" name="address"/></td>
   </tr>
   <tr>
     <td colspan="2" align="center"><input type="submit" value="添加"/></td>
   </tr>
</table>
</form>
</body>
</html>

10.2 editCon.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!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="${pageContext.request.contextPath }/ConUpdateServlet" method="post">
<input type="hidden" name="id" value="${contact.id }"/>
<table border="1" align="center" width="210px">
 <tr>
     <th>姓名</th>
       <td><input type="text" name="name" value="${contact.name }" readonly="readonly"/></td>
    </tr>
   <tr>
     <th>性别</th>
       <td>
       <input type="radio" name="gender" value="男"  <c:if test="${contact.gender=='男' }">checked="checked"</c:if>  />男
        <input type="radio" name="gender" value="女"  <c:if test="${contact.gender=='女' }">checked="checked"</c:if> />女
        </td>
   </tr>
   <tr>
     <th>电话</th>
       <td><input type="text" name="phone" value="${contact.phone }"/></td>
   </tr>
   <tr>
     <th>邮箱</th>
       <td><input type="text" name="email" value="${contact.email }"/></td>
   </tr>
   <tr>
     <th>地址</th>
       <td><input type="text" name="address" value="${contact.address }"/></td>
   </tr>
   <tr>
     <td colspan="2" align="center"><input type="submit" value="修改"/></td>
   </tr>
</table>
</form>
</body>
</html>

10.3 listCon.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!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="${pageContext.request.contextPath }/ConUpdateServlet" method="post">
<input type="hidden" name="id" value="${contact.id }"/>
<table border="1" align="center" width="210px">
 <tr>
     <th>姓名</th>
       <td><input type="text" name="name" value="${contact.name }" readonly="readonly"/></td>
    </tr>
   <tr>
     <th>性别</th>
       <td>
       <input type="radio" name="gender" value="男"  <c:if test="${contact.gender=='男' }">checked="checked"</c:if>  />男
        <input type="radio" name="gender" value="女"  <c:if test="${contact.gender=='女' }">checked="checked"</c:if> />女
        </td>
   </tr>
   <tr>
     <th>电话</th>
       <td><input type="text" name="phone" value="${contact.phone }"/></td>
   </tr>
   <tr>
     <th>邮箱</th>
       <td><input type="text" name="email" value="${contact.email }"/></td>
   </tr>
   <tr>
     <th>地址</th>
       <td><input type="text" name="address" value="${contact.address }"/></td>
   </tr>
   <tr>
     <td colspan="2" align="center"><input type="submit" value="修改"/></td>
   </tr>
</table>
</form>
</body>
</html>

以上就是通讯录的所有代码,添加修改完成后所有的数据都保存在了数据库中结果如下:

到这里通讯录的功能基本就算完成

上一篇 下一篇

猜你喜欢

热点阅读