JavaWeb - 综合练习
综合练习:
1. 简单功能
1. 列表查询
2. 登录
3. 添加
4. 删除
5. 修改
2. 复杂功能
1. 删除选中
2. 分页查询
1. 减轻服务器内存的开销
2. 提升用户体验
(2)
3. 复杂条件查询
##登录功能
1. 调整页面,加入验证码功能
# 整体思路设计:
1. 设计页面布局,通过form表单传输参数到Servlet页面
2. Servlet页面设置编码、接收参数,根据参数和功能要求找到Service页面,Service页面根据需求将参数和条件传递到Dao页面进行数据处理
3. Dao页面编写核心sql,将数据包装后返回
4. Servlet页面拿到数据后通过转发和重定向让页面数据回显或跳转页面
5. 在前端页面通过JSTL和EL表达式获取域中的数据,放置到页面中
登录的login页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>管理员登录</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <script type="text/javascript"> //切换验证码 function refreshCode() { //获取验证码的图片对象 var vcode = document.getElementById("vcode"); //设置其src属性,加时间戳 vcode.src = "${pageContext.request.contextPath}/checkCodeServlet?time"+new Date().getTime(); } </script> </head> <body> <div class="container" style="width: 400px;"> <h3 style="text-align: center;">管理员登录</h3> <form action="${pageContext.request.contextPath}/loginServlet" method="post"> <div class="form-group"> <label for="user">用户名:</label> <input type="text" name="username" class="form-control" id="user" placeholder="请输入用户名"/> </div> <div class="form-group"> <label for="password">密码:</label> <input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/> </div> <div class="form-inline"> <label for="vcode">验证码:</label> <input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="请输入验证码" style="width: 120px;"/> <a href="javascript:refreshCode();"><img src="${pageContext.request.contextPath}/checkCodeServlet" title="看不清点击刷新" id="vcode"/></a> </div> <hr/> <div class="form-group" style="text-align: center;"> <input class="btn btn btn-primary" type="submit" value="登录"> </div> </form> <!-- 出错显示的信息框 --> <div class="alert alert-warning alert-dismissible" role="alert"> <button type="button" class="close" data-dismiss="alert" > <span>×</span></button> <strong>${login_msg}</strong> </div> </div> </body> </html>
进行登录页面的loginServlet页面:
package web.servlet; import domain.User; import org.apache.commons.beanutils.BeanUtils; import service.UserService; import service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.设置编码 request.setCharacterEncoding("utf-8"); // 2. 获取数据 String verifycode = request.getParameter("verifycode"); // 3. 验证码校验 HttpSession session = request.getSession(); String check_code =(String) session.getAttribute("check_code"); //确保验证码一次性 session.removeAttribute("check_code"); if(!check_code.equalsIgnoreCase(verifycode)){ //验证码不正确 //提示信息,跳转登录页面 request.setAttribute("login_msg","验证码错误!"); request.getRequestDispatcher("/login.jsp").forward(request,response); } // 3.封装user对象 Map<String, String[]> map = request.getParameterMap(); User user = new User(); try { BeanUtils.populate(user,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // 5. 调用Service查询 UserService service = new UserServiceImpl(); User login_user = service.login(user); // 6. 判断是否登录成功 if(login_user!=null){ //登录成功 // 将用户存入session,跳转页面 session.setAttribute("user",login_user); response.sendRedirect(request.getContextPath()+"/index.jsp"); }else { //登录失败 request.setAttribute("login_msg","用户名或密码错误"); request.getRequestDispatcher("/login.jsp").forward(request,response); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
index主页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>首页</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <script type="text/javascript"> </script> </head> <body> <div align="center" style="font-size: 25px">${user.name},欢迎您</div> <div align="center"> <a href="${pageContext.request.contextPath}/findUserByPageServlet" style="text-decoration:none;font-size:33px">查询所有用户信息 </a> </div> </body> </html>
查看用户列表的Servlet:
package web.servlet; import domain.PageBean; import domain.User; import service.UserService; import service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Map; @WebServlet("/findUserByPageServlet") public class findUserByPageServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //1. 获取参数 String currentPage = request.getParameter("currentPage");//当前页码 String rows = request.getParameter("rows");//每页显示的条数 if(currentPage==null||"".equals(currentPage)){ currentPage="1"; } if(rows==null || "".equals(rows)){ rows = "5"; } // 获取条件查询的参数 Map<String, String[]> condition = request.getParameterMap(); //2. 调用service UserService service = new UserServiceImpl(); PageBean<User> pb = service.findUserByPage(currentPage,rows,condition); // System.out.println(pb); //3. 将PageBean存入request request.setAttribute("pb",pb); // 将查询条件也存入,方便回显 request.setAttribute("condition",condition); //4. 转发到list.jsp request.getRequestDispatcher("/list.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
点击查看所有列表的list页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>用户信息管理系统</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> <style type="text/css"> td, th { text-align: center; } </style> <script> //删除时弹出提示框 function delUser(id) { if(confirm("您确定要删除吗")){ //访问路径 location.href = "${pageContext.request.contextPath}/delServlet?id=" + id; } } window.onload = function () { //给删除选中按钮添加单击事件 document.getElementById("delSelected").onclick = function () { //删除确认 if (confirm("您确定要删除选中条目吗?")) { var flag = false;//用于判断是否有条目被选中,防止空指针异常 // 判断是否有选中条目 var cbs = document.getElementsByName("uid"); for(var i = 0; i < cbs.length ;i++){ if(cbs[i].checked){ //表示有一个条目选中了 flag = true; break; } } if(flag) {//有条目被选中 //将所有选了的表单提交 document.getElementById("delForm").submit(); } } } }; // 全选全不选的勾勾 document.getElementById("firstCb").onclick = function () { // 获取下面列表中所有的Cb var cbs = document.getElementsByName("uid"); // 遍历 for(var i = 0; i < cbs.length ;i++){ //设置这些cbs[i]的checked状态等于firstCb的checked状态 cbs[i].checked = this.checked; } }; } </script> </head> <body> <div class="container"> <h3 style="text-align: center">用户信息列表</h3> <div style="float: left"> <form class="form-inline" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post"> <div class="form-group" style="margin-left: 5px"> <label for="exampleInputName2">姓名</label> <input type="text" class="form-control" id="exampleInputName2" name="name" value="${condition.name[0]}" > </div> <div class="form-group" style="margin-left: 5px"> <label for="exampleInputName3">籍贯</label> <input type="text" class="form-control" id="exampleInputName3" name="address" value="${condition.address[0]}"> </div> <div class="form-group" style="margin-left: 5px"> <label for="exampleInputEmail2">邮箱</label> <input type="email" class="form-control" id="exampleInputEmail2" name="email" value="${condition.email[0]}"> </div> <button type="submit" class="btn btn-default">查询</button> </form> </div> <div style="float: right; margin: 5px"> <a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加联系人</a> <%--给删除选中按钮加单击事件,使其提交复选框选中的id表单--%> <a class="btn btn-primary" href="javascript:void(0);" id="delSelected">删除选中</a> </div> <%--将复选框的id用表单的形式提交--%> <form id="delForm" action="${pageContext.request.contextPath}/delSelectedServlet" method="post"> <table border="1" class="table table-bordered table-hover"> <tr class="success"> <th><input type="checkbox" id="firstCb"></th> <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>籍贯</th> <th>QQ</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach items="${pb.list}" var="user" varStatus="s"> <tr> <th><input type="checkbox" name="uid" value="${user.id}"></th> <td>${s.count}</td> <td>${user.name}</td> <td>${user.gender}</td> <td>${user.age}</td> <td>${user.address}</td> <td>${user.qq}</td> <td>${user.email}</td> <td><a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改</a> <a class="btn btn-default btn-sm" href="javascript:delUser(${user.id});">删除</a></td> </tr> </c:forEach> </table> </form> <%--分页工具条--%> <div> <nav aria-label="Page navigation"> <ul class="pagination"> <%--第一页时前一页不可选--%> <c:if test="${pb.currentPage==1}"> <li class="disabled"> <%--上一页--%> <a href="#" aria-label="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage -1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}"> <span aria-hidden="true">«</span> </a> </li> </c:if> <c:if test="${pb.currentPage!=1}"> <li> <%--上一页--%> <a href="#" aria-label="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage -1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}"> <span aria-hidden="true">«</span> </a> </li> </c:if> <%--页码的获取--%> <c:forEach begin="1" end="${pb.totalPage}" var="i"> <%--为页码添加激活状态--%> <c:if test="${pb.currentPage==i}"> <li class="active"><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}"> ${i} </a></li> </c:if> <%--为页码添加激活状态--%> <c:if test="${pb.currentPage!= i}"> <li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}"> ${i} </a></li> </c:if> </c:forEach> <li> <%--下一页--%> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage +1}&rows=5" aria-label="Next"> <span aria-hidden="true">»</span> </a> </li> <span style="font-size: 25px; margin-left: 8px"> 共${pb.totalCount}条记录,共${pb.totalPage}页 </span> </ul> </nav> </div> </div> </body> </html>
list页面点击修改数据后跳转到的查找用户信息并回显的Servlet:
package web.servlet; import domain.User; import service.UserService; import service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/findUserServlet") public class findUserServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); UserService service = new UserServiceImpl(); // 在数据库中查找到该id的用户 User user = service.findUser(id); // 将该用户封装到user里 request.setAttribute("user",user); //传递到显示信息的更新的jsp request.getRequestDispatcher("/update.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
回显信息,并且提供修改数据页面的jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>修改用户</title> <link href="css/bootstrap.min.css" rel="stylesheet"> <script src="js/jquery-2.1.0.min.js"></script> <script src="js/bootstrap.min.js"></script> </head> <body> <div class="container" style="width: 400px;"> <h3 style="text-align: center;">修改联系人</h3> <form action="${pageContext.request.contextPath}/updateServlet" method="post"> <%--隐藏域--%> <input type="hidden" name="id" value="${user.id}"> <div class="form-group"> <label for="name">姓名:</label> <input type="text" class="form-control" id="name" name="name" value="${user.name}" readonly="readonly" placeholder="请输入姓名" /> </div> <div class="form-group"> <label>性别:</label> <%--先通过JSTL判断性别,在设置checked属性--%> <c:if test="${user.gender == '男'}"> <input type="radio" name="gender" value="男" checked />男 <input type="radio" name="gender" value="女" />女 </c:if> <c:if test="${user.gender == '女'}"> <input type="radio" name="gender" value="男" />男 <input type="radio" name="gender" value="女" checked />女 </c:if> </div> <div class="form-group"> <label for="age">年龄:</label> <input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄" value="${user.age}" /> </div> <div class="form-group"> <label for="address">籍贯:</label> <select name="address" class="form-control" id="address" > <c:if test="${user.address == '广东'}"> <option value="广东" selected="selected">广东</option> <option value="广西">广西</option> <option value="湖南">湖南</option> </c:if> <c:if test="${user.address == '湖南'}"> <option value="广东">广东</option> <option value="广西">广西</option> <option value="湖南" selected="selected">湖南</option> </c:if> <c:if test="${user.address == '广西'}"> <option value="广东" >广东</option> <option value="广西" selected="selected">广西</option> <option value="湖南">湖南</option> </c:if> <c:if test="${user.address != '广西' and user.address!= '广东' and user.address!= '湖南'}"> <option value="广东" >广东</option> <option value="广西">广西</option> <option value="湖南">湖南</option> <option value="${user.address}" selected="selected">${user.address}</option> </c:if> </select> </div> <div class="form-group"> <label for="qq">QQ:</label> <input type="text" class="form-control" name="qq" placeholder="请输入QQ号码" id="qq" value="${user.qq}"/> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" name="email" placeholder="请输入邮箱地址" id="email" value="${user.email}"/> </div> <div class="form-group" style="text-align: center"> <input class="btn btn-primary" type="submit" value="提交" /> <input class="btn btn-default" type="reset" value="重置" /> <input class="btn btn-default" type="button" value="返回"/> </div> </form> </div> </body> </html>
进行update信息接收的Servlet:
package web.servlet; import domain.User; import org.apache.commons.beanutils.BeanUtils; import service.UserService; import service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/updateServlet") public class updateServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); Map<String, String[]> map = request.getParameterMap(); User user = new User(); try { BeanUtils.populate(user,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } UserService service = new UserServiceImpl(); service.updateUser(user); //重定向到用户列表,展示更新的数据 response.sendRedirect(request.getContextPath()+"/userListServlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
将更新的信息封装到user里传递给UserListServlet后,该Servlet将数据重新更新到list.jsp页面
package web.servlet; import domain.User; import service.UserService; import service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/userListServlet") public class UserListServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. 调用UserService完成查询 UserService service = new UserServiceImpl(); List<User> users = service.findAll(); // 2.将list存进request域 request.setAttribute("users",users); //3. 转发到list.jsp request.getRequestDispatcher("/list.jsp").forward(request,response); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
list页面提供的添加联系人的jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!-- HTML5文档--> <!DOCTYPE html> <!-- 网页使用的语言 --> <html lang="zh-CN"> <head> <!-- 指定字符集 --> <meta charset="utf-8"> <!-- 使用Edge最新的浏览器的渲染方式 --> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。 width: 默认宽度与设备的宽度相同 initial-scale: 初始的缩放比,为1:1 --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --> <title>添加用户</title> <!-- 1. 导入CSS的全局样式 --> <link href="css/bootstrap.min.css" rel="stylesheet"> <!-- 2. jQuery导入,建议使用1.9以上的版本 --> <script src="js/jquery-2.1.0.min.js"></script> <!-- 3. 导入bootstrap的js文件 --> <script src="js/bootstrap.min.js"></script> </head> <body> <div class="container"> <center><h3>添加联系人页面</h3></center> <form action="${pageContext.request.contextPath}/addServlet" method="post"> <div class="form-group"> <label for="name">姓名:</label> <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名"> </div> <div class="form-group"> <label>性别:</label> <input type="radio" name="gender" value="男" checked="checked"/>男 <input type="radio" name="gender" value="女"/>女 </div> <div class="form-group"> <label for="age">年龄:</label> <input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄"> </div> <div class="form-group"> <label for="jiguan">籍贯:</label> <select name="address" class="form-control" id="jiguan"> <option value="广东">广东</option> <option value="广西">广西</option> <option value="湖南">湖南</option> </select> </div> <div class="form-group"> <label for="qq">QQ:</label> <input type="text" id="qq" class="form-control" name="qq" placeholder="请输入QQ号码"/> </div> <div class="form-group"> <label for="email">Email:</label> <input type="text" class="form-control" name="email" placeholder="请输入邮箱地址" id="email"/> </div> <div class="form-group" style="text-align: center"> <input class="btn btn-primary" type="submit" value="提交" /> <input class="btn btn-default" type="reset" value="重置" /> <input class="btn btn-default" type="button" value="返回" /> </div> </form> </div> </body> </html>
进行添加信息的Servlet:
package web.servlet; import domain.User; import org.apache.commons.beanutils.BeanUtils; import service.UserService; import service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.util.Map; @WebServlet("/addServlet") public class addServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); Map<String, String[]> map = request.getParameterMap(); User user = new User(); try { BeanUtils.populate(user,map)A; } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } UserService service = new UserServiceImpl(); service.add(user); response.sendRedirect(request.getContextPath()+"/userListServlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
list页面提供删除按钮连接的Serlvet:
package web.servlet; import service.UserService; import service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/delServlet") public class delServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String id = request.getParameter("id"); UserService service = new UserServiceImpl(); service.del(id); response.sendRedirect(request.getContextPath()+"/userListServlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
list页面提供的删除选中处理的Servlet:
package web.servlet; import service.UserService; import service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/delSelectedServlet") public class delSelectedServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String[] uids = request.getParameterValues("uid"); UserService service = new UserServiceImpl(); service.delSelectedUser(uids); response.sendRedirect(request.getContextPath()+"/userListServlet"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
domain包中封装的用来进行分页查询的PageBean实体类:
package domain; import java.util.List; /** * 分页对象 */ public class PageBean<T> { private int totalCount; //总记录数 private int totalPage; //总页码 private List<T> list; // 每页的数据 private int currentPage; //当前页码 private int rows; // 每页显示的记录数 public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getRows() { return rows; } public void setRows(int rows) { this.rows = rows; } @Override public String toString() { return "PageBean{" + "totalCount=" + totalCount + ", totalPage=" + totalPage + ", list=" + list + ", currentPage=" + currentPage + ", rows=" + rows + '}'; } }
domain包下封装的User实体类:
package domain; public class User { private int id; private String name; private String gender; private int age; private String address; private String qq; private String email; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getId() { return id; } public void setId(int 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 int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getQq() { return qq; } public void setQq(String qq) { this.qq = qq; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", gender='" + gender + '\'' + ", age=" + age + ", address='" + address + '\'' + ", qq='" + qq + '\'' + ", email='" + email + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
service包下的UserService接口:
package service; import domain.PageBean; import domain.User; import java.util.List; import java.util.Map; /** * 用户管理的业务接口 */ public interface UserService { /** * 查询所有用户信息 * @return */ public List<User> findAll(); /** * 用户登录 * @param user * @return */ public User login(User user); /** * 添加用户 * @param user * @return */ public void add(User user); /** * 根据id删除 * @param id */ public void del(String id); /** * 根据id找用户 * @param id * @return */ User findUser(String id); void updateUser(User user); /** * 批量删除用户 * @param uids */ void delSelectedUser(String[] uids); /** * 分页条件查询 * @param currentPage * @param rows * @param condition * @return */ PageBean<User> findUserByPage(String currentPage, String rows, Map<String, String[]> condition); }
service包下UserService接口的实现类:
package service.impl; import dao.UserDao; import dao.impl.UserDaoImpl; import domain.PageBean; import domain.User; import service.UserService; import java.util.List; import java.util.Map; public class UserServiceImpl implements UserService{ UserDao dao = new UserDaoImpl(); @Override public List<User> findAll() { //调用dao来完成查询 return dao.findAll(); } @Override public User login(User user) { return dao.findUserByUsernameAndPassword(user.getUsername(),user.getPassword()); } @Override public void add(User user) { dao.add(user); } @Override public void del(String id) { dao.del(Integer.parseInt(id)); } @Override public User findUser(String id) { return dao.findUserById(Integer.parseInt(id)); } @Override public void updateUser(User user) { dao.updateUser(user); } @Override public void delSelectedUser(String[] uids) { if (uids != null && uids.length > 0) { // 1. 遍历数组 for (String uid : uids) { dao.del(Integer.parseInt(uid)); } } } @Override public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) { int currentPage = Integer.parseInt(_currentPage); int rows = Integer.parseInt(_rows); // 使第一页原地跳转 if(currentPage<=0){ currentPage=1; } //1. 创建一个空的pageBean对象 PageBean<User> pb = new PageBean<User>(); //2. 设置参数 pb.setCurrentPage(currentPage); pb.setRows(rows); //3. 调用dao查询总记录数 int totalCount = dao.findTotalCount(condition); pb.setTotalCount(totalCount); //4. 调用dao查询List集合 //计算开始的记录索引 int start = (currentPage - 1) * rows; List<User> list = dao.findByPage(start,rows,condition); pb.setList(list); //5. 计算总页码 int totalPage = (totalCount % rows) == 0 ? totalCount/rows : (totalCount/rows) + 1; pb.setTotalPage(totalPage); return pb; } }
dao包下UserDao接口:
package dao; import domain.User; import java.util.List; import java.util.Map; /** * 用户操作的DAO */ public interface UserDao { public List<User> findAll(); public User findUserByUsernameAndPassword(String username,String password); public void add(User user); public void del(int id); User findUserById(int id); void updateUser(User user); /** * 查询总记录数 * @return * @param condition */ int findTotalCount(Map<String, String[]> condition); /** * 分页查询每页记录 * @param start * @param rows * @param condition * @return */ List<User> findByPage(int start, int rows, Map<String, String[]> condition); }
dao包下UserDao的实现类:
package dao.impl; import dao.UserDao; import domain.User; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import util.JDBCUtils; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public class UserDaoImpl implements UserDao { private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); @Override public List<User> findAll() { // 使用JDBC操作数据库 //1.定义sql String sql = "select * from user"; List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class)); return users; } @Override public User findUserByUsernameAndPassword(String username,String password) { try{ String sql = "select * from user where username =? and password = ?"; User login_user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class),username,password); return login_user; }catch (Exception e){ e.printStackTrace(); return null; } } @Override public void add(User user) { String name = user.getName(); String gender = user.getGender(); int age = user.getAge(); String address = user.getAddress(); String qq = user.getQq(); String email = user.getEmail(); String sql = "insert into user values(null,?,?,?,?,?,?,null,null)"; template.update(sql,name,gender,age,address,qq,email); } @Override public void del(int id) { String sql = "delete from user where id = ?"; template.update(sql,id); } @Override public User findUserById(int id) { String sql = "select * from user where id = ?"; User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id); return user; } @Override public void updateUser(User user) { String sql = "update user set name = ?,gender = ?,age = ?,address = ?,qq = ?,email = ? where id = ?"; template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getId()); } @Override public int findTotalCount(Map<String, String[]> condition) { //1. 定义模板初始化sql String sql = "select count(*) from user where 1 = 1"; StringBuilder sb = new StringBuilder(sql); //2. 遍历map Set<String> keySet = condition.keySet(); //定义参数的集合,后期将value放入 List<Object> params = new ArrayList<Object>(); for (String key : keySet) { // 排除分页条件参数 if("currentPage".equals(key) || "rows".equals(key)){ continue; } // 获取value String value = condition.get(key)[0]; // 判断value是否有值 if(value != null && !"".equals(value)){ //有值,注意空格 sb.append(" and " + key+ " like ? "); //加了几次,就加入集合几个value params.add("%"+value+"%");//?条件的参数 } } System.out.println(sb.toString()); System.out.println(params); return template.queryForObject(sb.toString(),Integer.class,params.toArray()); } @Override public List<User> findByPage(int start, int rows, Map<String, String[]> condition) { String sql = "select * from user where 1 = 1"; StringBuilder sb = new StringBuilder(sql); //2. 遍历map Set<String> keySet = condition.keySet(); //定义参数的集合,后期将value放入 List<Object> params = new ArrayList<Object>(); for (String key : keySet) { // 排除分页条件参数 if("currentPage".equals(key) || "rows".equals(key)){ continue; } // 获取value String value = condition.get(key)[0]; // 判断value是否有值 if(value != null && !"".equals(value)){ //有值,注意空格 sb.append(" and " + key+ " like ? "); //加了几次,就加入集合几个value params.add("%"+value+"%");//?条件的参数 } } //添加分页的查询 sb.append(" limit ?, ?"); //添加分页查询的参数 params.add(start); params.add(rows); sql = sb.toString(); return template.query(sql,new BeanPropertyRowMapper<User>(User.class),params.toArray()); } }
util包下对JDBCTemplate工具类进行的封装:
package util; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import javax.xml.crypto.Data; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; /** * JDBC工具类 使用Durid连接池 */ public class JDBCUtils { private static DataSource ds ; static { try { //1.加载配置文件 Properties pro = new Properties(); //使用ClassLoader加载配置文件,获取字节输入流 InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //2.初始化连接池对象 ds = DruidDataSourceFactory.createDataSource(pro); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } /** * 获取连接池对象 */ public static DataSource getDataSource(){ return ds; } /** * 获取连接Connection对象 */ public static Connection getConnection() throws SQLException { return ds.getConnection(); } }
数据库连接的配置properties:
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/day17 username=root password=woaini1314 # 初始化连接数量 initialSize=5 # 最大连接数 maxActive=10 # 最大等待时间 maxWait=3000