欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

《第一个web项目》实现注册登录增删改查自动跳转

程序员文章站 2022-05-24 18:14:15
...

一、简介

由于刚学servlet,还不会jsp技术,而且html学的也很烂,所以代码可能比较冗余,本项目用到的技术有html,css,servlet,tomcat,druid,oracle,java代码,使用工具MyEclipse2018

二、项目大致的功能关系图

《第一个web项目》实现注册登录增删改查自动跳转

三、登陆层

1.Login.html

介绍:展示给用户操作的登录界面,让用户输入账号密码,当用户点击登陆按钮后,跳转到LoginAction判断账号密码是否输入正确。当用户点击注册按钮后,跳转到regist.html界面

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title>登陆页面</title>
		<style type="text/css">
			img {
				width: 30px;
				height: 30px;
			}
			
			#div1 {
				text-align: center;
				margin: auto;
				/*控制div的字体大小*/
				font-size: 30px;
				/*控制文本和边框之间的距离*/
				padding: 15px;
				margin-left:-40px;
			}
			
			
			#div2 {
				text-align: center;
				margin:auto;
				width: 300px;
				height: 100px;
				padding: 0px;
			}
			/*使光标放在超连接上变红*/
			
			a:hover {
				color: red;
			}
		</style>
	</head>

	<body>
		<div id="div1">用户登陆</div>
		<hr />
		<form action="/servlet_day5/login">
			<div id="div2">
				<table border="0" cellspacing="0" cellpadding="7">
					<tr>
						<td>
							<img src="img/user.png" />
						</td>
						<td>
							<input type="text" name="username" />
						</td>
					</tr>
					<tr>
						<td>
							<img src="img/pwd.png" />
						</td>
						<td>
							<input type="password" name = "password"/>
						</td>
					</tr>
					<tr>
						<td>
							<a href="/servlet_day5/regist.html" style="text-decoration: none">注册</a>							
						</td>
						<td>
							<input id="regist" type="submit" value="登陆" />
						</td>
					</tr>
				</table>
			</div>
		</form>
	</body>

</html>

2.LoginAction业务类

介绍:接收用户输入的数据,并调用dao层内的方法判断登录信息是否正确,如果不正确则展示对应的提示界面,如果正确,将信息存入request作用域并跳转到LoginJsp展示层

package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.PersonDaoImpl;

public class LoginAction extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4545630235072860810L;

	private static PersonDaoImpl pdi = new PersonDaoImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		String un = req.getParameter("username");
		String pwd = req.getParameter("password");
		String getPwd = pdi.queryPasswordByUserName(un);
		// 判断账号密码是否都为空
		if(un.equals("") && pwd.equals("")) {
			resp.sendRedirect("/servlet_day5/allnull.html");
			//判断账号是否为空
		}else if (un.equals("")) {
			resp.sendRedirect("/servlet_day5/unnull.html");
			// 判断密码是否为空
		} else if (pwd.equals("")) {
			resp.sendRedirect("/servlet_day5/pwd1null.html");
		} else {
			// 判断账号密码是否正确
			if (getPwd == null || !getPwd.equals(pwd)) {
				resp.sendRedirect("/servlet_day5/loginfailed.html");
			} else {
				// 将获取到的username放到Request作用域
				req.setAttribute("username", un);
				// 转发给success并响应给浏览器
				req.getRequestDispatcher("/loginsuccess").forward(req, resp);
			}
		}
	}

}

3.LoginJsp展示层

介绍:接收LoginAction存放在request作用域中数据,将登陆成功的信息动态展示给用户,并自动3秒跳转到ShowJsp界面

package 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;

public class LoginJsp extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7333050027516684398L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");
		String username = (String) req.getAttribute("username");
		String html = "<!DOCTYPE html>\n" + "<html>\n" + "  <head>\n" + "<meta http-equiv=\"refresh\" content=\"3;URL=/servlet_day5/show\"> " +"    <meta charset=\"UTF-8\">\n"
				+ "		<title>登陆状态</title>\n" + "  </head>\n" + "  <body> 用户" + username + ",登陆成功!3秒后跳转到联系人界面~ </body>\n"
				+ "</html>";
		PrintWriter pw = resp.getWriter();
		pw.flush();
		pw.print(html);
	}
}

四、注册层

1.regist.html

介绍:展示给用户操作的注册界面,让用户输入注册信息,当用户点击注册按钮后,跳转到RegistAction判断用户输入的数据是否合法。当用户点击重置按钮后,将信息恢复默认值

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title>注册页面</title>
		<style type="text/css">
			img {
				width: 30px;
				height: 30px;
			}
			
			#div1 {
				text-align: center;
				margin: auto;
				/*控制div的字体大小*/
				font-size: 30px;
				/*控制文本和边框之间的距离*/
				padding: 15px;
				margin-left: -40px;
			}
			
			#div2 {
				text-align: center;
				margin: auto;
				width: 300px;
				height: 100px;
				padding: 0px;
			}
			/*使光标放在超连接上变红*/
			
			a:hover {
				color: red;
			}
		</style>
	</head>

	<body>
		<div id="div1">用户注册</div>
		<hr />
		<form action="/servlet_day5/regist" method="post">
			<div id="div2">
				<table border="0" cellspacing="0" cellpadding="7">
					<tr>
						<td>
							用户名:
						</td>
						<td>
							<input type="text" name="username" />
						</td>
					</tr>
					<tr>
						<td>
							密码:
						</td>
						<td>
							<input type="password" name="password1" />
						</td>
					</tr>
					<tr>
						<td>
							密码:
						</td>
						<td>
							<input type="password" name="password2" />
						</td>
					</tr>
					<tr>
						<td>
							姓名:
						</td>
						<td>
							<input type="text" name="name" />
						</td>
					</tr>
					<tr>
						<td>
							年龄:
						</td>
						<td>
							<input type="text" name="age" />
						</td>
					</tr>
					<tr>
						<td>
							电话:
						</td>
						<td>
							<input type="text" name="phone" />
						</td>
					</tr>
					<tr>
						<td>
							家庭住址:
						</td>
						<td>
							<input type="text" name="address" />
						</td>
					</tr>
					<tr>
						<td>
							<input type="reset" style="float: left;"/>
						</td>
						<td>
							<input id="regist" type="submit" value="立即注册" />
						</td>
					</tr>
				</table>
			</div>
		</form>
	</body>

</html>

2.RegtistAction业务层

介绍:接收用户输入的注册信息,根据约束条件先进行第一轮判断,如果不合法则展示对应的提示界面,如果满足约束条件,调用dao层进行第二轮判断,如果合法,将信息存入request作用域并跳转到RegistJsp展示层

package servlet;

import java.io.IOException;

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

import dao.PersonDaoImpl;
import entity.Person;

public class RegistAction extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3653522036179307006L;

	// 创建一个PersonDaoImpl对象
	private static PersonDaoImpl pdi = new PersonDaoImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		int id = pdi.getSequence();
		String un = req.getParameter("username");
		String pwd1 = req.getParameter("password1");
		String pwd2 = req.getParameter("password2");
		String name = req.getParameter("name");
		String strAge = req.getParameter("age");
		Integer age = Integer.parseInt(strAge);
		String phone = req.getParameter("phone");
		String address = req.getParameter("address");
		// 判断账号是否为空
		if (un.equals("")) {
			resp.sendRedirect("/servlet_day5/unnull.html");
			// 判断第一次输入的密码是否为空
		} else if (pwd1.equals("")) {
			resp.sendRedirect("/servlet_day5/pwd1null.html");
			// 判断第二次输入的密码是否为空
		} else if (pwd2.equals("")) {
			resp.sendRedirect("/servlet_day5/pwd2null.html");
			// 判断用户名是否被使用
		} else if (pdi.ifExistToUserName(un)) {
			resp.sendRedirect("/servlet_day5/registfailed.html");
			// 判断两次输入的密码是否一致
		} else if (!pwd1.equals(pwd2)) {
			resp.sendRedirect("/servlet_day5/notboth.html");
			// 判断姓名是否为空
		} else if (name.equals("")) {
			resp.sendRedirect("/servlet_day5/namenull.html");
			// 判断年龄是否合法
		} else if (age > 200) {
			resp.sendRedirect("/servlet_day5/agemorethan.html");
			// 判断手机号码是否合法 长度为11位并且是1开头
		} else if (!phone.equals("") && phone.charAt(0) != '1' || phone.length() != 11) {
			resp.sendRedirect("/servlet_day5/morethan.html");
		} else {
			// 将注册信息存入数据库
			pdi.insert(un, pwd1, new Person(id, name, age, phone, address));
			// 使用重定向响应给浏览器
			resp.sendRedirect("/servlet_day5/registsuccess");
		}
	}
}

3.RegistJsp展示层

介绍:接收RegistAction存放在request作用域中数据,将注册成功的信息动态展示给用户,并自动3秒跳转到Login.html登录层

package 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;

public class RegistJsp extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5800424491666199917L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		String html = "<!DOCTYPE html>\n" + "<html>\n" + "<meta http-equiv=\"refresh\" content=\"3;URL=Login.html\"> " + "  <head>\n" + "    <meta charset=\"UTF-8\">\n"
				+ "		<title>注册状态</title>\n" + "  </head>\n" + "  <body> 注册成功!3秒后将跳转到登陆界面~ </body>\n"
				+ "</html>";
		PrintWriter pw = resp.getWriter();
		pw.flush();
		pw.print(html);
	}
}

五、展示所有用户信息

1.ShowJsp展示层

介绍:调用dao层中的selectAll方法获取所有用户信息的集合,并动态展示在浏览器界面上,具有添加用户、删除用户、修改用户、模糊搜索等功能。并根据用户对应的操作,跳转到不同的界面

package 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 dao.PersonDaoImpl;
import entity.Person;

public class ShowJsp extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7024825002117458007L;

	private static PersonDaoImpl pdi = new PersonDaoImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		StringBuilder sb = new StringBuilder("<!DOCTYPE html>\r\n");
		sb.append("<html>\r\n").append("\r\n").append("	<head>\r\n").append("		<meta charset=\"utf-8\" />\r\n")
				.append("		<title>展示联系人页面</title>\r\n").append("		<style type=\"text/css\">\r\n")
				.append("			img {\r\n").append("				width: 30px;\r\n")
				.append("				height: 30px;\r\n").append("			}\r\n").append("			\r\n")
				.append("			#title {\r\n").append("				text-align: center;\r\n")
				.append("				/*控制div的字体大小*/\r\n").append("				font-size: 30px;\r\n")
				.append("				/*控制文本和边框之间的距离*/\r\n").append("				padding: 15px;\r\n")
				.append("			}\r\n").append("			/*使光标放在超连接上变红*/\r\n").append("			\r\n")
				.append("			a:hover {\r\n").append("				color: red;\r\n").append("			}\r\n")
				.append("			\r\n").append("			a {\r\n").append("				color: blue;\r\n")
				.append("			}\r\n").append("			\r\n").append("			form {\r\n")
				.append("				text-align: center;\r\n").append("				font-family: 微软雅黑;\r\n")
				.append("				font-size: 18px;\r\n").append("			}\r\n").append("			\r\n")
				.append("			thead {\r\n").append("				color: white;\r\n").append("			}\r\n")
				.append("		</style>\r\n").append("	</head>\r\n").append("\r\n").append("	<body>\r\n")
				.append("		<div id=\"title\">展示所有联系人</div>\r\n").append("		<hr />\r\n")
				.append("		<form action=\"/servlet_day5/search\" method=\"post\">\r\n")
				.append("			<div style=\" text-align: center;\">\r\n")
				.append("				<div style=\"width: 48%;margin: auto;position:relative\">\r\n")
				.append("					<tr>\r\n").append("						<td>\r\n")
				.append("							<a href=\"insert.html\" style=\"position: relative;top: 0px;right: 170px;\">\r\n")
				.append("								<img src=\"img/add.png\" />\r\n")
				.append("							</a>\r\n").append("						</td>\r\n")
				.append("						<td>\r\n")
				.append("							<input type=\"text\" name=\"search\" style=\"position: relative;top: -5px;right: -166px;\" />\r\n")
				.append("						</td>\r\n").append("						<td>\r\n")
				.append("							<input type=\"submit\" style=\"position: relative;top: -5px;right: -170px;\">搜索</input>\r\n")
				.append("						</td>\r\n").append("					</tr>\r\n")
				.append("				</div>\r\n")
				.append("		</form>").append("		<form action=\"/servlet_day5/delete\" method=\"post\">\r\n")
				.append("				<table border=\"1\" cellspacing=\"1\" cellpadding=\"3\" style=\"margin: auto; width: 35%;\">\r\n")
				.append("					<thead bgcolor=\"aquamarine\">\r\n")
				.append("						<tr>\r\n").append("							<th>\r\n")
				.append("								<input type=\"submit\" value=\"删除选中\" />\r\n")
				.append("							</th>\r\n")
				.append("							<th>&emsp;</th>\r\n")
				.append("							<th>ID</th>\r\n")
				.append("							<th>USERNAME</th>\r\n")
				.append("							<th>AGE</th>\r\n")
				.append("							<th>PHONE</th>\r\n")
				.append("							<th>ADDRESS</th>\r\n")
				.append("							<th>删除</th>\r\n")
				.append("							<th>修改</th>\r\n").append("						</tr>\r\n")
				.append("					</thead>\r\n").append("					<tbody>\r\n");
		List<Person> list = pdi.selectAll();
		for (Person p : list) {
			sb.append("<tr>\r\n").append("		              <td><input type=\"checkbox\" name=\"id\" value=\""+p.getId()+"\" /></td>\r\n")
					.append("		              <td><img src=\"img/person.png\" /> </td>\r\n")
					.append("		              <td>").append(p.getId()).append("</td>\r\n")
					.append("		              <td>").append(p.getName()).append("</td>\r\n")
					.append("		              <td>").append(p.getAge()).append("</td>\r\n")
					.append("		              <td>").append(p.getPhone()).append("</td>\r\n")
					.append("		              <td>").append(p.getAddress()).append("</td>\r\n")
					.append("		              <td>")
					.append("<a href=\"/servlet_day5/delete?id=" + p.getId() + "\" name=\"remove\">删除</a>")
					.append("</td>\r\n").append("		              <td>")
					.append("<a href=\"/servlet_day5/showone?id=" + p.getId() + "\" name=\"update\">修改</a>")
					.append("</td>\r\n");
		}
		sb.append("					</tbody>\r\n").append("				</table>\r\n").append("			</div>\r\n")
				.append("	</body>\r\n").append("\r\n").append("</html>");
		String html = sb.toString();
		PrintWriter pw = resp.getWriter();
		pw.flush();
		pw.print(html);
	}
}

六、添加用户

1.insert.html

介绍:展示给用户操作的添加界面,让用户输入添加的联系人信息,当用户点击添加按钮后,跳转到InsertAction判断用户输入的数据是否合法。当用户点击重置按钮后,将信息恢复默认值

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title>添加联系人页面</title>
		<style type="text/css">
			img {
				width: 30px;
				height: 30px;
			}
			
			#div1 {
				text-align: center;
				margin: auto;
				/*控制div的字体大小*/
				font-size: 30px;
				/*控制文本和边框之间的距离*/
				padding: 15px;
				margin-left: -40px;
			}
			
			#div2 {
				text-align: center;
				margin: auto;
				width: 300px;
				height: 100px;
				padding: 0px;
			}
			/*使光标放在超连接上变红*/
			
			a:hover {
				color: red;
			}
		</style>
	</head>

	<body>
		<div id="div1">添加联系人</div>
		<hr />
		<form action="/servlet_day5/insert" method="post">
			<div id="div2">
				<table border="0" cellspacing="0" cellpadding="7">
					<tr>
						<td>
							用户名:
						</td>
						<td>
							<input type="text" name="username" />
						</td>
					</tr>
					<tr>
						<td>
							密码:
						</td>
						<td>
							<input type="password" name="password1" />
						</td>
					</tr>
					<tr>
						<td>
							密码:
						</td>
						<td>
							<input type="password" name="password2" />
						</td>
					</tr>
					<tr>
						<td>
							姓名:
						</td>
						<td>
							<input type="text" name="name" />
						</td>
					</tr>
					<tr>
						<td>
							年龄:
						</td>
						<td>
							<input type="text" name="age" />
						</td>
					</tr>
					<tr>
						<td>
							电话:
						</td>
						<td>
							<input type="text" name="phone" />
						</td>
					</tr>
					<tr>
						<td>
							家庭住址:
						</td>
						<td>
							<input type="text" name="address" />
						</td>
					</tr>
					<tr>
						<td>
							<input type="reset" style="float: left;"/>
						</td>
						<td>
							<input id="insert" type="submit" value="添加" />
						</td>
					</tr>
				</table>
			</div>
		</form>
	</body>

</html>

2.InsertAction业务类

介绍:接收用户输入的添加信息,根据约束条件先进行第一轮判断,如果不合法则展示对应的提示界面,如果满足约束条件,调用dao层进行第二轮判断,如果合法,跳转到ShowJsp界面

package servlet;

import java.io.IOException;

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

import dao.PersonDaoImpl;
import entity.Person;

public class InsertAction extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 3653522036179307006L;

	// 创建一个PersonDaoImpl对象
	private static PersonDaoImpl pdi = new PersonDaoImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		int id = pdi.getSequence();
		String un = req.getParameter("username");
		String pwd1 = req.getParameter("password1");
		String pwd2 = req.getParameter("password2");
		String name = req.getParameter("name");
		String strAge = req.getParameter("age");
		Integer age = Integer.parseInt(strAge);
		String phone = req.getParameter("phone");
		String address = req.getParameter("address");
		// 判断账号是否为空
		if (un.equals("")) {
			resp.sendRedirect("/servlet_day5/unnull.html");
			// 判断第一次输入的密码是否为空
		} else if (pwd1.equals("")) {
			resp.sendRedirect("/servlet_day5/pwd1null.html");
			// 判断第二次输入的密码是否为空
		} else if (pwd2.equals("")) {
			resp.sendRedirect("/servlet_day5/pwd2null.html");
			// 判断用户名是否被使用
		} else if (pdi.ifExistToUserName(un)) {
			resp.sendRedirect("/servlet_day5/insertfailed.html");
			// 判断两次输入的密码是否一致
		} else if (!pwd1.equals(pwd2)) {
			resp.sendRedirect("/servlet_day5/notboth.html");
			// 判断姓名是否为空
		} else if (name.equals("")) {
			resp.sendRedirect("/servlet_day5/namenull.html");
			// 判断年龄是否合法
		} else if (age > 200) {
			resp.sendRedirect("/servlet_day5/agemorethan.html");
			// 判断手机号码是否合法 长度为11位并且是1开头
		} else if (!phone.equals("") && phone.charAt(0) != '1' || phone.length() != 11) {
			resp.sendRedirect("/servlet_day5/morethan.html");
		} else {
			// 将添加的信息存入数据库
			pdi.insert(un, pwd1, new Person(id, name, age, phone, address));
			// 使用重定向响应给浏览器
			resp.sendRedirect("/servlet_day5/show");
		}
	}
}

七、删除用户

1.DeleteAction业务层

介绍:接收用户点击删除超链接或是点批量删除按钮传递过来的id值的集合,并调用dao层实现批量删除

package servlet;

import java.io.IOException;
import java.util.LinkedHashSet;

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

import dao.PersonDaoImpl;

public class DeleteAction extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4219373680813944804L;

	private static PersonDaoImpl pdi = new PersonDaoImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 设置文本格式
		resp.setContentType("text/html");
		// 设置编码集
		resp.setCharacterEncoding("utf-8");
		// 收集数据
		String[] strId = req.getParameterValues("id");
		System.out.println("id="+strId);
		LinkedHashSet<Integer> idSet = new LinkedHashSet<>();
		for (String id : strId) {
			idSet.add(Integer.parseInt(id));
		}
		pdi.deleteAll(idSet);
		// 将响应重定向到服务器
		resp.sendRedirect("/servlet_day5/show");
	}
}


八、修改用户信息

1.ShowOneJsp展示层

介绍:展示用户修改的联系人信息,当用户修改信息后点击确认按钮跳转到UpdateAction业务层进行判断,当用户点击重置按钮后,恢复到初始信息

package 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 dao.PersonDaoImpl;
import entity.Person;

public class ShowOneJsp extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -8190635567314628515L;

	private static PersonDaoImpl pdi = new PersonDaoImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		String strId = req.getParameter("id");
		int id = Integer.parseInt(strId);
		Person p = pdi.selectOne(id);
		StringBuilder sb = new StringBuilder();
		sb.append("<!DOCTYPE html>\r\n").append("<html>\r\n").append("\r\n").append("	<head>\r\n")
				.append("		<meta charset=\"utf-8\" />\r\n").append("		<title>修改联系人页面</title>\r\n")
				.append("		<style type=\"text/css\">\r\n").append("			div {\r\n")
				.append("				text-align: center;\r\n").append("				/*控制div的字体大小*/\r\n")
				.append("				font-size: 30px;\r\n").append("				/*控制文本和边框之间的距离*/\r\n")
				.append("				padding: 15px;\r\n").append("			}\r\n").append("			\r\n")
				.append("			/*使光标放在超连接上变红*/\r\n").append("			a:hover {\r\n")
				.append("				color: red;\r\n").append("			}\r\n").append("		</style>\r\n")
				.append("	</head>\r\n").append("\r\n").append("	<body>\r\n").append("		<div>修改联系人</div>\r\n")
				.append("		<hr />\r\n").append("		<form action=\"/servlet_day5/update?id="+id+"\" method=\"post\">")
				.append("			<table border=\"0\" cellspacing=\"0\" cellpadding=\"3\" align=\"center\">\r\n")
				.append("				<tr>\r\n").append("					<td>\r\n")
				.append("						姓名\r\n").append("					</td>\r\n")
				.append("					<td>\r\n").append("						<input type=\"text\" value=\"")
				.append(p.getName()).append("\" name=\"name\"/>\r\n").append("					</td>\r\n")
				.append("				</tr>\r\n").append("				<tr>\r\n")
				.append("					<td>\r\n").append("						年龄\r\n")
				.append("					</td>\r\n").append("					<td>\r\n")
				.append("						<input type=\"text\" value=\"").append(p.getAge()).append("\" name=\"age\"/>\r\n")
				.append("					</td>\r\n").append("				</tr>\r\n")
				.append("				<tr>\r\n").append("					<td>\r\n")
				.append("						手机号\r\n").append("					</td>\r\n")
				.append("					<td>\r\n").append("						<input type=\"text\" value=\"")
				.append(p.getPhone()).append("\" name=\"phone\"/>\r\n").append("					</td>\r\n")
				.append("				</tr>\r\n").append("				<tr>\r\n")
				.append("					<td>\r\n").append("						地址\r\n")
				.append("					</td>\r\n").append("					<td>\r\n")
				.append("						<input type=\"text\" value=\"").append(p.getAddress())
				.append("\" name=\"address\"/>\r\n").append("					</td>\r\n").append("				</tr>\r\n")
				.append("				<tr>\r\n").append("					<td></td>\r\n")
				.append("					<td align=\"center\">\r\n")
				.append("						<input type=\"submit\" value=\"修改\" />\r\n")
				.append("					</td>\r\n").append("				</tr>\r\n")
				.append("			</table>\r\n").append("		</form>\r\n").append("	</body>\r\n").append("\r\n")
				.append("</html>");
		String html = sb.toString();
		PrintWriter pw = resp.getWriter();
		pw.flush();
		pw.print(html);
	}
}

2.UpdateAction业务层

介绍:接收用户修改后的信息,判断是否满足约束条件,如果不满足,跳转到对应的提示界面,如果满足,调用dao层将数据库中数据进行修改

package servlet;

import java.io.IOException;

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

import dao.PersonDaoImpl;
import entity.Person;

public class UpdateAction extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4219373680813944804L;

	private static PersonDaoImpl pdi = new PersonDaoImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		// 设置文本格式
		resp.setContentType("text/html");
		// 设置编码集
		resp.setCharacterEncoding("utf-8");
		// 收集数据
		int id = Integer.parseInt(req.getParameter("id"));
		String name = req.getParameter("name");
		int age = Integer.parseInt(req.getParameter("age"));
		String phone = req.getParameter("phone");
		String address = req.getParameter("address");
		if (age > 200) {
			resp.sendRedirect("/servlet_day5/agemorethan.html");
		} else if (phone.charAt(0) != '1' || phone.length() != 11) {
			resp.sendRedirect("/servlet_day5/morethan.html");
		} else {
			pdi.update(id, new Person(name, age, phone, address));
			// 将响应重定向到服务器
			resp.sendRedirect("/servlet_day5/show");
		}
	}
}

九、搜索层

1.SearchAction业务层

介绍:接收用户点击超链接时传递过来的数据,调用dao层中的方法进行模糊查询,并将数据放入request作用域进行存储

package servlet;

import java.io.IOException;
import java.util.LinkedHashSet;

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

import dao.PersonDaoImpl;
import entity.Person;

public class SearchAction extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -750773065686049751L;

	private static PersonDaoImpl pdi = new PersonDaoImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		String value = req.getParameter("search");
		LinkedHashSet<Person> selectAllLike = new LinkedHashSet<>();
		if (pdi.ifInteger(value)) {
			selectAllLike.addAll(pdi.selectLikeAge(value));
			selectAllLike.addAll(pdi.selectLikeTel(value));
		} else {
			selectAllLike.addAll(pdi.selectLikeName(value));
			selectAllLike.addAll(pdi.selectLikeAddress(value));
		}
		// 将查询到的值放到作用域
		req.setAttribute("searchAll", selectAllLike);
		// 转发给SearchJsp
		req.getRequestDispatcher("/searchsuccess").forward(req, resp);
	}
}

2.SearchJsp展示层

介绍:获取request作用域中的数据集,并动态展示在浏览器界面上

package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashSet;

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

import entity.Person;

public class SearchJsp extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 7024825002117458007L;

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		StringBuilder sb = new StringBuilder("<!DOCTYPE html>\r\n");
		sb.append("<html>\r\n").append("\r\n").append("	<head>\r\n").append("		<meta charset=\"utf-8\" />\r\n")
				.append("		<title>展示联系人页面</title>\r\n").append("		<style type=\"text/css\">\r\n")
				.append("			img {\r\n").append("				width: 30px;\r\n")
				.append("				height: 30px;\r\n").append("			}\r\n").append("			\r\n")
				.append("			#title {\r\n").append("				text-align: center;\r\n")
				.append("				/*控制div的字体大小*/\r\n").append("				font-size: 30px;\r\n")
				.append("				/*控制文本和边框之间的距离*/\r\n").append("				padding: 15px;\r\n")
				.append("			}\r\n").append("			/*使光标放在超连接上变红*/\r\n").append("			\r\n")
				.append("			a:hover {\r\n").append("				color: red;\r\n").append("			}\r\n")
				.append("			\r\n").append("			a {\r\n").append("				color: blue;\r\n")
				.append("			}\r\n").append("			\r\n").append("			form {\r\n")
				.append("				text-align: center;\r\n").append("				font-family: 微软雅黑;\r\n")
				.append("				font-size: 18px;\r\n").append("			}\r\n").append("			\r\n")
				.append("			thead {\r\n").append("				color: white;\r\n").append("			}\r\n")
				.append("		</style>\r\n").append("	</head>\r\n").append("\r\n").append("	<body>\r\n")
				.append("		<div id=\"title\">展示所有联系人</div>\r\n").append("		<hr />\r\n")
				.append("		<form action=\"/servlet_day5/search\" method=\"post\">\r\n")
				.append("			<div style=\" text-align: center;\">\r\n")
				.append("				<div style=\"width: 48%;margin: auto;position:relative\">\r\n")
				.append("					<tr>\r\n").append("						<td>\r\n")
				.append("							<a href=\"insert.html\" style=\"position: relative;top: 0px;right: 170px;\">\r\n")
				.append("								<img src=\"img/add.png\" />\r\n")
				.append("							</a>\r\n").append("						</td>\r\n")
				.append("						<td>\r\n")
				.append("							<input type=\"text\" name=\"search\" style=\"position: relative;top: -5px;right: -166px;\" />\r\n")
				.append("						</td>\r\n").append("						<td>\r\n")
				.append("							<input type=\"submit\" style=\"position: relative;top: -5px;right: -170px;\">搜索</input>\r\n")
				.append("						</td>\r\n").append("					</tr>\r\n")
				.append("				</div>\r\n").append("		</form>")
				.append("				<table border=\"1\" cellspacing=\"1\" cellpadding=\"3\" style=\"margin: auto; width: 35%;\">\r\n")
				.append("					<thead bgcolor=\"aquamarine\">\r\n")
				.append("						<tr>\r\n").append("							<th>\r\n")
				.append("								<input type=\"button\" value=\"删除选中\" />\r\n")
				.append("							</th>\r\n")
				.append("							<th>&emsp;</th>\r\n")
				.append("							<th>ID</th>\r\n")
				.append("							<th>USERNAME</th>\r\n")
				.append("							<th>AGE</th>\r\n")
				.append("							<th>PHONE</th>\r\n")
				.append("							<th>ADDRESS</th>\r\n")
				.append("							<th>删除</th>\r\n")
				.append("							<th>修改</th>\r\n").append("						</tr>\r\n")
				.append("					</thead>\r\n").append("					<tbody>\r\n");
		LinkedHashSet<Person> list = (LinkedHashSet<Person>) req.getAttribute("searchAll");
		for (Person p : list) {
			sb.append("<tr>\r\n").append("		              <td><input type=\"checkbox\" /></td>\r\n")
					.append("		              <td><img src=\"img/person.png\" /> </td>\r\n")
					.append("		              <td>").append(p.getId()).append("</td>\r\n")
					.append("		              <td>").append(p.getName()).append("</td>\r\n")
					.append("		              <td>").append(p.getAge()).append("</td>\r\n")
					.append("		              <td>").append(p.getPhone()).append("</td>\r\n")
					.append("		              <td>").append(p.getAddress()).append("</td>\r\n")
					.append("		              <td>")
					.append("<a href=\"/servlet_day5/delete?id=" + p.getId() + "\" name=\"remove\">删除</a>")
					.append("</td>\r\n").append("		              <td>")
					.append("<a href=\"/servlet_day5/showone?id=" + p.getId() + "\" name=\"update\">修改</a>")
					.append("</td>\r\n");
		}
		sb.append("					</tbody>\r\n").append("				</table>\r\n").append("			</div>\r\n")
				.append("	</body>\r\n").append("\r\n").append("</html>");
		String html = sb.toString();
		PrintWriter pw = resp.getWriter();
		pw.flush();
		pw.print(html);
	}
}

十、dao层

1.PersonDao接口

介绍:定义了一些需要用到的方法

package dao;

import java.util.LinkedHashSet;
import java.util.List;

import entity.Person;

public interface PersonDao {
	// 通过用户名查询密码
	public String queryPasswordByUserName(String username);

	// 判断用户名是否存在
	public boolean ifExistToUserName(String username);

	// 新用户注册
	public boolean insert(String username, String password,Person p);

	// 查询所有用户信息
	public List<Person> selectAll();
	
	// 通过id查询用户信息
	public Person selectOne(Integer id);
	
	// 获取下一个序列值
	public int getSequence();
	
	// 判断是否为整数
	public boolean ifInteger(String str);
	
	// 通过id批量删除用户
	public void deleteAll(LinkedHashSet<Integer> id);
	
	// 根据id修改用户信息
	public void update(Integer id,Person p);
	
	// 通过手机号模糊查询用户
	public List<Person> selectLikeTel(String tel);
	
	// 通过姓名模糊查询用户
	public List<Person> selectLikeName(String name);
	
	// 通过地址模糊查询用户
	public List<Person> selectLikeAddress(String addr);
	
	// 通过年龄模糊查询用户
	public List<Person> selectLikeAge(String age);
}

2.PersonDaoImpl实现类

介绍:通过jdbc连接数据库,实现接口中的方法

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;

import org.junit.Test;

import entity.Person;
import utils.JdbcUtils;

public class PersonDaoImpl implements PersonDao {

	// 通过用户名查询密码
	@Override
	public String queryPasswordByUserName(String username) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement("select password from person where username = ?");
			ps.setString(1, username);
			rs = ps.executeQuery();
			boolean bn = rs.next();
			if (bn) {
				return rs.getString(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, rs);
		}
		return null;
	}

	@Test
	public void testQuery() {
		PersonDaoImpl pdi = new PersonDaoImpl();
		String str = pdi.queryPasswordByUserName("zxw");
		System.out.println(str);
	}

	// 判断用户名是否存在
	@Override
	public boolean ifExistToUserName(String username) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement("select password from person where username = ?");
			ps.setString(1, username);
			rs = ps.executeQuery();
			return rs.next();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, rs);
		}
		return false;
	}

	// 注册新用户
	@Override
	public boolean insert(String username, String password, Person p) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement("insert into person values(?,?,?,?,?,?,?)");
			ps.setInt(1, p.getId());
			ps.setString(2, username);
			ps.setString(3, password);
			ps.setString(4, p.getName());
			ps.setInt(5, p.getAge() == null ? 0 : p.getAge());
			ps.setString(6, p.getPhone());
			ps.setString(7, p.getAddress());
			ps.executeUpdate();
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, rs);
		}
		return false;
	}

	// 获取所有用户信息
	@Override
	public List<Person> selectAll() {
		List<Person> list = new ArrayList<Person>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement("select ID,NAME,AGE,PHONE,ADDRESS from person");
			rs = ps.executeQuery();
			while (rs.next()) {
				Integer id = rs.getInt(1);
				String name = rs.getString(2);
				Integer age = rs.getInt(3);
				String phone = rs.getString(4);
				String address = rs.getString(5);
				list.add(new Person(id, name, age, phone, address));
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, rs);
		}
		return null;
	}

	@Test
	public void testSelectAll() {
		List<Person> list = selectAll();
		for (Person p : list) {
			System.out.println(p);
		}
	}

	// 获取下一个序列值
	@Override
	public int getSequence() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement("select login_seq.nextVal from dual");
			rs = ps.executeQuery();
			if (rs.next())
				return rs.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, rs);
		}
		return 0;
	}

	@Test
	public void testGetSequence() {
		System.out.println(getSequence());
	}

	// 判断是否为整数
	@Override
	public boolean ifInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
		return pattern.matcher(str).matches();
	}

	@Test
	public void testIfInteger() {
		Scanner s = new Scanner(System.in);
		System.out.println(ifInteger(s.next()) ? "是整数!" : "不是整数!");
		s.close();
	}

	// 通过id批量删除用户
	@Override
	public void deleteAll(LinkedHashSet<Integer> idSet) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = JdbcUtils.getConnection();
			for(Integer id : idSet) {
				ps = conn.prepareStatement("delete person where id = ?");
				ps.setInt(1, id);
				ps.executeUpdate();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, null);
		}
	}

	@Test
	public void testDeleteAll() {
		LinkedHashSet<Integer> idSet = new LinkedHashSet<>();
		idSet.add(48);
		idSet.add(52);
		idSet.add(53);
		idSet.add(54);
		idSet.add(55);
		deleteAll(idSet);
	}


	@Override
	public Person selectOne(Integer id) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement("select NAME,AGE,PHONE,ADDRESS from person where id = ?");
			ps.setInt(1, id);
			rs = ps.executeQuery();
			if (rs.next())
				return new Person(rs.getString(1), rs.getInt(2), rs.getString(3), rs.getString(4));
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, rs);
		}
		return null;
	}

	@Test
	public void testSelectOne() {
		Person p = selectOne(1);
		System.out.println(p);
	}

	@Override
	public void update(Integer id, Person p) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement("update person set NAME=?,AGE=?,PHONE=?,ADDRESS=? where ID=?");
			ps.setString(1, p.getName());
			ps.setInt(2, p.getAge());
			ps.setString(3, p.getPhone());
			ps.setString(4, p.getAddress());
			ps.setInt(5, id);
			ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, rs);
		}
	}

	@Test
	public void testUpdate() {
		update(38, new Person("修改测试", 20, "12345678910", "湖南娄底"));
	}

	@Override
	public List<Person> selectLikeTel(String tel) {
		List<Person> list = new ArrayList<Person>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement("select ID,NAME,AGE,PHONE,ADDRESS from person where PHONE like '%'||?||'%'");
			ps.setString(1, tel);
			rs = ps.executeQuery();
			while (rs.next()) {
				Integer id = rs.getInt(1);
				String name = rs.getString(2);
				Integer age = rs.getInt(3);
				String phone = rs.getString(4);
				String address = rs.getString(5);
				list.add(new Person(id, name, age, phone, address));
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, rs);
		}
		return null;
	}

	@Override
	public List<Person> selectLikeName(String name) {
		List<Person> list = new ArrayList<Person>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement("select ID,NAME,AGE,PHONE,ADDRESS from person where NAME like '%'||?||'%'");
			ps.setString(1, name);
			rs = ps.executeQuery();
			while (rs.next()) {
				Integer id = rs.getInt(1);
				String name1 = rs.getString(2);
				Integer age = rs.getInt(3);
				String phone = rs.getString(4);
				String address = rs.getString(5);
				list.add(new Person(id, name1, age, phone, address));
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, rs);
		}
		return null;
	}

	@Test
	public void testSelectLike() {
		List<Person> list = selectLikeName("刘");
		System.out.println(list.size());
		for (Person p : list) {
			System.out.println(p);
		}
	}

	@Override
	public List<Person> selectLikeAddress(String addr) {
		List<Person> list = new ArrayList<Person>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement("select ID,NAME,AGE,PHONE,ADDRESS from person where ADDRESS like '%'||?||'%'");
			ps.setString(1, addr);
			rs = ps.executeQuery();
			while (rs.next()) {
				Integer id = rs.getInt(1);
				String name1 = rs.getString(2);
				Integer age = rs.getInt(3);
				String phone = rs.getString(4);
				String address = rs.getString(5);
				list.add(new Person(id, name1, age, phone, address));
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, rs);
		}
		return null;
	}

	@Override
	public List<Person> selectLikeAge(String age) {
		List<Person> list = new ArrayList<Person>();
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = JdbcUtils.getConnection();
			ps = conn.prepareStatement("select ID,NAME,AGE,PHONE,ADDRESS from person where AGE like '%'||?||'%'");
			ps.setString(1, age);
			rs = ps.executeQuery();
			while (rs.next()) {
				Integer id = rs.getInt(1);
				String name1 = rs.getString(2);
				Integer age1 = rs.getInt(3);
				String phone = rs.getString(4);
				String address = rs.getString(5);
				list.add(new Person(id, name1, age1, phone, address));
			}
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JdbcUtils.closeAll(conn, ps, rs);
		}
		return null;
	}
}

十一、其它的工具类和资源文件

1.JdbcUtils工具类

介绍:定义了获取连接和关闭资源的方法,供dao层调用

package utils;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class JdbcUtils {
	// 封装一个数据库连接池对象
	private static DataSource ds;
	// 加载驱动
	static {
		try {
			Properties pro = new Properties();
			// 创建一个输入流对象读取数据
			InputStream path = JdbcUtils.class.getResourceAsStream("/druid.properties");
			pro.load(path);
			ds = DruidDataSourceFactory.createDataSource(pro);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	// 创建一个ThreadLocal对象
	private static final ThreadLocal<Connection> local1 = new ThreadLocal<>();

	// 根据帐号密码获取Connetion对象
	public static Connection getConnection(String userName, String password) {
		try {
			if (local1.get() == null) {
				local1.set(ds.getConnection());
			}
			return local1.get();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 创建一个ThreadLocal对象
	private static final ThreadLocal<Connection> local2 = new ThreadLocal<>();

	// 获取默认帐号密码的Connection对象
	public static Connection getConnection() {
		try {
			if (local2.get() == null) {
				local2.set(ds.getConnection());
			}
			return local2.get();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 关闭所有资源
	public static void closeAll(Connection conn, PreparedStatement ps, ResultSet rs) {
		if (conn != null) {
			try {
				if (local1.get() != null) {
					local1.remove();
				} else if (local2.get() != null) {
					local2.remove();
				}
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		if (ps != null) {
			try {
				ps.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	// 关闭Connection
	public static void closeOne(Connection conn) {
		if (conn != null) {
			try {
				if (local1.get() != null) {
					local1.remove();
				} else if (local2.get() != null) {
					local2.remove();
				}
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

2.实体类Person

介绍:封装了一些属性,覆盖了equals和hashcode方法

package entity;

public class Person {
	private Integer id;
	private String name;
	private Integer age;
	private String phone;
	private String address;

	public Person() {
		super();
	}

	public Person(Integer id, String name, Integer age, String phone, String address) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
		this.phone = phone;
		this.address = address;
	}

	public Person(String name, Integer age, String phone, String address) {
		super();
		this.name = name;
		this.age = age;
		this.phone = phone;
		this.address = address;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	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 getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + ", phone=" + phone + ", address=" + address
				+ "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
}

3.xml配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <!-- LoginAction业务层 -->
  <servlet>
  	<servlet-name>loginAction</servlet-name>
  	<servlet-class>servlet.LoginAction</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>loginAction</servlet-name>
  	<url-pattern>/login</url-pattern>
  </servlet-mapping>
  
  <!-- LoginJsp展示层 -->
  <servlet>
  	<servlet-name>loginJsp</servlet-name>
  	<servlet-class>servlet.LoginJsp</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>loginJsp</servlet-name>
  	<url-pattern>/loginsuccess</url-pattern>
  </servlet-mapping>
  
  <!-- RegistAction业务层 -->
   <servlet>
  	<servlet-name>RegistAction</servlet-name>
  	<servlet-class>servlet.RegistAction</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>RegistAction</servlet-name>
  	<url-pattern>/regist</url-pattern>
  </servlet-mapping>
  
  <!-- RegistJsp展示层 -->
   <servlet>
  	<servlet-name>RegistJSP</servlet-name>
  	<servlet-class>servlet.RegistJsp</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>RegistJSP</servlet-name>
  	<url-pattern>/registsuccess</url-pattern>
  </servlet-mapping>
  
  <!-- 展示所有用户信息 -->
   <servlet>
  	<servlet-name>ShowJsp</servlet-name>
  	<servlet-class>servlet.ShowJsp</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>ShowJsp</servlet-name>
  	<url-pattern>/show</url-pattern>
  </servlet-mapping> 
  
  <!-- 修改用户信息 -->
   <servlet>
  	<servlet-name>UpdateAction</servlet-name>
  	<servlet-class>servlet.UpdateAction</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>UpdateAction</servlet-name>
  	<url-pattern>/update</url-pattern>
  </servlet-mapping> 
  
  <!-- 展示修改的用户信息 -->
   <servlet>
  	<servlet-name>ShowOneJsp</servlet-name>
  	<servlet-class>servlet.ShowOneJsp</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>ShowOneJsp</servlet-name>
  	<url-pattern>/showone</url-pattern>
  </servlet-mapping> 
  
  <!-- 添加用户-->
   <servlet>
  	<servlet-name>InsertAction</servlet-name>
  	<servlet-class>servlet.InsertAction</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>InsertAction</servlet-name>
  	<url-pattern>/insert</url-pattern>
  </servlet-mapping>
  
  <!-- 删除用户 -->
   <servlet>
  	<servlet-name>DeleteAction</servlet-name>
  	<servlet-class>servlet.DeleteAction</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>DeleteAction</servlet-name>
  	<url-pattern>/delete</url-pattern>
  </servlet-mapping>
  
  <!-- 模糊搜索用户Action -->
   <servlet>
  	<servlet-name>SearchAction</servlet-name>
  	<servlet-class>servlet.SearchAction</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>SearchAction</servlet-name>
  	<url-pattern>/search</url-pattern>
  </servlet-mapping>
  
  <!-- 模糊搜索用户Jsp -->
   <servlet>
  	<servlet-name>SearchJsp</servlet-name>
  	<servlet-class>servlet.SearchJsp</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>SearchJsp</servlet-name>
  	<url-pattern>/searchsuccess</url-pattern>
  </servlet-mapping> 
  
</web-app>