黑马第1个案例 登录验证 增删改查 条件查询+分页

 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: jie
 4   Date: 2019/5/12
 5   Time: 9:01
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
10 <!DOCTYPE html>
11 <html lang="zh-CN">
12 <head>
13     <meta charset="utf-8"/>
14     <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
15     <meta name="viewport" content="width=device-width, initial-scale=1"/>
16     <title>管理员登录</title>
17 
18     <!-- 1. 导入CSS的全局样式 -->
19     <link href="css/bootstrap.min.css" rel="stylesheet">
20     <!-- 2. jQuery导入,建议使用1.9以上的版本 -->
21     <script src="js/jquery-2.1.0.min.js"></script>
22     <!-- 3. 导入bootstrap的js文件 -->
23     <script src="js/bootstrap.min.js"></script>
24     <script type="text/javascript">
25         function refreshCode(){
26             //切换验证码
27             /*
28                 获取验证码图片对象
29                 设置其src,加上时间戳
30 
31              */
32             var vcode = document.getElementById("vcode");
33             vcode.src = "${pageContext.request.contextPath}/checkCodeServlet?time=" + new Date().getTime();
34         }
35     </script>
36 </head>
37 <body>
38 <div class="container" style="width: 400px;">
39     <h3 style="text-align: center;">管理员登录</h3>
40     <form action="${pageContext.request.contextPath}/loginServlet" method="post">
41         <div class="form-group">
42             <label for="user">用户名:</label>
43             <input type="text" name="username" class="form-control" id="user" placeholder="请输入用户名"/>
44         </div>
45 
46         <div class="form-group">
47             <label for="password">密码:</label>
48             <input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/>
49         </div>
50 
51         <div class="form-inline">
52             <label for="vcode">验证码:</label>
53             <input type="text" name="verifycode" class="form-control" id="verifycode" maxlength="4" placeholder="请输入验证码" style="width: 120px;"/>
54             <a href="javascript:refreshCode()"><img src="${pageContext.request.contextPath}/checkCodeServlet" title="看不清点击刷新" id="vcode"/></a>
55         </div>
56         <hr/>
57         <div class="form-group" style="text-align: center;">
58             <input class="btn btn btn-primary" type="submit" value="登录">
59         </div>
60     </form>
61 
62     <!-- 出错显示的信息框 -->
63     <c:if test="${loginMsg != null}">
64         <div class="alert alert-warning alert-dismissible" role="alert">
65             <button type="button" class="close" data-dismiss="alert" >
66                 <span>&times;</span></button>
67             <strong>${loginMsg}</strong>
68         </div>
69     </c:if>
70 </div>
71 </body>
72 </html>
login.jsp
  1 <%--
  2   Created by IntelliJ IDEA.
  3   User: jie
  4   Date: 2019/5/10
  5   Time: 20:00
  6   To change this template use File | Settings | File Templates.
  7 --%>
  8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 10 <!DOCTYPE html>
 11 <!-- 网页使用的语言 -->
 12 <html lang="zh-CN">
 13 <head>
 14     <!-- 指定字符集 -->
 15     <meta charset="utf-8">
 16     <!-- 使用Edge最新的浏览器的渲染方式 -->
 17     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 18     <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
 19     width: 默认宽度与设备的宽度相同
 20     initial-scale: 初始的缩放比,为1:1 -->
 21     <meta name="viewport" content="width=device-width, initial-scale=1">
 22     <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
 23     <title>用户信息管理系统</title>
 24 
 25     <!-- 1. 导入CSS的全局样式 -->
 26     <link href="css/bootstrap.min.css" rel="stylesheet">
 27     <!-- 2. jQuery导入,建议使用1.9以上的版本 -->
 28     <script src="js/jquery-2.1.0.min.js"></script>
 29     <!-- 3. 导入bootstrap的js文件 -->
 30     <script src="js/bootstrap.min.js"></script>
 31     <style type="text/css">
 32         td, th {
 33             text-align: center;
 34         }
 35         .mb-10{
 36             margin-bottom: 10px;
 37         }
 38         .float-right{
 39             float: right;
 40         }
 41         .float-left{
 42             float: left;
 43         }
 44         .tool::after{
 45             content: '';
 46             display: block;
 47             clear: both;
 48         }
 49         .table>tbody>tr>td{
 50             vertical-align: middle;
 51         }
 52         .total-page{
 53             margin-top: 5px;
 54             display: inline-block;
 55             margin-left: 15px;
 56             font-size: 16px;
 57         }
 58         .pageSize{
 59             display: inline-block;
 60             width: auto;
 61             margin: 0px 10px;
 62         }
 63         .jumpPage{
 64             display: inline-block;
 65             width: 50px;
 66         }
 67     </style>
 68     <script>
 69 
 70         window.onload = function () {
 71             /*
 72                 全选和全部选功能实现
 73                     1为firstCb绑定单击事件
 74                     3获取所有的复选框,将其状态设置为和firstCb一致
 75              */
 76             var firstCb = document.getElementById("firstCb");
 77             // console.log(firstCb.checked);
 78             firstCb.onclick = function () {
 79                 // firstCb.checked = !firstCb.checked;
 80                 var ids = document.getElementsByName("id");
 81                 for (var i = 0; i < ids.length; i++) {
 82                     ids[i].checked = firstCb.checked;
 83                 }
 84             }
 85 
 86             /*
 87                 设置页的大小
 88              */
 89             document.getElementById("pageSizeSelect").onchange = function(){
 90                 //手动提交查询条件表单
 91                 document.getElementById("searchForm").submit();
 92             };
 93             /*
 94                 页大小控制的回显
 95              */
 96             var pageSizeOptions = document.getElementById("pageSizeSelect").options;
 97             for (var i = 0; i < pageSizeOptions.length; i++) {
 98                 if(pageSizeOptions[i].value == "${userPage.pageSize}"){
 99                     pageSizeOptions[i].selected = true;
100                 }
101             }
102             /*
103                 页面跳转
104              */
105             document.getElementById("jumpPage").onkeydown = function (ev) {
106                 if(ev.keyCode == 13){
107                     //按下回车,将currentPage元素的值设置为输入框的值
108                     // var currentPage = document.getElementById("jumpPage").value;
109                     // var currentPageEle = document.getElementById("currentPage");
110                     // currentPageEle.value = currentPage;
111                     var currentPageValue = document.getElementById("jumpPage").value;
112                     //验证输入页码是否是数字
113                     if(currentPageValue.match(/^\d+$/)){
114                         //是数字,提交表单
115                         document.getElementById("currentPage").value = currentPageValue;
116                         //提交表单
117                         document.getElementById("searchForm").submit();
118                     }else{
119                         //不是数字,清空输入内容
120                         document.getElementById("jumpPage").value = "";
121                     }
122                 }
123             }
124         }
125         function  deleteUser(id) {
126             if(confirm("确定要删除改用户吗?")){
127                 location.href = "/deleteServlet?id=" + id;
128             }
129         }
130         function submitDelSelected(){
131             //判断是否选择了删除项
132             var hasSelected = false;
133             var ids = document.getElementsByName("id");
134             for (var i = 0; i < ids.length; i++) {
135                 if(ids[i].checked == true){
136                     hasSelected = true;
137                     break;
138                 }
139             }
140             if(hasSelected){
141                 //需要用户确认
142                 if(confirm("确定要删除这些用户吗?")){
143                     document.getElementById("delSelectedForm").submit();
144                 }
145             }else{
146                 //给出还没有选择的提示
147                 confirm("请先选择需要删除的用户");
148             }
149         }
150     </script>
151 </head>
152 <body>
153 <div class="container">
154 
155     <h3 style="text-align: center">用户信息列表</h3>
156 
157     <%--<div class="btn-group" role="group" aria-label="...">--%>
158         <%--<button type="button" class="btn btn-default">Left</button>--%>
159         <%--<button type="button" class="btn btn-default">Middle</button>--%>
160         <%--<button type="button" class="btn btn-default">Right</button>--%>
161     <%--</div>--%>
162     <div class="tool mb-10">
163         <form id="searchForm" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post" class="form-inline float-left">
164             <input type="hidden" id="currentPage" name="currentPage" value="${userPage.currentPage}">
165             <div class="form-group">
166                 <label for="name">姓名</label>
167                 <input type="text" value="${searchCondition.name[0]}" class="form-control" id="name" name="name">
168             </div>
169             <div class="form-group">
170                 <label for="address">籍贯</label>
171                 <input type="text" class="form-control" value="${searchCondition.address[0]}" id="address" name="address">
172             </div>
173             <div class="form-group">
174                 <label for="email">邮箱</label>
175                 <input type="email" class="form-control" value="${searchCondition.email[0]}" id="email" name="email">
176             </div>
177             <button type="submit" class="btn btn-default">查询</button>
178         </form>
179         <div class="right-tool float-right">
180             <a class="btn btn-primary" href="add.jsp" role="button">添加联系人</a>
181             <a class="btn btn-primary" href="javascript: submitDelSelected();" role="button">删除选中</a>
182             <form action="${pageContext.request.contextPath}/delSelectedServlet" method="post" id="delSelectedForm"></form>
183             <%--<button type="button" class="btn btn-primary">添加联系人</button>--%>
184             <%--<button type="button" class="btn btn-primary">删除选中</button>--%>
185         </div>
186     </div>
187     <table border="1" class="table table-bordered table-hover">
188         <tr class="success">
189             <th><input type="checkbox" id="firstCb"></th>
190             <th>编号</th>
191             <th>姓名</th>
192             <th>性别</th>
193             <th>年龄</th>
194             <th>籍贯</th>
195             <th>QQ</th>
196             <th>邮箱</th>
197             <th>操作</th>
198         </tr>
199         <c:forEach items="${userPage.pageData}" var="user" varStatus="vs">
200             <tr>
201                 <td><input form="delSelectedForm" type="checkbox" name="id" value="${user.id}"></td>
202                 <td>${vs.count}</td>
203                 <td>${user.name}</td>
204                 <td>${user.gender}</td>
205                 <td>${user.age}</td>
206                 <td>${user.address}</td>
207                 <td>${user.qq}</td>
208                 <td>${user.email}</td>
209                 <td><a class="btn btn-default btn-sm" href="/findUserServlet?id=${user.id}">修改</a>&nbsp;<a class="btn btn-default btn-sm" href="javascript: deleteUser(${user.id});">删除</a></td>
210             </tr>
211         </c:forEach>
212     </table>
213 
214     <nav>
215         <ul class="pagination">
216             <c:if test="${userPage.currentPage == 1}">
217                 <li class="disabled">
218             </c:if>
219             <c:if test="${userPage.currentPage != 1}">
220                 <li>
221             </c:if>
222                     <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${userPage.currentPage - 1}&pageSize=${userPage.pageSize}&name=${searchCondition.name[0]}&address=${searchCondition.address[0]}&email=${searchCondition.email[0]}" aria-label="Previous">
223                         <span aria-hidden="true">&laquo;</span>
224                     </a>
225                 </li>
226             <c:forEach begin="1" end="${userPage.totalPage}" var="i">
227                 <c:if test="${userPage.currentPage == i}">
228                     <li class="active">
229                 </c:if>
230                 <c:if test="${userPage.currentPage != i}">
231                     <li>
232                 </c:if>
233                 <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&pageSize=${userPage.pageSize}&name=${searchCondition.name[0]}&address=${searchCondition.address[0]}&email=${searchCondition.email[0]}">${i}</a></li>
234             </c:forEach>
235             <c:if test="${userPage.currentPage == userPage.totalPage}">
236                 <li class="disabled">
237             </c:if>
238             <c:if test="${userPage.currentPage != userPage.totalPage}">
239                 <li>
240             </c:if>
241                 <a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${userPage.currentPage + 1}&pageSize=${userPage.pageSize}&name=${searchCondition.name[0]}&address=${searchCondition.address[0]}&email=${searchCondition.email[0]}" aria-label="Next">
242                     <span aria-hidden="true">&raquo;</span>
243                 </a>
244             </li>
245 
246             <span class="total-page">共${userPage.totalCount}条记录,共${userPage.totalPage}页</span>
247             <select form="searchForm" id="pageSizeSelect" name="pageSize" class="pageSize form-control">
248                 <option value="3">3</option>
249                 <option value="5">5</option>
250                 <option value="8">8</option>
251                 <option value="10">10</option>
252                 <option value="15">15</option>
253             </select>
254         </ul>
255         跳转到 <input id="jumpPage" class="form-control jumpPage" type="text">
256     </nav>
257 </div>
258 </body>
259 </html>
List.jsp
 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: jie
 4   Date: 2019/5/10
 5   Time: 20:53
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <!-- HTML5文档-->
10 <!DOCTYPE html>
11 <!-- 网页使用的语言 -->
12 <html lang="zh-CN">
13 <head>
14     <!-- 指定字符集 -->
15     <meta charset="utf-8">
16     <!-- 使用Edge最新的浏览器的渲染方式 -->
17     <meta http-equiv="X-UA-Compatible" content="IE=edge">
18     <!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。
19     width: 默认宽度与设备的宽度相同
20     initial-scale: 初始的缩放比,为1:1 -->
21     <meta name="viewport" content="width=device-width, initial-scale=1">
22     <!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
23     <title>添加用户</title>
24 
25     <!-- 1. 导入CSS的全局样式 -->
26     <link href="css/bootstrap.min.css" rel="stylesheet">
27     <!-- 2. jQuery导入,建议使用1.9以上的版本 -->
28     <script src="js/jquery-2.1.0.min.js"></script>
29     <!-- 3. 导入bootstrap的js文件 -->
30     <script src="js/bootstrap.min.js"></script>
31     <style>
32         .error{
33             width: 400px;
34             height: 50px;
35             margin: auto;
36             border-radius: 10px;
37             box-shadow: 0px 0px 2px;
38         }
39     </style>
40 </head>
41 <body>
42 <div class="container">
43     <center><h3>添加联系人页面</h3></center>
44     <form action="${pageContext.request.contextPath}/addUserServlet" method="post">
45         <div class="form-group">
46             <label for="name">姓名:</label>
47             <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
48         </div>
49 
50         <div class="form-group">
51             <label>性别:</label>
52             <input type="radio" name="gender" value="男" checked="checked"/>53             <input type="radio" name="gender" value="女"/>54         </div>
55 
56         <div class="form-group">
57             <label for="age">年龄:</label>
58             <input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄">
59         </div>
60 
61         <div class="form-group">
62             <label for="address">籍贯:</label>
63             <select name="address" class="form-control" id="address">
64                 <option value="广东">广东</option>
65                 <option value="广西">广西</option>
66                 <option value="湖南">湖南</option>
67             </select>
68         </div>
69 
70         <div class="form-group">
71             <label for="qq">QQ:</label>
72             <input type="text" id="qq" class="form-control" name="qq" placeholder="请输入QQ号码"/>
73         </div>
74 
75         <div class="form-group">
76             <label for="email">Email:</label>
77             <input type="text" id="email" class="form-control" name="email" placeholder="请输入邮箱地址"/>
78         </div>
79 
80         <div class="form-group" style="text-align: center">
81             <input class="btn btn-primary" type="submit" value="提交" />
82             <input class="btn btn-default" type="reset" value="重置" />
83             <input id="return" class="btn btn-default" type="button" value="返回" />
84             <%--<a class="btn btn-default" href="${pageContext.request.contextPath}/findUserByPageServlet" role="button">返回</a>--%>
85         </div>
86     </form>
87     <div class="error">
88         ${error}
89     </div>
90 </div>
91 <script>
92     document.getElementById("return").onclick = function (ev) {
93         location.href = "${pageContext.request.contextPath}/findUserByPageServlet";
94     }
95 </script>
96 </body>
97 </html>
add.jsp
  1 <%--
  2   Created by IntelliJ IDEA.
  3   User: jie
  4   Date: 2019/5/10
  5   Time: 22:13
  6   To change this template use File | Settings | File Templates.
  7 --%>
  8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 10 <!DOCTYPE html>
 11 <!-- 网页使用的语言 -->
 12 <html lang="zh-CN">
 13 <head>
 14     <!-- 指定字符集 -->
 15     <meta charset="utf-8">
 16     <meta http-equiv="X-UA-Compatible" content="IE=edge">
 17     <meta name="viewport" content="width=device-width, initial-scale=1">
 18     <title>修改用户</title>
 19 
 20     <link href="css/bootstrap.min.css" rel="stylesheet">
 21     <script src="js/jquery-2.1.0.min.js"></script>
 22     <script src="js/bootstrap.min.js"></script>
 23     <script>
 24 
 25         window.onload = function(){
 26             /*
 27                 使用js完成修改页面,省份数据回显
 28              */
 29             <%--var addressSelect = document.getElementById("address");--%>
 30             <%--for (var i = 0; i < addressSelect.options.length; i++) {--%>
 31                 <%--if(addressSelect.options[i].value == "${user.address}")--%>
 32                     <%--addressSelect.options[i].selected = true;--%>
 33             <%--}--%>
 34             //下拉列表
 35             <%--var addressOptions = document.getElementById("address").options;--%>
 36             <%--for (var i = 0; i < addressOptions.length; i++) {--%>
 37                 <%--if(addressOptions[i].value == "${user.address}"){--%>
 38                     <%--addressOptions[i].selected = true;--%>
 39                     <%--break;--%>
 40                 <%--}--%>
 41 
 42             <%--}--%>
 43             <%--//单选--%>
 44             <%--var genderRadios = document.getElementsByName("gender");--%>
 45             <%--for (var i = 0; i < genderRadios.length; i++) {--%>
 46                 <%--//注意:一定要把${user.gender}放在引号里面,本质上是文本替换。--%>
 47                 <%--if(genderRadios[i].value == "${user.gender}"){--%>
 48                     <%--genderRadios[i].checked = true;--%>
 49                 <%--}--%>
 50             <%--}--%>
 51         }
 52 
 53     </script>
 54 </head>
 55 <body>
 56 <div class="container" style="width: 400px;">
 57     <h3 style="text-align: center;">修改联系人</h3>
 58     <form action="${pageContext.request.contextPath}/updateServlet" method="post">
 59         <input type="hidden" name="id" value="${user.id}">
 60         <div class="form-group">
 61             <label for="name">姓名:</label>
 62             <input type="text" class="form-control" id="name" name="name" value="${user.name}"/>
 63         </div>
 64 
 65         <div class="form-group">
 66             <label>性别:</label>
 67 
 68             <%--<input type="radio" name="gender" value="男" />男--%>
 69             <%--<input type="radio" name="gender" value="女" />女--%>
 70 
 71             <c:if test="${user.gender == '男'}">
 72                 <input type="radio" name="gender" value="男"  checked/> 73                 <input type="radio" name="gender" value="女"  /> 74             </c:if>
 75             <c:if test="${user.gender == '女'}">
 76                 <input type="radio" name="gender" value="男"  /> 77                 <input type="radio" name="gender" value="女" checked /> 78             </c:if>
 79             <c:if test="${user.gender != '女' && user.gender != '男'}">
 80                 <input type="radio" name="gender" value="男"  /> 81                 <input type="radio" name="gender" value="女"  /> 82             </c:if>
 83         </div>
 84 
 85         <div class="form-group">
 86             <label for="age">年龄:</label>
 87             <input type="text" class="form-control" id="age" value="${user.age}" name="age" placeholder="请输入年龄" />
 88         </div>
 89 
 90         <div class="form-group">
 91             <label for="address">籍贯:</label>
 92             <%--<select name="address" id="address" class="form-control" >--%>
 93 
 94                 <%--<c:if test="${user.address == '广东'}">--%>
 95                     <%--<option value="广东" selected >广东</option>--%>
 96                     <%--<option value="广西" >广西</option>--%>
 97                     <%--<option value="湖南" >湖南</option>--%>
 98                 <%--</c:if>--%>
 99                 <%--<c:if test="${user.address == '广西'}">--%>
100                     <%--<option value="广东" >广东</option>--%>
101                     <%--<option value="广西" selected>广西</option>--%>
102                     <%--<option value="湖南" >湖南</option>--%>
103                 <%--</c:if>--%>
104                 <%--<c:if test="${user.address == '湖南'}">--%>
105                     <%--<option value="广东" >广东</option>--%>
106                     <%--<option value="广西" >广西</option>--%>
107                     <%--<option value="湖南" selected>湖南</option>--%>
108                 <%--</c:if>--%>
109                 <%--<c:if test="${user.address != '广东' && user.address != '广西' && user.address != '湖南'}">--%>
110                     <%--<option value="广东" >广东</option>--%>
111                     <%--<option value="广西" >广西</option>--%>
112                     <%--<option value="湖南" >湖南</option>--%>
113                 <%--</c:if>--%>
114 
115             <%--</select>--%>
116             <select name="address" id="address" class="form-control" >
117                 <c:choose>
118                     <c:when test="${user.address == '广东'}">
119                         <option value="广东" selected >广东</option>
120                         <option value="广西" >广西</option>
121                         <option value="湖南" >湖南</option>
122                     </c:when>
123                     <c:when test="${user.address == '广西'}">
124                         <option value="广东"  >广东</option>
125                         <option value="广西" selected >广西</option>
126                         <option value="湖南" >湖南</option>
127                     </c:when>
128                     <c:when test="${user.address == '湖南'}">
129                         <option value="广东"  >广东</option>
130                         <option value="广西" >广西</option>
131                         <option value="湖南" selected >湖南</option>
132                     </c:when>
133                     <c:otherwise>
134                         <option value="广东" >广东</option>
135                         <option value="广西" >广西</option>
136                         <option value="湖南" >湖南</option>
137                     </c:otherwise>
138                 </c:choose>
139             </select>
140         </div>
141 
142         <div class="form-group">
143             <label for="qq">QQ:</label>
144             <input type="text" id="qq" class="form-control" value="${user.qq}" name="qq" placeholder="请输入QQ号码"/>
145         </div>
146 
147         <div class="form-group">
148             <label for="email">Email:</label>
149             <input type="text" id="email" class="form-control" value="${user.email}" name="email" placeholder="请输入邮箱地址"/>
150         </div>
151 
152         <div class="form-group" style="text-align: center">
153             <input class="btn btn-primary" type="submit" value="提交" />
154             <input class="btn btn-default" type="reset" value="重置" />
155             <input id="returnUserList" class="btn btn-default" type="button" value="返回"/>
156         </div>
157     </form>
158 </div>
159 <script>
160     document.getElementById("returnUserList").onclick = function (ev) {
161         location.href = "${pageContext.request.contextPath}/findUserByPageServlet";
162     }
163 </script>
164 </body>
165 </html>
update.jsp
 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: jie
 4   Date: 2019/5/9
 5   Time: 20:26
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <!DOCTYPE html>
10 <html lang="zh-CN">
11 <head>
12   <meta charset="utf-8"/>
13   <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
14   <meta name="viewport" content="width=device-width, initial-scale=1"/>
15   <title>首页</title>
16 
17   <!-- 1. 导入CSS的全局样式 -->
18   <link href="css/bootstrap.min.css" rel="stylesheet">
19   <!-- 2. jQuery导入,建议使用1.9以上的版本 -->
20   <script src="js/jquery-2.1.0.min.js"></script>
21   <!-- 3. 导入bootstrap的js文件 -->
22   <script src="js/bootstrap.min.js"></script>
23   <script type="text/javascript">
24   </script>
25 </head>
26 <body>
27 <div align="center">
28   <a
29           href="/findUserByPageServlet" style="text-decoration:none;font-size:33px">查询所有用户信息
30   </a>
31 </div>
32 </body>
33 </html>
index.jsp
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.User;
 4 import cn.itcast.service.impl.UserServiceImpl;
 5 import org.apache.commons.beanutils.BeanUtils;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import javax.servlet.http.HttpSession;
13 import java.io.IOException;
14 import java.lang.reflect.InvocationTargetException;
15 
16 @WebServlet("/loginServlet")
17 public class LoginServlet extends HttpServlet {
18     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19         /*
20             设置编码
21             校验验证码
22             获取参数
23             封装User
24             调用Service查询
25             判断是否登录成功
26          */
27         request.setCharacterEncoding("UTF-8");
28 
29         String verifycode = request.getParameter("verifycode");
30         HttpSession session = request.getSession();
31         String checkcodeSession = (String) session.getAttribute("CHECKCODE_SERVER");
32         session.removeAttribute("CHECKCODE_SERVER");
33         if(checkcodeSession == null || !checkcodeSession.equalsIgnoreCase(verifycode)){
34             //验证码不正确,给出提示信息,跳转到登录页面
35             request.setAttribute("loginMsg", "验证码错误");
36             request.getRequestDispatcher("/login.jsp").forward(request, response);
37             return;
38         }
39 
40         User loginCondition = new User();
41         try {
42             BeanUtils.populate(loginCondition, request.getParameterMap());
43         } catch (IllegalAccessException e) {
44             e.printStackTrace();
45         } catch (InvocationTargetException e) {
46             e.printStackTrace();
47         }
48 
49         UserServiceImpl userService = new UserServiceImpl();
50         User user = userService.login(loginCondition);
51         if(user != null){
52             request.getSession().setAttribute("user", user);
53             response.sendRedirect(request.getContextPath() + "/index.jsp");
54         }else{
55             //跳转到登录页面,给出用户名或密码错误提示
56             request.setAttribute("loginMsg", "用户名或密码错误");
57             request.getRequestDispatcher("/login.jsp").forward(request, response);
58         }
59     }
60 
61     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
62         doPost(request, response);
63     }
64 }
LoginServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.utils.GraphicHelper;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import java.io.IOException;
11 
12 @WebServlet("/checkCodeServlet")
13 public class CheckCodeServlet extends HttpServlet {
14     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
15         String checkcode = GraphicHelper.create(80, 40, "jpg", response.getOutputStream());
16         request.getSession().setAttribute("CHECKCODE_SERVER", checkcode);
17     }
18 
19     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
20         doPost(request, response);
21     }
22 }
CheckCodeServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.User;
 4 import cn.itcast.service.UserService;
 5 import cn.itcast.service.impl.UserServiceImpl;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.IOException;
13 import java.util.List;
14 
15 @WebServlet("/userListServlet")
16 public class UserListServlet extends HttpServlet {
17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18         //调用业务,获取所有用户
19         UserService userService = new UserServiceImpl();
20         List<User> userList = userService.findAll();
21 
22         //存入request域,转发到list.jsp
23         request.setAttribute("userList", userList);
24         request.getRequestDispatcher("list.jsp").forward(request, response);
25     }
26 
27     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
28         doPost(request, response);
29     }
30 }
UserListServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.User;
 4 import cn.itcast.service.UserService;
 5 import cn.itcast.service.impl.UserServiceImpl;
 6 import org.apache.commons.beanutils.BeanUtils;
 7 
 8 import javax.servlet.ServletException;
 9 import javax.servlet.annotation.WebServlet;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import java.io.IOException;
14 import java.lang.reflect.InvocationTargetException;
15 
16 @WebServlet("/addUserServlet")
17 public class AddUserServlet extends HttpServlet {
18     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19         /*
20         在AddServlet中:
21             获取表单参数并封装成对象User
22             调用业务添加用户,addUser(User):boolean
23             成功,重定向到userListServlet
24             (注意:如果使用转发,则地址为addServlet,用户刷新会出问题)
25             失败,直接转发回原来的add.jsp,给出错误消息
26          */
27         request.setCharacterEncoding("UTF-8");
28         //获取表单参数并封装成对象User
29         User user = new User();
30         try {
31             //如果传入了xxx作为年龄,不会传出异常,BeanUtils将数字解析异常吃掉了。并将整型赋值为0。
32             BeanUtils.populate(user, request.getParameterMap());
33         } catch (IllegalAccessException e) {
34             e.printStackTrace();
35         } catch (InvocationTargetException e) {
36             e.printStackTrace();
37         }
38 
39         //调用业务添加用户,addUser(User):boolean
40         UserService userService = new UserServiceImpl();
41         if(userService.add(user)){
42             //成功,重定向到userListServlet
43             response.sendRedirect(request.getContextPath() + "/findUserByPageServlet");
44         }else{
45             //失败,直接转发回原来的add.jsp,给出错误消息,有问题,永远不会出现失败。
46             request.setAttribute("error", "添加用户失败");
47             request.getRequestDispatcher("/add.jsp").forward(request, response);
48         }
49     }
50 
51     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
52         doPost(request, response);
53     }
54 }
AddUserServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.service.UserService;
 4 import cn.itcast.service.impl.UserServiceImpl;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.annotation.WebServlet;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import java.io.IOException;
12 
13 @WebServlet("/deleteServlet")
14 public class DeleteUserServlet extends HttpServlet {
15 
16     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
17         /*
18             在deleteServlet中:
19                 获取id,根据id,调用业务删除用户
20                 重定向到userListServlet页。
21          */
22         //获取id
23         String id = request.getParameter("id");
24 
25         //根据id,调用业务删除用户
26         UserServiceImpl userService = new UserServiceImpl();
27         userService.deleteById(id);
28 
29         //重定向到userListServlet页。
30         response.sendRedirect(request.getContextPath() + "/findUserByPageServlet");
31 
32         //使用转发,貌似没有出问题,除了用户列表的地址栏变为:http://localhost/deleteServlet?id=10
33 //        request.getRequestDispatcher("/findUserByPageServlet").forward(request, response);
34     }
35 
36     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
37         doPost(request, response);
38     }
39 }
DeleteUserServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.User;
 4 import cn.itcast.service.impl.UserServiceImpl;
 5 import org.apache.commons.beanutils.BeanUtils;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.IOException;
13 import java.lang.reflect.InvocationTargetException;
14 
15 @WebServlet("/findUserServlet")
16 public class FindUserServlet extends HttpServlet {
17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18         /*
19         在EditServlet中:
20             获取参数,封装User,存入request域,转发给update.jsp
21          */
22         String id = request.getParameter("id");
23 
24         UserServiceImpl userService = new UserServiceImpl();
25         User user = userService.findUserById(id);
26 
27         request.setAttribute("user", user);
28         request.getRequestDispatcher("/update.jsp").forward(request, response);
29     }
30 
31     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
32         doPost(request, response);
33     }
34 }
FindUserServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.User;
 4 import cn.itcast.service.UserService;
 5 import cn.itcast.service.impl.UserServiceImpl;
 6 import org.apache.commons.beanutils.BeanUtils;
 7 
 8 import javax.servlet.ServletException;
 9 import javax.servlet.annotation.WebServlet;
10 import javax.servlet.http.HttpServlet;
11 import javax.servlet.http.HttpServletRequest;
12 import javax.servlet.http.HttpServletResponse;
13 import java.io.IOException;
14 import java.lang.reflect.InvocationTargetException;
15 
16 @WebServlet("/updateServlet")
17 public class UpdateUserServlet extends HttpServlet {
18     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
19         /*
20         在updateServlet中:
21             获取表单数据,封装User对象。
22             调业务更新,void update(User)
23             转发到userListServlet
24          */
25         request.setCharacterEncoding("UTF-8");
26         //获取表单数据,封装User对象。
27         User user = new User();
28         try {
29             BeanUtils.populate(user, request.getParameterMap());
30         } catch (IllegalAccessException e) {
31             e.printStackTrace();
32         } catch (InvocationTargetException e) {
33             e.printStackTrace();
34         }
35         //调业务更新,void update(User)
36         UserService userService = new UserServiceImpl();
37         userService.update(user);
38 
39         //转发到userListServlet
40         response.sendRedirect("/findUserByPageServlet");
41     }
42 
43     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
44         doPost(request, response);
45     }
46 }
UpdateUserServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.service.impl.UserServiceImpl;
 4 
 5 import javax.servlet.ServletException;
 6 import javax.servlet.annotation.WebServlet;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 import java.io.IOException;
11 
12 @WebServlet("/delSelectedServlet")
13 public class DelSelectedServlet extends HttpServlet {
14     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
15         /*
16             2.在DelSelectedServlet中
17                 获取选中的id
18                 调用业务,删除选中用户 deleteUsers(String ids[])
19                 转到,UserListServlet
20          */
21         //获取选中的id
22         String[] ids = request.getParameterValues("id");
23 
24         //调用业务,删除选中用户 deleteUsers(String ids[])
25         UserServiceImpl userService = new UserServiceImpl();
26         userService.deleteUsers(ids);
27 
28         //转到,UserListServlet
29         response.sendRedirect(request.getContextPath() + "/findUserByPageServlet");
30     }
31 
32     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
33         doPost(request, response);
34     }
35 }
DelSelectedServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.PageBean;
 4 import cn.itcast.domain.User;
 5 import cn.itcast.service.impl.UserServiceImpl;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.IOException;
13 import java.util.Map;
14 
15 @WebServlet("/findUserByPageServlet")
16 public class FindUserByPageServlet extends HttpServlet {
17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18         request.setCharacterEncoding("utf-8");
19         //获取页面参数
20         String currentPage = request.getParameter("currentPage");
21         String pageSize = request.getParameter("pageSize");
22 
23         Map<String, String[]> searchCondition = request.getParameterMap();
24         //查询用户页的业务。
25         UserServiceImpl userService = new UserServiceImpl();
26         PageBean<User> userPage = userService.findUserByPage(currentPage, pageSize, searchCondition);
27 
28         //转发给list.jsp
29         request.setAttribute("searchCondition", searchCondition);
30         request.setAttribute("userPage", userPage);
31         request.getRequestDispatcher("/list.jsp").forward(request, response);
32     }
33 
34     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
35         doPost(request, response);
36     }
37 }
FindUserByPageServlet
 1 package cn.itcast.web.servlet;
 2 
 3 import cn.itcast.domain.PageBean;
 4 import cn.itcast.domain.User;
 5 import cn.itcast.service.impl.UserServiceImpl;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.annotation.WebServlet;
 9 import javax.servlet.http.HttpServlet;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import java.io.IOException;
13 import java.util.Map;
14 
15 @WebServlet("/findUserByPageServlet")
16 public class FindUserByPageServlet extends HttpServlet {
17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
18         request.setCharacterEncoding("utf-8");
19         //获取页面参数
20         String currentPage = request.getParameter("currentPage");
21         String pageSize = request.getParameter("pageSize");
22 
23         Map<String, String[]> searchCondition = request.getParameterMap();
24         //查询用户页的业务。
25         UserServiceImpl userService = new UserServiceImpl();
26         PageBean<User> userPage = userService.findUserByPage(currentPage, pageSize, searchCondition);
27 
28         //转发给list.jsp
29         request.setAttribute("searchCondition", searchCondition);
30         request.setAttribute("userPage", userPage);
31         request.getRequestDispatcher("/list.jsp").forward(request, response);
32     }
33 
34     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
35         doPost(request, response);
36     }
37 }
FindUserByPageServlet
 1 package cn.itcast.web.filter;
 2 
 3 import cn.itcast.domain.User;
 4 
 5 import javax.servlet.*;
 6 import javax.servlet.annotation.WebFilter;
 7 import javax.servlet.http.HttpServletRequest;
 8 import java.io.IOException;
 9 
10 @WebFilter("/*")
11 public class LoginFilter implements Filter {
12     public void destroy() {
13     }
14 
15     public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
16         HttpServletRequest request = (HttpServletRequest) req;
17         //放行登录相关资源
18         String uri = request.getRequestURI();
19         if(uri.contains("/css/") || uri.contains("/fonts/") || uri.contains("/js/")
20             || uri.contains("/loginServlet") || uri.contains("/login.jsp") || uri.contains("/checkCodeServlet")){
21             chain.doFilter(req, resp);
22             return;
23         }
24 
25         //判断是否登录
26         User user = (User) request.getSession().getAttribute("user");
27         if(user != null){
28             //已经登录,放行
29             chain.doFilter(req, resp);
30         }else{
31             //没有登录,转发到登录页面进行登录
32             req.setAttribute("loginMsg", "您还没有登录,请登录!");
33             req.getRequestDispatcher("/login.jsp").forward(req, resp);
34         }
35     }
36 
37     public void init(FilterConfig config) throws ServletException {
38 
39     }
40 
41 }
LoginFilter
 1 package cn.itcast.utils;
 2 
 3 import com.alibaba.druid.pool.DruidDataSourceFactory;
 4 
 5 import javax.sql.DataSource;
 6 import javax.xml.crypto.Data;
 7 import java.io.IOException;
 8 import java.io.InputStream;
 9 import java.sql.Connection;
10 import java.sql.SQLException;
11 import java.util.Properties;
12 
13 /**
14  * JDBC工具类 使用Durid连接池
15  */
16 public class JDBCUtils {
17 
18     private static DataSource ds ;
19 
20     static {
21 
22         try {
23             //1.加载配置文件
24             Properties pro = new Properties();
25             //使用ClassLoader加载配置文件,获取字节输入流
26             InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
27             pro.load(is);
28 
29             //2.初始化连接池对象
30             ds = DruidDataSourceFactory.createDataSource(pro);
31 
32         } catch (IOException e) {
33             e.printStackTrace();
34         } catch (Exception e) {
35             e.printStackTrace();
36         }
37     }
38 
39     /**
40      * 获取连接池对象
41      */
42     public static DataSource getDataSource(){
43         return ds;
44     }
45 
46 
47     /**
48      * 获取连接Connection对象
49      */
50     public static Connection getConnection() throws SQLException {
51         return  ds.getConnection();
52     }
53 }
JDBCUtils
 1 package cn.itcast.utils;
 2 
 3 import javax.imageio.ImageIO;
 4 import java.awt.*;
 5 import java.awt.image.BufferedImage;
 6 import java.io.IOException;
 7 import java.io.OutputStream;
 8 import java.util.Random;
 9 
10 public final class GraphicHelper {
11 
12     /**
13      * 以字符串形式返回生成的验证码,同时输出一个图片
14      *
15      * @param width
16      *            图片的宽度
17      * @param height
18      *            图片的高度
19      * @param imgType
20      *            图片的类型
21      * @param output
22      *            图片的输出流(图片将输出到这个流中)
23      * @return 返回所生成的验证码(字符串)
24      */
25     public static String create(final int width, final int height,
26                                 final String imgType, OutputStream output) {
27         StringBuffer sb = new StringBuffer();
28         Random random = new Random();
29 
30         BufferedImage image = new BufferedImage(width, height,
31                 BufferedImage.TYPE_INT_RGB);
32         Graphics graphic = image.getGraphics();
33         graphic.setColor(Color.getColor("F8F8F8"));
34         graphic.fillRect(0, 0, width, height);
35 
36         Color[] colors = new Color[] { Color.BLUE, Color.GRAY, Color.GREEN,
37                 Color.RED, Color.BLACK, Color.ORANGE, Color.magenta,Color.darkGray,Color.pink };
38         // 在 "画板"上生成干扰线条 ( 40 是线条个数)
39         for (int i = 0; i < 40; i++) {
40             graphic.setColor(colors[random.nextInt(colors.length)]);
41             final int x = random.nextInt(width);
42             final int y = random.nextInt(height);
43             final int w = random.nextInt(20);
44             final int h = random.nextInt(20);
45             final int signA = random.nextBoolean() ? 1 : -1;
46             final int signB = random.nextBoolean() ? 1 : -1;
47             graphic.drawLine(x, y, x + w * signA, y + h * signB);
48         }
49         // 在 "画板"上绘制字母
50         graphic.setFont(new Font("Comic Sans MS", Font.BOLD, 30));
51         for (int i = 0; i < 4; i++) {
52             final int temp = random.nextInt(26) + 97;
53             String s = String.valueOf((char) temp);
54             sb.append(s);
55             graphic.setColor(colors[random.nextInt(colors.length)]);
56             graphic.drawString(s, i * (width / 4), height - (height / 3));
57         }
58         graphic.dispose();
59         try {
60             ImageIO.write(image, imgType, output);
61         } catch (IOException e) {
62             e.printStackTrace();
63         }
64         return sb.toString();
65     }
66 }
GraphicHelper
 1 package cn.itcast.service;
 2 
 3 import cn.itcast.domain.PageBean;
 4 import cn.itcast.domain.User;
 5 
 6 import java.util.List;
 7 import java.util.Map;
 8 
 9 /**
10  * 用户管理服务
11  */
12 public interface UserService {
13 
14     /**
15      * 查询所有用户
16      * @return 所有用户的List集合对象
17      */
18     List<User> findAll();
19 
20     /**
21      * 根据id删除用户
22      * @param id 需要被删除的用户的id
23      */
24     void deleteById(String id);
25 
26     /**
27      * 添加用户
28      * @return 如果添加成功,返回true,否则返回false
29      */
30     boolean add(User user);
31 
32     /**
33      * 根据用户id,进行更新
34      * @param user 需要更新的用户
35      */
36     void update(User user);
37 
38     /**
39      * 根据id数组删除用户
40      * @param ids 需要被删除的多个用户的id集合
41      */
42     void deleteUsers(String[] ids);
43 
44     /**
45      * 根据当前页和页大小查询页
46      * @return
47      * @param currentPageStr
48      * @param pageSizeStr
49      * @param parameterMap
50      */
51     PageBean<User> findUserByPage(String currentPageStr, String pageSizeStr, Map<String, String[]> parameterMap);
52 
53     /**
54      * 根据id查询用户
55      * @return
56      */
57     User findUserById(String id);
58 
59     /**
60      *  用户登录
61      * @param loginCondition 用户名和密码
62      * @return
63      */
64     User login(User loginCondition);
65 }
UserService
 1 package cn.itcast.service.impl;
 2 
 3 import cn.itcast.dao.UserDao;
 4 import cn.itcast.dao.impl.UserDaoImpl;
 5 import cn.itcast.domain.PageBean;
 6 import cn.itcast.domain.User;
 7 import cn.itcast.service.UserService;
 8 
 9 import java.util.List;
10 import java.util.Map;
11 
12 public class UserServiceImpl implements UserService {
13     private UserDao userDao = new UserDaoImpl();
14 
15     @Override
16     public List<User> findAll() {
17         return userDao.findAll();
18     }
19 
20     @Override
21     public void deleteById(String id) {
22         userDao.deleteById(Integer.parseInt(id));
23     }
24 
25     @Override
26     public boolean add(User user) {
27         return userDao.add(user) > 0 ? true : false;
28     }
29 
30     @Override
31     public void update(User user) {
32         userDao.update(user);
33     }
34 
35     @Override
36     public void deleteUsers(String[] ids) {
37         //健壮性判断
38         if(ids != null && ids.length > 0){
39             for (String id : ids) {
40                 userDao.deleteById(Integer.parseInt(id));
41             }
42         }
43     }
44 
45     @Override
46     public PageBean<User> findUserByPage(String currentPageStr, String pageSizeStr, Map<String, String[]> searchCondition) {
47         //currentPage和pageSize
48         int currentPage = currentPageStr == null || "".equals(currentPageStr)
49                             ? 1 : Integer.parseInt(currentPageStr);
50         int pageSize = pageSizeStr == null || "".equals(pageSizeStr)
51                         ? 3 : Integer.parseInt(pageSizeStr);
52         //查询总条数
53         int totalCount = (int) userDao.findTotalCount(searchCondition);
54         //如果总条数为0,怎么进行处理
55 
56         //总页数
57         int totalPage = totalCount % pageSize == 0
58                 ? totalCount / pageSize
59                 : totalCount / pageSize + 1;
60 
61         //注意:如果总条数为0的处理方式,当前页超出范围
62         if(currentPage > totalPage){
63             currentPage = totalPage;
64         }
65         if(currentPage < 1){
66             currentPage = 1;
67         }
68 
69         //查询数据
70         int start = (currentPage - 1) * pageSize;
71         List<User> users = userDao.findUserByPage(start, pageSize, searchCondition);
72 
73         PageBean<User> userPage = new PageBean<>();
74         userPage.setCurrentPage(currentPage);
75         userPage.setPageSize(pageSize);
76         userPage.setTotalPage(totalPage);
77         userPage.setTotalCount(totalCount);
78         userPage.setPageData(users);
79         return userPage;
80     }
81 
82     @Override
83     public User findUserById(String id) {
84         return userDao.findById(Integer.parseInt(id));
85     }
86 
87     @Override
88     public User login(User loginCondition) {
89         return userDao.findByUsernameAndPassword(loginCondition.getUsername(), loginCondition.getPassword());
90     }
91 }
UserServiceImpl
 1 package cn.itcast.dao;
 2 
 3 import cn.itcast.domain.User;
 4 
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 /**
 9  * 用户操作
10  */
11 public interface UserDao {
12     /**
13      * 查询所有用户
14      * @return
15      */
16     List<User> findAll();
17 
18     /**
19      * 根据id删除用户
20      * @param id 被删除用户的id
21      */
22     void deleteById(int id);
23 
24     /**
25      *  添加用户
26      * @param user 被添加的用户
27      * @return
28      */
29     int add(User user);
30 
31     /**
32      * 根据用户id,进行用户修改
33      * @param user
34      */
35     void update(User user);
36 
37     /**
38      *  查询全部用户数量
39      * @return
40      * @param searchCondition
41      */
42     long findTotalCount(Map<String, String[]> searchCondition);
43 
44     /**
45      * 查询用户分页
46      * @param start 起始行
47      * @param pageSize 最大数量
48      * @param searchCondition
49      * @return
50      */
51     List<User> findUserByPage(int start, int pageSize, Map<String, String[]> searchCondition);
52 
53     /**
54      * 根据id查询用户
55      * @param id
56      * @return
57      */
58     User findById(int id);
59 
60     /**
61      * 根据用户名和密码查询用户
62      * @param username
63      * @param password
64      * @return
65      */
66     User findByUsernameAndPassword(String username, String password);
67 }
UserDao
  1 package cn.itcast.dao.impl;
  2 
  3 import cn.itcast.dao.UserDao;
  4 import cn.itcast.domain.User;
  5 import cn.itcast.utils.JDBCUtils;
  6 import org.springframework.dao.DataAccessException;
  7 import org.springframework.jdbc.core.BeanPropertyRowMapper;
  8 import org.springframework.jdbc.core.JdbcTemplate;
  9 
 10 import java.util.ArrayList;
 11 import java.util.List;
 12 import java.util.Map;
 13 
 14 public class UserDaoImpl implements UserDao {
 15     private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());
 16 
 17     @Override
 18     public int add(User user) {
 19         //写sql
 20         String sql = "insert into user(name, gender, age, address, qq, email) values(?,?,?,?,?,?) ";
 21         //添加用户
 22         return jdbcTemplate.update(sql, user.getName(), user.getGender(), user.getAge(),
 23                 user.getAddress(), user.getQq(), user.getEmail());
 24     }
 25 
 26     @Override
 27     public void deleteById(int id) {
 28         //写sql
 29         String sql = "delete from user where id=?";
 30         //根据id删除用户
 31         jdbcTemplate.update(sql, id);
 32     }
 33 
 34     @Override
 35     public void update(User user) {
 36         //写sql
 37         String sql = "update user set name=?, gender=?, age=?, address=?, qq=?, email=? where id=? ";
 38         //修改用户
 39         jdbcTemplate.update(sql, user.getName(), user.getGender(), user.getAge(),
 40                 user.getAddress(), user.getQq(), user.getEmail(), user.getId());
 41     }
 42 
 43     @Override
 44     public long findTotalCount(Map<String, String[]> searchCondition) {
 45         StringBuilder sql = new StringBuilder();
 46         sql.append("select count(*) from user where 1=1 ");
 47 
 48         List<Object> params = new ArrayList<>();
 49         prepareConditionPart(searchCondition, sql, params);
 50 
 51         return jdbcTemplate.queryForObject(sql.toString(), Long.class, params.toArray());
 52     }
 53 
 54     @Override
 55     public List<User> findUserByPage(int start, int pageSize, Map<String, String[]> searchCondition) {
 56         StringBuilder sql = new StringBuilder();
 57         sql.append("select id, name, gender, age, address, qq, email from  user where 1=1 ");
 58 
 59         List<Object> params = new ArrayList<>();
 60         prepareConditionPart(searchCondition, sql, params);
 61 //        String[] name = searchCondition.get("name");
 62 //        if(name != null){
 63 //            sql.append(" and name like ? ");
 64 //            params.add("%"+name[0]+"%");
 65 //        }
 66 //
 67 //        String[] address = searchCondition.get("address");
 68 //        if(address != null){
 69 //            sql.append(" and address like ? ");
 70 //            params.add("%"+address[0]+"%");
 71 //        }
 72 //
 73 //        String[] email = searchCondition.get("email");
 74 //        if(email != null){
 75 //            sql.append(" and email like ? ");
 76 //            params.add("%"+email[0]+"%");
 77 //        }
 78 
 79         sql.append(" limit ?, ? ");
 80         params.add(start);
 81         params.add(pageSize);
 82 
 83         return jdbcTemplate.query(sql.toString(), new BeanPropertyRowMapper<>(User.class),
 84                 params.toArray());
 85     }
 86 
 87     private void prepareConditionPart(Map<String, String[]> searchCondition, StringBuilder sql, List<Object> params) {
 88         String[] name = searchCondition.get("name");
 89         if (name != null && !"".equals(name[0])) {
 90             sql.append(" and name like ? ");
 91             params.add("%" + name[0] + "%");
 92         }
 93 
 94         String[] address = searchCondition.get("address");
 95         if (address != null && !"".equals(address[0])) {
 96             sql.append(" and address like ? ");
 97             params.add("%" + address[0] + "%");
 98         }
 99 
100         String[] email = searchCondition.get("email");
101         if (email != null && !"".equals(email[0])) {
102             sql.append(" and email like ? ");
103             params.add("%" + email[0] + "%");
104         }
105     }
106 
107     @Override
108     public List<User> findAll() {
109         //写sql
110         String sql = "select id, name, gender, age, address, qq, email from user";
111         //查询
112         return jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class));
113     }
114 
115     @Override
116     public User findById(int id) {
117         String sql = "select id, name, gender, age, address, qq, email from user where id=?";
118         return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
119     }
120 
121     @Override
122     public User findByUsernameAndPassword(String username, String password) {
123         String sql = "select id, name, gender, age, address, qq, email from user where username=? and password=?";
124         User user = null;
125         try{
126             user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class),
127                     username, password);
128         }catch (DataAccessException e){
129             e.printStackTrace();
130         }
131         return user;
132     }
133 }
UserDaoImpl
  1 package cn.itcast.domain;
  2 /*
  3 create table user(   -- 创建表
  4     id int primary key auto_increment,
  5     name varchar(20) not null,
  6     gender varchar(5),
  7     age int,
  8     address varchar(32),
  9     qq    varchar(20),
 10     email varchar(50)
 11 );
 12  */
 13 public class User {
 14     private Integer id;
 15     private String name;
 16     private String gender;
 17     private Integer age;
 18     private String address;
 19     private String qq;
 20     private String email;
 21 
 22     private String username;
 23     private String password;
 24 
 25 
 26 
 27     public User() {
 28     }
 29 
 30     public Integer getId() {
 31         return id;
 32     }
 33 
 34     public void setId(Integer id) {
 35         this.id = id;
 36     }
 37 
 38     public String getName() {
 39         return name;
 40     }
 41 
 42     public void setName(String name) {
 43         this.name = name;
 44     }
 45 
 46     public String getGender() {
 47         return gender;
 48     }
 49 
 50     public void setGender(String gender) {
 51         this.gender = gender;
 52     }
 53 
 54     public Integer getAge() {
 55         return age;
 56     }
 57 
 58     public void setAge(Integer age) {
 59         this.age = age;
 60     }
 61 
 62     public String getAddress() {
 63         return address;
 64     }
 65 
 66     public void setAddress(String address) {
 67         this.address = address;
 68     }
 69 
 70     public String getQq() {
 71         return qq;
 72     }
 73 
 74     public void setQq(String qq) {
 75         this.qq = qq;
 76     }
 77 
 78     public String getEmail() {
 79         return email;
 80     }
 81 
 82     public void setEmail(String email) {
 83 
 84         this.email = email;
 85     }
 86 
 87     public String getUsername() {
 88         return username;
 89     }
 90 
 91     public void setUsername(String username) {
 92         this.username = username;
 93     }
 94 
 95     public String getPassword() {
 96         return password;
 97     }
 98 
 99     public void setPassword(String password) {
100         this.password = password;
101     }
102 }
User
 1 package cn.itcast.domain;
 2 
 3 import java.util.List;
 4 
 5 public class PageBean<T> {
 6     //总页数
 7     private int totalPage;
 8     //总条数
 9     private int totalCount;
10     //页大小
11     private int pageSize;
12     //当前页
13     private int currentPage;
14     //页数据
15     private List<T> pageData;
16 
17     public PageBean() {
18     }
19 
20     public int getTotalPage() {
21         return totalPage;
22     }
23 
24     public void setTotalPage(int totalPage) {
25         this.totalPage = totalPage;
26     }
27 
28     public int getTotalCount() {
29         return totalCount;
30     }
31 
32     public void setTotalCount(int totalCount) {
33         this.totalCount = totalCount;
34     }
35 
36     public int getPageSize() {
37         return pageSize;
38     }
39 
40     public void setPageSize(int pageSize) {
41         this.pageSize = pageSize;
42     }
43 
44     public int getCurrentPage() {
45         return currentPage;
46     }
47 
48     public void setCurrentPage(int currentPage) {
49         this.currentPage = currentPage;
50     }
51 
52     public List<T> getPageData() {
53         return pageData;
54     }
55 
56     public void setPageData(List<T> pageData) {
57         this.pageData = pageData;
58     }
59 }
PageBean

posted @ 2019-05-13 22:59  没有理由不会呀  阅读(971)  评论(0编辑  收藏  举报