Java–小项目(登录、增删改查、分页、搜索)
博客说明
文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!
概念 技术选型 Servlet、JSP、MySQL、JDBCTempleat、Duird、BeanUtilS、tomcat
功能介绍 登录功能,列表展示,数据添加,数据编辑,数据删除,批量删除,分页展示,关键字搜索
创建JavaWeb项目
导入依赖
添加页面文件
数据库 1 2 3 4 5 6 7 8 9 10 11 12 13 create database little ; use little ; create table user ( id int primary key auto_increment, name varchar (20 ) not null , gender varchar (5 ), age int , address varchar (32 ), qq varchar (20 ), email varchar (50 , username varchar (32 ), password varchar (32 ), );
列表展示 思路 首先我们需要一组列表的数据,那么我们就需要一个相对应servlet,通过我们的三层架构,使用service同一做接口,然后调用dao层使用JBDC操作数据库,这样我们可以获得一个map集合的数据,然后就是渲染数据到jsp页面了,通过JSTL和EL把数据循环渲染到表里面,达到列表的展示
list.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 <%-- Created by IntelliJ IDEA. User: tanglei Date: 2020 /6 /28 Time: 下午2 :15 To change this template use File | Settings | File Templates. --%> <%@ 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> </head> <body> <div class ="container" > <h3 style="text-align: center">用户信息列表</h3> <table border="1" class ="table table-bordered table-hover" > <tr class ="success" > <th>编号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> <th>籍贯</th> <th>QQ</th> <th>邮箱</th> <th>操作</th> </tr> <c:forEach items="${users}" var ="user" varStatus="s" > <tr> <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="update.html">修改</a> <a class="btn btn-default btn-sm" href="">删除</a></td> </tr> </c:forEach> <tr> <td colspan="8" align="center"><a class="btn btn-primary" href="add.html">添加联系人</a></td> </tr> </table> </div> </body> </html>
servlet 代码文件很多,就不一一展示了
UserListServlet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 package cn.guizimo.little.web.servlet;import cn.guizimo.little.domain.User;import cn.guizimo.little.service.UserService;import cn.guizimo.little.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 { @Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { UserService userService = new UserServiceImpl(); List<User> users = userService.findAll(); req.setAttribute("users" ,users); req.getRequestDispatcher("/list.jsp" ).forward(req,resp); } @Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this .doPost(req, resp); } }
测试
登录 思路 登录功能首先就是对表单提交的数据进行比对,验证码可以在生成的时候就把它存入到session中,然后在servlet中进行比对,其他的字段在通过调用dao层的JDBC操作数据库进行比对,最后把登录成功的用户信息存入session中
login.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 <%-- Created by IntelliJ IDEA. User: tanglei Date: 2020 /6 /28 Time: 下午7 :37 To change this template use File | Settings | File Templates. --%> <%@ 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 () { let vcode = document.getElementById("vcode" ); vcode.src = "${pageContext.request.contextPath}/checkCodeServlet?=" + 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 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 package cn.guizimo.little.web.servlet;import cn.guizimo.little.domain.User;import cn.guizimo.little.service.UserService;import cn.guizimo.little.service.impl.UserServiceImpl;import org.apache.commons.beanutils.BeanUtils;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 { @Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8" ); String verifycode = req.getParameter("verifycode" ); HttpSession session = req.getSession(); String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER" ); session.removeAttribute("CHECKCODE_SERVER" ); if (!checkcode_server.equalsIgnoreCase(verifycode)) { req.setAttribute("login_msg" , "验证码错误" ); req.getRequestDispatcher("/login.jsp" ).forward(req, resp); return ; } Map<String, String[]> parameterMap = req.getParameterMap(); User user = new User(); try { BeanUtils.populate(user, parameterMap); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } UserService userService = new UserServiceImpl(); User loginUser = userService.login(user); if (loginUser != null ){ session.setAttribute("user" ,loginUser); resp.sendRedirect(req.getContextPath()+"/index.jsp" ); }else { req.setAttribute("login_msg" , "登录失败" ); req.getRequestDispatcher("/login.jsp" ).forward(req, resp); } } @Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this .doPost(req, resp); } }
CheckCodeServlet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 package cn.guizimo.little.web.servlet;import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.IOException;import java.util.Random;import javax.imageio.ImageIO;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@WebServlet ("/checkCodeServlet" )public class CheckCodeServlet extends HttpServlet { public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("pragma" ,"no-cache" ); response.setHeader("cache-control" ,"no-cache" ); response.setHeader("expires" ,"0" ); int width = 80 ; int height = 30 ; BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); Graphics g = image.getGraphics(); g.setColor(Color.GRAY); g.fillRect(0 ,0 , width,height); String checkCode = getCheckCode(); request.getSession().setAttribute("CHECKCODE_SERVER" ,checkCode); g.setColor(Color.YELLOW); g.setFont(new Font("黑体" ,Font.BOLD,24 )); g.drawString(checkCode,15 ,25 ); ImageIO.write(image,"PNG" ,response.getOutputStream()); } private String getCheckCode () { String base = "0123456789ABCDEFGabcdefg" ; int size = base.length(); Random r = new Random(); StringBuffer sb = new StringBuffer(); for (int i=1 ;i<=4 ;i++){ int index = r.nextInt(size); char c = base.charAt(index); sb.append(c); } return sb.toString(); } public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this .doGet(request,response); } }
测试
添加人员 思路 添加操作就是把jsp提交的表单的数据向数据库里面存储,过程为jsp->servlet->service->dao
add.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 <%-- Created by IntelliJ IDEA. User: tanglei Date: 2020 /6 /28 Time: 下午8 :55 To change this template use File | Settings | File Templates. --%> <%@ 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}/addUserServlet" 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="address">籍贯:</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" 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="请输入邮箱地址" /> </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>
AddUserServlet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 package cn.guizimo.little.web.servlet;import cn.guizimo.little.domain.User;import cn.guizimo.little.service.UserService;import cn.guizimo.little.service.impl.UserServiceImpl;import org.apache.commons.beanutils.BeanUtils;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 ("/addUserServlet" )public class AddUserServlet extends HttpServlet { @Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8" ); Map<String, String[]> parameterMap = req.getParameterMap(); User user = new User(); try { BeanUtils.populate(user,parameterMap); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } UserService userService = new UserServiceImpl(); userService.addUser(user); resp.sendRedirect(req.getContextPath()+"/userListServlet" ); } @Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this .doPost(req, resp); } }
测试
修改 思路 首先我们需要在打开jsp页面的时候就查询到这样的一条记录,通过这一条记录的id作为表单的隐藏域,在servlet里面将数据进行保存即可
update.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 <%-- Created by IntelliJ IDEA. User: tanglei Date: 2020 /6 /29 Time: 上午10 :44 To change this template use File | Settings | File Templates. --%> <%@ 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}/updateUserServlet" method="post" > <!-- 隐藏域 提交id--> <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> <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" value="${user.age}" id="age" name="age" placeholder="请输入年龄" /> </div> <div class ="form-group" > <label for="address">籍贯:</label> <select name="address" id="address" class ="form-control" > <c:if test="${user.address == '陕西'}" > <option value="陕西" selected>陕西</option> <option value="北京">北京</option> <option value="上海">上海</option> </c:if> <c:if test="${user.address == '北京'}" > <option value="陕西" >陕西</option> <option value="北京" selected>北京</option> <option value="上海">上海</option> </c:if> <c:if test="${user.address == '上海'}" > <option value="陕西" >陕西</option> <option value="北京">北京</option> <option value="上海" selected>上海</option> </c:if> </select> </div> <div class ="form-group" > <label for="qq">QQ:</label> <input type="text" id="qq" class ="form-control" value="${user.qq}" name="qq" placeholder="请输入QQ号码" /> </div> <div class ="form-group" > <label for="email">Email:</label> <input type="text" id="email" class ="form-control" value="${user.email}" name="email" placeholder="请输入邮箱地址" /> </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="重置" /> <a class="btn btn-default" href="${pageContext.request.contextPath}/userListServlet">返回</a> </div> </form> </div> </body> </html>
FindUserServlet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package cn.guizimo.little.web.servlet;import cn.guizimo.little.domain.User;import cn.guizimo.little.service.UserService;import cn.guizimo.little.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 { @Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id" ); UserService service = new UserServiceImpl(); User user = service.findUserById(id); req.setAttribute("user" ,user); req.getRequestDispatcher("/update.jsp" ).forward(req,resp); } @Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this .doPost(req, resp); } }
UpdateUserServlet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 package cn.guizimo.little.web.servlet;import cn.guizimo.little.domain.User;import cn.guizimo.little.service.UserService;import cn.guizimo.little.service.impl.UserServiceImpl;import org.apache.commons.beanutils.BeanUtils;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 ("/updateUserServlet" )public class UpdateUserServlet extends HttpServlet { @Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8" ); Map<String, String[]> map = req.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); resp.sendRedirect(req.getContextPath()+"/userListServlet" ); } @Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this .doPost(req, resp); } }
测试
删除 思路 通过获取到对应的id即可到servlet中处理,操作数据库删除,在进行删除的时候可出现提示框
DelUserServlet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 package cn.guizimo.little.web.servlet;import cn.guizimo.little.service.UserService;import cn.guizimo.little.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 ("/delUserServlet" )public class DelUserServlet extends HttpServlet { @Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id" ); UserService service = new UserServiceImpl(); service.deleteUser(id); resp.sendRedirect(req.getContextPath()+"/userListServlet" ); } @Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this .doPost(req, resp); } }
测试
删除选择的多个 思路 和删除差不多,最主要是获取id的集合
DelSelectedServlet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 package cn.guizimo.little.web.servlet;import cn.guizimo.little.service.UserService;import cn.guizimo.little.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 { @Override protected void doPost (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String[] ids = req.getParameterValues("uid" ); UserService service = new UserServiceImpl(); service.delSelectedUser(ids); resp.sendRedirect(req.getContextPath()+"/userListServlet" ); } @Override protected void doGet (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this .doPost(req, resp); } }
测试
分页 思路 在jsp中获取查询的总条数,每页显示的条数,当前的页码,将之传递给服务器,操作数据库进行查询
list.jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 <%-- Created by IntelliJ IDEA. User: tanglei Date: 2020 /6 /28 Time: 下午2 :15 To change this template use File | Settings | File Templates. --%> <%@ 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 deleteUser (id) { if (confirm("您确定要删除吗?" )) { location.href = "${pageContext.request.contextPath}/delUserServlet?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("form" ).submit(); } } } document.getElementById("firstCb" ).onclick = function () { var cbs = document.getElementsByName("uid" ); for (var i = 0 ; i < cbs.length; i++) { 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" > <label for="exampleInputName2">姓名</label> <input type="text" name="name" value="${condition.name[0]}" class ="form-control" id="exampleInputName2" > </div> <div class ="form-group" > <label for="exampleInputName3">籍贯</label> <input type="text" name="address" value="${condition.address[0]}" class ="form-control" id="exampleInputName3" > </div> <div class ="form-group" > <label for="exampleInputEmail2">邮箱</label> <input type="text" name="email" value="${condition.email[0]}" class ="form-control" id="exampleInputEmail2" > </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> <a class="btn btn-primary" href="javascript:void(0);" id="delSelected">删除选中</a> </div> <form id="form" 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> <td><input type="checkbox" name="uid" value="${user.id}"></td> <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:deleteUser(${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="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=1&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Previous" > <span aria-hidden="true">«</span> </a> </li> </c:if> <c:if test="${pb.currentPage != 1}" > <li> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage - 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Previous" > <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> <c:if test="${pb.currentPage == pb.totalPage}" > <li class ="disabled" > <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.totalPage}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next" > <span aria-hidden="true">»</span> </a> </li> </c:if> <c:if test="${pb.currentPage != pb.totalPage}" > <li> <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next" > <span aria-hidden="true">»</span> </a> </li> </c:if> <span style="font-size: 25px;margin-left: 5px;" > 共${pb.totalCount}条记录,共${pb.totalPage}页 </span> </ul> </nav> </div> </div> </body> </html>
FindUserByPageServlet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 package cn.guizimo.little.web.servlet;import cn.guizimo.little.domain.PageBean;import cn.guizimo.little.domain.User;import cn.guizimo.little.service.UserService;import cn.guizimo.little.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" ); 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(); UserService service = new UserServiceImpl(); PageBean<User> pb = service.findUserByPage(currentPage,rows,condition); System.out.println(pb); request.setAttribute("pb" ,pb); request.setAttribute("condition" ,condition); request.getRequestDispatcher("/list.jsp" ).forward(request,response); } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this .doPost(request, response); } }
测试
条件查询 思路 主要是在sql语句的编写
jsp 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <div style="float: left;" > <form class ="form-inline" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post" > <div class ="form-group" > <label for="exampleInputName2">姓名</label> <input type="text" name="name" value="${condition.name[0]}" class ="form-control" id="exampleInputName2" > </div> <div class ="form-group" > <label for="exampleInputName3">籍贯</label> <input type="text" name="address" value="${condition.address[0]}" class ="form-control" id="exampleInputName3" > </div> <div class ="form-group" > <label for="exampleInputEmail2">邮箱</label> <input type="text" name="email" value="${condition.email[0]}" class ="form-control" id="exampleInputEmail2" > </div> <button type="submit" class="btn btn-default">查询</button> </form> </div>
dao层方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 @Override public int findTotalCount (Map<String, String[]> condition) { String sql = "select count(*) from user where 1 = 1 " ; StringBuilder sb = new StringBuilder(sql); Set<String> keySet = condition.keySet(); List<Object> params = new ArrayList<Object>(); for (String key : keySet) { if ("currentPage" .equals(key) || "rows" .equals(key)){ continue ; } String value = condition.get(key)[0 ]; if (value != null && !"" .equals(value)){ sb.append(" and " +key+" like ? " ); 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); Set<String> keySet = condition.keySet(); List<Object> params = new ArrayList<Object>(); for (String key : keySet) { if ("currentPage" .equals(key) || "rows" .equals(key)){ continue ; } String value = condition.get(key)[0 ]; if (value != null && !"" .equals(value)){ sb.append(" and " +key+" like ? " ); params.add("%" +value+"%" ); } } sb.append(" limit ?,? " ); params.add(start); params.add(rows); sql = sb.toString(); System.out.println(sql); System.out.println(params); return template.query(sql,new BeanPropertyRowMapper<User>(User.class ),params .toArray ()) ; }
测试
感谢
黑马程序员
万能的网络
以及勤劳的自己