目录
要求实现的功能:
在网页上实现联系人程序对联系人的增删改查
1)添加联系人
2)修改联系人
3)删除联系人
4)查询联系人
5)根据编号查询联系人
一、前提准备
1)创建目录
|-src
com.csdn.web :存放servlet类
com.csdn.service :存放业务逻辑接口
com.csdn.service.impl :存放业务逻辑的实现类
com.csdn.dao :存放dao的接口
com.csdn.dao.impl :存放dao的实现类
com.csdn.util :存放工具类
com.csdn.pojo :存放实体类对象
com.csdn.test :测试
|-web
WEB-INF
jsp:存放js资源
lib:将所需的包导入
2)数据库创建
CREATE DATABASE contact_sys;
USE contact_sys;
CREATE TABLE contact(
cid INT(11) NOT NULL AUTO_INCREMENT,
NAME VARCHAR(255) DEFAULT NULL,
gender VARCHAR(4) DEFAULT NULL,
age INT(11),
phone VARCHAR(11) ,
email VARCHAR(255) ,
qq VARCHAR(255),
PRIMARY KEY (cid)
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
INSERT INTO contact VALUES(1,'张三','男',22,13333333333,'zhangsan@qq.com','1.jpg');
INSERT INTO contact VALUES(2,'李四','男',23,15555555555,'lisi@qq.com','2.jpg');
INSERT INTO contact VALUES(3,'王五','男',24,17777777777,'wangwu@qq.com','3.jpg');
3)在idea中连接数据库,导入所需的架包,在util中导入封装好的jdbcUtil类,在WEB-INF/jsp中创建list.jsp,为后续页面做准备。
4)在pojo中创建Contact类,写入对应属性
public class Contact {
private Integer cid;
private String name;
private String gender;
private Integer age;
private String phone;
private String email;
private String qq;
public Integer getCid() {return cid;}
public void setCid(Integer cid) {this.cid = cid;}
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 Integer getAge() {return age;}
public void setAge(Integer age) {this.age = age;}
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 getQq() {return qq;}
public void setQq(String qq) {this.qq = qq;}
@Override
public String toString() {
return "Contact{" +
"cid=" + cid +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
", phone='" + phone + '\'' +
", email='" + email + '\'' +
", qq='" + qq + '\'' +
'}';
}
}
5)在com.csdn.dao中创建接口,取名ContactDao
public interface ContactDao {
public void addContact(Contact contact);//添加联系人
public void updateContact(Contact contact);//修改联系人
public void deleteContact(Integer cid);//删除联系人
public List<Contact> findAll(); //查询所有联系人
public Contact findById(Integer cid);//根据编号查询联系人
}
在com.csdn.dao.impl中创建ContactDaoImpl来编写上面实现类
public class ContactDaoImpl implements ContactDao {
@Override
public void addContact(Contact contact) {
}
@Override
public void updateContact(Contact contact) {
}
@Override
public void deleteContact(Integer cid) {
}
@Override
public List<Contact> findAll() {
return null;
}
@Override
public Contact findById(Integer cid) {
return null;
}
}
6)在com.csdn.service创建接口,取名ContactService,方法与dao中一样
public interface ContactService {
public void addContact(Contact contact);//添加联系人
public void updateContact(Contact contact);//修改联系人
public void deleteContact(Integer cid);//删除联系人
public List<Contact> findAll(); //查询所有联系人
public Contact findById(Integer cid);//根据编号查询联系人
}
在com.csdn.service.impl中创建ContactServiceImpl来编写上面实现类
public class ContactServiceImpl implements ContactService {
@Override
public void addContact(Contact contact) {
}
@Override
public void updateContact(Contact contact) {
}
@Override
public void deleteContact(Integer cid) {
}
@Override
public List<Contact> findAll() {
return null;
}
@Override
public Contact findById(Integer cid) {
return null;
}
}
二、功能实现
1.查询所有联系人
1)在web中创建ContactFindAllServlet类
@WebServlet("/contactFindAllServlet")
public class ContactFindAllServlet extends HttpServlet {
//重写doget,dopost方法
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置字符集
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset = utf-8");
//调用service层方法
ContactService contactService = new ContactServiceImpl();
List<Contact> contactList = contactService.findAll();
//保存自request对象里
req.setAttribute("contactList",contactList);
//跳转页面
req.getRequestDispatcher("WEB-INF/jsp/list.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2)在service层 找到service实现类。
创建ContactDao对象
private ContactDao contactDao = new ContactDaoImpl();
找到对应查询所有的方法进行编写
@Override
public List<Contact> findAll() {
return contactDao.findAll();
}
3)在dao层实现查询所有,在ContactDaoImpl类找到findAll()方法
@Override
public List<Contact> findAll() {
//获取queryRunner对象
QueryRunner queryRunner = JdbcUtil.getQueryRunner();
//准备sql
String sql = "select cid,name,gender,age,phone,email,qq from contact";
try {
//调用方法
List<Contact> contactList = queryRunner.query(sql, new BeanListHandler<Contact>(Contact.class));
//返回数据
return contactList;
} catch (SQLException e) {
e.printStackTrace();
}
throw new RuntimeException("查询所有联系人异常");
}
4)可在Test中创建类进行测试
public class ContactDaoImplTest {
ContactDao contactDao = new ContactDaoImpl();
@Test
public void contactFindAllTest(){
List<Contact> contactList = contactDao.findAll();
System.out.println(contactList);
}
}
出现结果
此时程序正常运行
5)在list.jsp设计页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>查询所有联系人</title>
<style type="text/css">
table td{
/*文字居中*/
text-align:center;
}
/*合并表格的边框*/
table{
border-collapse:collapse;
}
</style>
</head>
<body>
<center><h3>查询所有联系人</h3></center>
<table align="center" border="1" width="900px">
<tr>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>电话</th>
<th>邮箱</th>
<th>QQ</th>
<th>操作</th>
</tr>
<c:forEach varStatus="vs" var="contact" items="${contactList}">
<tr>
<td>${vs.count}</td>
<td>${contact.name}</td>
<td>${contact.gender}</td>
<td>${contact.age}</td>
<td>${contact.phone}</td>
<td>${contact.email}</td>
<td>${contact.qq}</td>
<td><a href="">修改</a> <a href="">删除</a></td>
</tr>
</c:forEach>
<tr>
<td colspan="8" align="center"><a href="添加联系人.html">[添加联系人]</a></td>
</tr>
</table>
</body>
</html>
6)运行后可获得展示的内容,即实现找到所有联系人功能
2.添加联系人
1)点击添加联系人,需要跳转到添加联系人界面,首先需要设计一个添加联系人的界面,在jsp下建立add.jsp。
<html>
<head>
<title>添加联系人</title>
</head>
<body>
<center><h3>添加联系人</h3></center>
<form method="post" enctype="multipart/form-data" action="contactAddServlet">
<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="gender" value="男" checked="checked" />男
<input type="radio" name="gender" 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="file" name="qq"/></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="保存"/>
<input type="reset" value="重置"/></td>
</tr>
</table>
</form>
</body>
</html>
2)由于add.jsp在WEB-INF下面,需要在web层写一个ContactToAddServlet类,来跳转。
@WebServlet("/contactToAddServlet")
public class ContactToAddServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("WEB-INF/jsp/add.jsp").forward(req,resp);
}
}
通过list.jsp跳转,在添加联系人处进行修改
<tr>
<td colspan="8" align="center"><a href="${pageContext.request.contextPath}/contactToAddServlet">[添加联系人]</a></td>
</tr>
3)在web层创建ContactAddText类
@WebServlet("/contactAddServlet")
@MultipartConfig//上传注解支持
public class ContactAddServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置字符集
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//接收参数
String name = req.getParameter("name");
String gender = req.getParameter("gender");
String age = req.getParameter("age");
String phone = req.getParameter("phone");
String email = req.getParameter("email");
//qq为上传表单
//获取上传组件
Part qq = req.getPart("qq");
//设置上传路径
String upLoadPath = "E:\\apache-tomcat\\webapps\\upload";
//创建目录
File file = new File(upLoadPath);
//判断
if (!file.exists()){
file.mkdirs();//连同子目录一起创建
}
//使用UUID保证文件名唯一性
String uploadFileName =
UUID.randomUUID().toString().replace("-","")
+qq.getSubmittedFileName();
//上传
if (qq != null){
qq.write(upLoadPath + uploadFileName);
}
//把数据封装到对象中
Contact contact = new Contact();
contact.setName(name);
contact.setGender(gender);
contact.setAge(Integer.parseInt(age));
contact.setPhone(phone);
contact.setEmail(email);
contact.setQq(uploadFileName);
System.out.println(contact);
//调用service层方法
ContactService contactService = new ContactServiceImpl();
contactService.addContact(contact);
//跳转查询页面
resp.sendRedirect(req.getContextPath() + "/contactFindAllServlet");
}
}
4)在service层的ContactAddService实现类找到addContact方法
@Override
public void addContact(Contact contact) {
contactDao.addContact(contact);
}
5)在dao层实现添加,在ContactDaoImpl类找到addContact()方法
@Override
public void addContact(Contact contact) {
QueryRunner queryRunner = JdbcUtil.getQueryRunner();
String sql = "insert into contact(name,gender,age,phone,email,qq) values(?,?,?,?,?,?)";
try {
queryRunner.update(sql,contact.getName(),contact.getGender(),contact.getAge(),
contact.getPhone(),contact.getEmail(),contact.getQq());
} catch (SQLException e) {
e.printStackTrace();
}
}
此时,已经基本实现方法,可在list.jsp更新完善一下。
6.运行查看
进入添加页面,添加数据
保存成功:
3.修改联系人
1)修改联系人相当于查询单个联系人+添加,首先在web层下创建一个查询单个的Servlet
@WebServlet("contactFindByIdServlet")
public class ContactFindByIdServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置字符集
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset = utf-8");
//接收参数
String cid = req.getParameter("cid");
//调用service层方法
ContactService contactService = new ContactServiceImpl();
Contact contact = contactService.findById(Integer.parseInt(cid));
//保存在域对象
req.setAttribute("contact",contact);
//跳转页面
req.getRequestDispatcher("WEB-INF/jsp/update.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2)在service层找到findById
@Override
public Contact findById(Integer cid) {
return contactDao.findById(cid);
}
}
3)dao层实现查询单个联系人
@Override
public Contact findById(Integer cid) {
QueryRunner queryRunner = JdbcUtil.getQueryRunner();
String sql = "select cid,name,gender,age,phone,email,qq from contact where cid = ?";
try {
Contact contact = queryRunner.query(sql, new BeanHandler<>(Contact.class),cid);
return contact;
} catch (SQLException e) {
e.printStackTrace();
}
throw new RuntimeException("查询单个联系人异常");
}
}
测试后没有问题
4)接下来开始实现修改联系人的操作,在web层下创建ContactFindAllServlet
@WebServlet("/contactUpdateServlet")
@MultipartConfig//上传注解支持
public class ContactUpdateServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置字符集
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset = utf-8");
//接收参数
String cid =req.getParameter("cid");
String name = req.getParameter("name");
String gender = req.getParameter("gender");
String age = req.getParameter("age");
String phone = req.getParameter("phone");
String email = req.getParameter("email");
//获取上传组件
Part part = req.getPart("qq");
//设置上传路径
String uploadPath = "E:\\apache-tomcat\\webapps\\upload";
//创建目录
File file = new File(uploadPath);
//判断
if (!file.exists()){
file.mkdirs();
}
//使用UUID来保证文件名称的唯一性
String uploadFileName =
UUID.randomUUID().toString().replace("-","")
+ part.getSubmittedFileName();
//上传
if (part != null){
part.write(uploadPath + "/" + uploadFileName);
}
//把数据封装到对象中
Contact contact = new Contact();
contact.setCid(Integer.parseInt(cid));
contact.setName(name);
contact.setGender(gender);
contact.setAge(Integer.parseInt(age));
contact.setPhone(phone);
contact.setEmail(email);
contact.setQq(uploadFileName);
System.out.println(contact);
//调用service层方法
ContactService contactService = new ContactServiceImpl();
contactService.updateContact(contact);
//跳转页面
resp.sendRedirect(req.getContextPath()+"/contactFindAllServlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
5)在service层找到updateContact
@Override
public void updateContact(Contact contact) {
contactDao.updateContact(contact);
}
6)dao层实现修改联系人
@Override
public void updateContact(Contact contact) {
QueryRunner queryRunner = JdbcUtil.getQueryRunner();
String sql = "update contact set name = ?,gender = ?,age = ?, phone = ?, email = ?, qq = ? where cid = ?";
try {
queryRunner.update(sql,contact.getName(),contact.getGender(),contact.getAge(),
contact.getPhone() , contact.getEmail(),contact.getQq(),contact.getCid());
} catch (SQLException e) {
e.printStackTrace();
}
}
7)创建jsp,实现修改页面
<html>
<head>
<title>修改联系人</title>
</head>
<body>
<center><h3>修改联系人</h3></center>
<form method="post" enctype="multipart/form-data" action="contactUpdateServlet">
<!-- 把cid作为隐藏域传过去 -->
<input type="hidden" name="cid" value="${contact.cid}">
<table align="center" border="1" width="300px">
<tr>
<th>姓名</th>
<td><input type="text" name="name" value="${contact.name}"/></td>
</tr>
<tr>
<th>性别</th>
<c:if test="${contact.gender == '男'}">
<td>
<input type="radio" name="gender" value="男" checked="checked" />男
<input type="radio" name="gender" value="女"/>女
</td>
</c:if>
<c:if test="${contact.gender == '女'}">
<td>
<input type="radio" name="gender" value="男" />男
<input type="radio" name="gender" value="女" checked="checked" />女
</td>
</c:if>
</tr>
<tr>
<th>年龄</th>
<td><input type="text" name="age" value="${contact.age}"/></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>QQ</th>
<td>
<img src="http://localhost:8081/upload/${contact.qq}" alt="这是图片" width="40" height="40">
<input type="file" name="qq"/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="保存"/>
<input type="reset" value="重置"/></td>
</tr>
</table>
</form>
</body>
</html>
8)点击运行,进入查询所有联系人页面
进行修改
修改完成:
4.删除联系人
1)在web层创建删除联系人ContactDeleteByIdServlet类
@WebServlet("/contactDeleteByIdServlet")
public class ContactDeleteByIdServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String cid = req.getParameter("cid");
ContactService contactService = new ContactServiceImpl();
contactService.deleteContact(Integer.parseInt(cid));
//跳转页面
resp.sendRedirect(req.getContextPath() + "/contactFindAllServlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
2)service层找到deleteContact
@Override
public void deleteContact(Integer cid) {
contactDao.deleteContact(cid);
}
3)dao层实现删除
@Override
public void deleteContact(Integer cid) {
QueryRunner queryRunner = JdbcUtil.getQueryRunner();
String sql = "delete from contact where cid = ?";
try {
queryRunner.update(sql,cid);
} catch (SQLException e) {
e.printStackTrace();
}
}
4)运行,查看删除操作是否完成
删除编号4
操作完成
5.分页查询联系人
1)在com.csdn.bean下创建PageBean类
public class PageBean {
private Integer pageNum;//当前页
private Integer pageSize;//每页显示条数
private Object pageData;//分页数据
private Integer totalPage;//总页数
private Integer totalCount;//总记录数
public Integer getPageNum() {
return pageNum;
}
public void setPageNum(Integer pageNum) {
this.pageNum = pageNum;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Object getPageData() {
return pageData;
}
public void setPageData(Object pageData) {
this.pageData = pageData;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
@Override
public String toString() {
return "PageBean{" +
"pageNum=" + pageNum +
", pageSize=" + pageSize +
", pageData=" + pageData +
", totalPage=" + totalPage +
", totalCount=" + totalCount +
'}';
}
}
2)在web层创建分页ContactFindByPageServlet类
@WebServlet("/contactFindByPageServlet")
public class ContactFindByPageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置字符集
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset = utf-8");
//设置当前页
String pageBum = req.getParameter("pageNum");
if (pageBum == null){
pageBum = "1";
}
//设置每页显示3条数据
Integer pageSize = 3;
//将对用数据封装到PageBean类中
PageBean pageBean = new PageBean();
pageBean.setPageNum(Integer.parseInt(pageBum));//封装pageNum属性
pageBean.setPageSize(pageSize);//封装pageSize属性
//在service层创建findByPage方法
ContactService contactService = new ContactServiceImpl();
pageBean = contactService.findByPage(pageBean);
//放到request域对象中
req.setAttribute("pageBean",pageBean);
//跳转界面
req.getRequestDispatcher("WEB-INF/jsp/list.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
3)service层创建findByPage方法
@Override
public PageBean findByPage(PageBean pageBean) {
return contactDao.findByPage(pageBean);
}
4)dao层实现分页
@Override
public PageBean findByPage(PageBean pageBean) {
QueryRunner queryRunner = JdbcUtil.getQueryRunner();
String sql = "select cid,name,gender,age,phone,email,qq from contact limit ?,?";
try {
List<Contact> contactList = queryRunner.query(sql, new BeanListHandler<Contact>(Contact.class),
(pageBean.getPageNum() - 1) * pageBean.getPageSize(),
pageBean.getPageSize());
//封装pageData属性
pageBean.setPageData(contactList);
//封装totalCount属性
Integer totalCount = getTotalCount();
pageBean.setTotalCount(totalCount);
//封装totalPage属性
Integer totalPage =
pageBean.getTotalCount()%pageBean.getPageSize() == 0 ?
pageBean.getTotalCount()/pageBean.getPageSize():
pageBean.getTotalCount()/pageBean.getPageSize() + 1;
pageBean.setTotalPage(totalPage);
return pageBean;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//查询总记录数
public Integer getTotalCount(){
QueryRunner queryRunner = JdbcUtil.getQueryRunner();
String sql = "select count(cid) from contact";
try {
Long totalCount = (Long)queryRunner.query(sql, new ScalarHandler<>());
return totalCount.intValue();//类型转换
} catch (SQLException e) {
e.printStackTrace();
}
throw new RuntimeException("查询总记录数异常");
}
}
5)修改lisj.jsp,将找到所有改为分页。并将添加,servlet层修改,删除的跳转路径改为分页
<%--<c:forEach items="${contactList}" var="contact" varStatus="vs" >--%>
<c:forEach items="${pageBean.pageData}" var="contact" varStatus="vs">
<tr>
<td colspan="9" align="center">
共${pageBean.totalPage}页 当前${pageBean.pageNum}/${pageBean.totalPage}页
<a href="${pageContext.request.contextPath}/contactFindByPageServlet?pageNum=1">首页</a>
<c:if test="${pageBean.pageNum == 1}">
<a>上一页</a>
</c:if>
<c:if test="${pageBean.pageNum >1}">
<a href="${pageContext.request.contextPath}/contactFindByPageServlet?pageNum=${pageBean.pageNum - 1}">上一页</a>
</c:if>
<c:if test="${pageBean.pageNum < pageBean.totalPage}">
<a href="${pageContext.request.contextPath}/contactFindByPageServlet?pageNum=${pageBean.pageNum + 1}">下一页</a>
</c:if>
<c:if test="${pageBean.pageNum == pageBean.totalPage}">
<a>下一页</a>
</c:if>
<a href="${pageContext.request.contextPath}/contactFindByPageServlet?pageNum=${pageBean.totalPage}">末页</a>
</td>
</tr>
5)查看
多加几组数据
6. 判断手机号是否重复
1)在添加联系人页面个添加焦点事件
<th>电话</th>
<td><input type="text" name="phone" id="phone" onfocus="showPhone()" onblur="checkPhone()"/>
<span id=phoneSpan></span>
</td>
<script type="application/javascript">
//获取焦点事件
function showPhone() {
var phoneSpanValue = document.getElementById("phoneSpan");
phoneSpanValue.innerHTML = "手机长度为11位".fontcolor("red");
}
//失去焦点事件
function checkPhone() {
var phoneNodeValue = document.getElementById("phone").value;
var phoneSpanNode = document.getElementById("phoneSpan");
$.get("checkContactPhoneServlet", { phone: phoneNodeValue},
function(backdata){
if("repeat" == backdata){
phoneSpanNode.innerHTML = "该手机号已被注册".fontcolor("red");
}else{
phoneSpanNode.innerHTML = "该手机号可用".fontcolor("green");
}
});
}
</script>
2)web层创建CheckContactPhoneServlet类
@WebServlet("/checkContactPhoneServlet")
public class CheckContactPhoneServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置字符集
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取数据
String phone = req.getParameter("phone");
//调用servlet方法
ContactServiceImpl contactService = new ContactServiceImpl();
//true为重复
boolean bo =contactService.checkContactPhone(phone);
//判断
if (bo){
resp.getWriter().write("repeat");
}else {
resp.getWriter().write("norepeat");
}
}
}
3)在service层ContactServiceImpl类创建从checkContactPhone方法
@Override
public boolean checkContactPhone(String phone) {
Contact contact = contactDao.checkContactPhone(phone);
if (contact != null){
return true;
}else {
return false;
}
}
4)dao层实现方法
@Override
public Contact checkContactPhone(String phone) {
QueryRunner queryRunner = JdbcUtil.getQueryRunner();
String sql ="select cid,name,gender,age,phone,email,qq from contact where phone = ?";
try {
Contact db_contact = queryRunner.query(sql,new BeanHandler<>(Contact.class),phone);
return db_contact;
} catch (SQLException e) {
e.printStackTrace();
}
throw new RuntimeException("查询电话重复异常");
}
5)在service中抛出异常,找到add方法进行修改
@Override
public void addContact(Contact contact) throws CheckContactPhoneException{
//在Dao添加之前进行判断
boolean bo = checkContactPhone(contact.getPhone());
//抛出异常
if (bo) {
throw new CheckContactPhoneException("手机号重复,不可用!!!");
}
contactDao.addContact(contact);
}
此时servlet层会出现异常,捕捉。
//调用service层方法
ContactService contactService = new ContactServiceImpl();
try {
contactService.addContact(contact);
} catch (CheckContactPhoneException e) {
//e.printStackTrace();//把异常信息大隐刀控制台上
req.setAttribute("msg",e.getMessage());
req.getRequestDispatcher("WEB-INF/jsp/add.jsp").forward(req,resp);
}
6)此时,实现可判断手机号是否重复
当手机号重复,则跳转至添加页面,无法添加联系人。
手机号不重复则可添加
7.批量删除联系人
1)web层创建ContactDeleteAllServlet类
@WebServlet("/contactDeleteAllServlet")
public class ContactDeleteAllServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置字符集
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取cids,由于是多选框这里使用getParameterValues方法
String[] cids = req.getParameterValues("cids");
//创建service对象
ContactService contactService = new ContactServiceImpl();
contactService.deleteAll(cids);
//跳转页面
resp.sendRedirect(req.getContextPath()+"/contactFindByPageServlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
2)service层实现接口重写deleteAll()方法
@Override
public void deleteAll(String[] cids) {
contactDao.deleteAll(cids);
}
3)dao层实现方法
@Override
public void deleteAll(String[] cids) {
QueryRunner queryRunner = JdbcUtil.getQueryRunner();
String sql = "delete from contact where cid = ?";
//使用批量删除操作
Object[][] objects = new Object[cids.length][];
//赋值
for (int i = 0; i < objects.length; i++) {
objects[i] = new Object[]{cids[i]};
}
try {
queryRunner.batch(sql,objects);//批量删除
} catch (SQLException e) {
e.printStackTrace();
}
}
list.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>查询所有联系人</title>
<style type="text/css">
table td{
/*文字居中*/
text-align:center;
}
/*合并表格的边框*/
table{
border-collapse:collapse;
}
</style>
</head>
<body>
<center><h3>查询所有联系人</h3></center>
<form action="contactDeleteAllServlet">
<table align="center" border="1" width="900px">
<tr>
<th><input type="checkbox" id="all" onclick="selectAll()">全选/反选</th>
<th>编号</th>
<th>姓名</th>
<th>性别</th>
<th>年龄</th>
<th>电话</th>
<th>邮箱</th>
<th>QQ</th>
<th>操作</th>
</tr>
<%--<c:forEach items="${contactList}" var="contact" varStatus="vs" >--%>
<c:forEach items="${pageBean.pageData}" var="contact" varStatus="vs">
<tr>
<td><input type="checkbox" class="item" name="cids" value="${contact.cid}"></td>
<td>${vs.count}</td>
<td>${contact.name}</td>
<td>${contact.gender}</td>
<td>${contact.age}</td>
<td>${contact.phone}</td>
<td>${contact.email}</td>
<td><img src="http://localhost:8083/upload/${contact.qq}" alt="这是图片" width="40p" height="40"></td>
<td><a href="${pageContext.request.contextPath}/contactFindByIdServlet?cid=${contact.cid}">修改</a>
<a href="${pageContext.request.contextPath}/contactDeleteByIdServlet?cid=${contact.cid}">删除</a></td>
</tr>
</c:forEach>
<tr>
<td colspan="9" align="center"><a href="${pageContext.request.contextPath}/contactToAddServlet">[添加联系人]</a></td>
</tr>
<tr>
<td colspan="9" align="center">
<input type="submit" value="批量删除">
</td>
</tr>
<tr>
<td colspan="9" align="center">
共${pageBean.totalPage}页 当前${pageBean.pageNum}/${pageBean.totalPage}页
<a href="${pageContext.request.contextPath}/contactFindByPageServlet?pageNum=1">首页</a>
<c:if test="${pageBean.pageNum == 1}">
<a>上一页</a>
</c:if>
<c:if test="${pageBean.pageNum >1}">
<a href="${pageContext.request.contextPath}/contactFindByPageServlet?pageNum=${pageBean.pageNum - 1}">上一页</a>
</c:if>
<c:if test="${pageBean.pageNum < pageBean.totalPage}">
<a href="${pageContext.request.contextPath}/contactFindByPageServlet?pageNum=${pageBean.pageNum + 1}">下一页</a>
</c:if>
<c:if test="${pageBean.pageNum == pageBean.totalPage}">
<a>下一页</a>
</c:if>
<a href="${pageContext.request.contextPath}/contactFindByPageServlet?pageNum=${pageBean.totalPage}">末页</a>
</td>
</tr>
</table>
</form>
</body>
<script type="application/javascript">
function selectAll() {
//获取全选框的节点对像
var allNode = document.getElementById("all");
//获取当前页面的其他节点对象
var itemNodes = document.getElementsByClassName("item");
//遍历且赋值得到过程
for (var i=0; i<itemNodes.length; i++){
itemNodes[i].checked = allNode.checked;
}
}
</script>
</html>
4)实现测试i
选中当前页面的编号1,2,点击批量删除
第三页联系人被全部删除