Java web 案例

1. 用户信息管理

  1. 简单功能

    • 列表查询

    • 登录

    • 添加

    • 删除

    • 修改

  2. 复杂功能

    • 删除选中
    • 分页查询:减轻服务器内存的开销,提升用户体验
    • 复杂条件查询

1.1 登录功能

对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
<%@ 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();
}

}

}
//1.获取第一个cb
document.getElementById("firstCb").onclick = function(){
//2.获取下边列表中所有的cb
var cbs = document.getElementsByName("uid");
//3.遍历
for (var i = 0; i < cbs.length; i++) {
//4.设置这些cbs[i]的checked状态 = firstCb.checked
cbs[i].checked = this.checked;

}

}


}


</script>
</head>
<body>
<div class="container">
<h3 style="text-align: center">用户信息列表</h3>

<div style="float: left;">

<form class="form-inline" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post">
<div class="form-group">
<%--label标签点击选中输入框--%>
<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>&nbsp;
<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">
</c:if>

<c:if test="${pb.currentPage != 1}">
<li>
</c:if>


<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">&laquo;</span>
</a>
</li>


<c:forEach begin="1" end="${pb.totalPage}" var="i" >


<c:if test="${pb.currentPage == i}">
<li class="active"><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
</c:if>
<c:if test="${pb.currentPage != i}">
<li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
</c:if>

</c:forEach>


<li>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
<span style="font-size: 25px;margin-left: 10px;">
共${pb.totalCount}条记录,共${pb.totalPage}页
</span>

</ul>
</nav>


</div>


</div>


</body>
</html>

对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
<%@ 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(){
//1.获取验证码图片对象
var vcode = document.getElementById("vcode");

//2.设置其src属性,加时间戳
vcode.src = "${pageContext.request.contextPath}/checkCodeServlet?time="+new Date().getTime();
}
</script>
</head>
<body>
<div class="container" style="width: 400px;">
<h3 style="text-align: center;">管理员登录</h3>
<form action="${pageContext.request.contextPath}/loginServlet" method="post">
<div class="form-group">
<label for="user">用户名:</label>
<input type="text" name="username" class="form-control" id="user" placeholder="请输入用户名"/>
</div>

<div class="form-group">
<label for="password">密码:</label>
<input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/>
</div>

<div class="form-inline">
<label for="vcode">验证码:</label>
<input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="请输入验证码" style="width: 120px;"/>
<a href="javascript:refreshCode();">
<img src="${pageContext.request.contextPath}/checkCodeServlet" title="看不清点击刷新" id="vcode"/>
</a>
</div>
<hr/>
<div class="form-group" style="text-align: center;">
<input class="btn btn btn-primary" type="submit" value="登录">
</div>
</form>

<!-- 出错显示的信息框 -->
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" >
<span>&times;</span>
</button>
<strong>${login_msg}</strong>
</div>
</div>
</body>
</html>

添加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
package cn.itcast.web.servlet;

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;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

/**
* 验证码
*/
@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");

//在内存中创建一个长80,宽30的图片,默认黑色背景
//参数一:长
//参数二:宽
//参数三:颜色
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);

//产生4个随机验证码,12Ey
String checkCode = getCheckCode();
//将验证码放入HttpSession中
request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);

//设置画笔颜色为黄色
g.setColor(Color.YELLOW);
//设置字体的小大
g.setFont(new Font("黑体",Font.BOLD,24));
//向图片上写入验证码
g.drawString(checkCode,15,25);

//将内存中的图片输出到浏览器
//参数一:图片对象
//参数二:图片的格式,如PNG,JPG,GIF
//参数三:图片输出到哪里去
ImageIO.write(image,"PNG",response.getOutputStream());
}
/**
* 产生4位随机字符串
*/
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++){
//产生0到size-1的随机值
int index = r.nextInt(size);
//在base字符串中获取下标为index的字符
char c = base.charAt(index);
//将c放入到StringBuffer中去
sb.append(c);
}
return sb.toString();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request,response);
}
}

编写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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package cn.itcast.web.servlet;

import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置编码
request.setCharacterEncoding("utf-8");

//2.获取数据
//2.1获取用户填写验证码
String verifycode = request.getParameter("verifycode");

//3.验证码校验
HttpSession session = request.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
session.removeAttribute("CHECKCODE_SERVER");//确保验证码一次性
if(!checkcode_server.equalsIgnoreCase(verifycode)){
//验证码不正确
//提示信息
request.setAttribute("login_msg","验证码错误!");
//跳转登录页面
request.getRequestDispatcher("/login.jsp").forward(request,response);

return;
}

Map<String, String[]> map = request.getParameterMap();
//4.封装User对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}


//5.调用Service查询
UserService service = new UserServiceImpl();
User loginUser = service.login(user);
//6.判断是否登录成功
if(loginUser != null){
//登录成功
//将用户存入session
session.setAttribute("user",loginUser);
//跳转页面
response.sendRedirect(request.getContextPath()+"/index.jsp");
}else{
//登录失败
//提示信息
request.setAttribute("login_msg","用户名或密码错误!");
//跳转登录页面
request.getRequestDispatcher("/login.jsp").forward(request,response);

}




}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}

1.2 添加功能

业务流程图

image-20191129201016530

编写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
<%@ 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="address">
<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" id="qq" name="qq" placeholder="请输入QQ号码"/>
</div>

<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="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="重置" />
<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
41
42
43
44
45
package cn.itcast.web.servlet;

import cn.itcast.domain.User;
import cn.itcast.service.UserService;
import cn.itcast.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 {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置编码
request.setCharacterEncoding("utf-8");
//2.获取参数
Map<String, String[]> map = request.getParameterMap();
//3.封装对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}

//4.调用Service保存
UserService service = new UserServiceImpl();
service.addUser(user);

//5.跳转到userListServlet
response.sendRedirect(request.getContextPath()+"/userListServlet");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}

编写UserService接口定义添加方法

1
2
3
4
5
6
7
8
9
10
11
12
13

/**
* 用户管理的业务接口
*/
public interface UserService {

/**
* 保存User
* @param user
*/
void addUser(User user);

}

编写UserServiceImpl实现添加方法

1
2
3
4
@Override
public void addUser(User user) {
dao.add(user);
}

编写UserDao接口定义添加方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 用户操作的DAO
*/
public interface UserDao {


public List<User> findAll();

User findUserByUsernameAndPassword(String username, String password);

void add(User user);

void delete(int id);

User findById(int i);

void update(User user);
}

编写UserDaoImpl实现添加方法

1
2
3
4
5
6
7
8
9
10
11
12
public class UserDaoImpl implements UserDao {

private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

@Override
public void add(User user) {
//1.定义sql
String sql = "insert into user values(null,?,?,?,?,?,?,null,null)";
//2.执行sql
template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail());
}
}

1.3 删除功能

业务流程图

image-20191130105255826

修改list.jsp增加删除按钮

1
2
3
<td>
<a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改</a>&nbsp;
<a class="btn btn-default btn-sm" href="javascript:deleteUser(${user.id});">删除</a></td>

编写DelUserServlet实现删除方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@WebServlet("/delUserServlet")
public class DelUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取id
String id = request.getParameter("id");
//2.调用service删除
UserService service = new UserServiceImpl();
service.deleteUser(id);

//3.跳转到查询所有Servlet
response.sendRedirect(request.getContextPath()+"/userListServlet");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}

编写UserService接口定义删除方法

1
2
3
4
5
6
7
8
9
10
11
12
13

/**
* 用户管理的业务接口
*/
public interface UserService {

/**
* 根据id删除User
* @param id
*/
void deleteUser(String id);

}

编写UserServiceImpl实现删除方法

1
2
3
4
@Override
public void deleteUser(String id) {
dao.delete(Integer.parseInt(id));
}

编写UserDao接口定义删除方法

1
void add(User user);

编写UserDaoImpl实现删除方法

1
2
3
4
5
6
7
8
9
10
11
12
public class UserDaoImpl implements UserDao {

private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

@Override
public void delete(int id) {
//1.定义sql
String sql = "delete from user where id = ?";
//2.执行sql
template.update(sql, id);
}
}

添加JS函数实现确认删除

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
<%@ 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;
}
}

</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标签点击选中输入框--%>
<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>&nbsp;
<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">
</c:if>

<c:if test="${pb.currentPage != 1}">
<li>
</c:if>


<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">&laquo;</span>
</a>
</li>


<c:forEach begin="1" end="${pb.totalPage}" var="i" >


<c:if test="${pb.currentPage == i}">
<li class="active"><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
</c:if>
<c:if test="${pb.currentPage != i}">
<li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
</c:if>

</c:forEach>


<li>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
<span style="font-size: 25px;margin-left: 10px;">
共${pb.totalCount}条记录,共${pb.totalPage}页
</span>

</ul>
</nav>


</div>


</div>


</body>
</html>

1.4 修改功能

业务流程图

image-20191130113308181

修改list.jsp页面

1
<a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/findUserServlet?id=${user.id}">修改</a>&nbsp;

编写findUserServlet根据id查找user

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取id
String id = request.getParameter("id");
//2.调用Service查询
UserService service = new UserServiceImpl();
User user = service.findUserById(id);

//3.将user存入request
request.setAttribute("user",user);
//4.转发到update.jsp
request.getRequestDispatcher("/update.jsp").forward(request,response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}

编写UserService接口根据id查找user

1
2
3
4
5
6
7
8
9
10
11
/**
* 用户管理的业务接口
*/
public interface UserService {
/**
* 根据id查询
* @param id
* @return
*/
User findUserById(String id);
}

编写UserServiceImpl实现根据id查找user方法

1
2
3
4
5
6
7
8
public class UserServiceImpl implements UserService {
private UserDao dao = new UserDaoImpl();

@Override
public User findUserById(String id) {
return dao.findById(Integer.parseInt(id));
}
}

编写UserDaoImpl实现根据id查找user方法

1
2
3
4
5
6
7
8
9
10
public class UserDaoImpl implements UserDao {

private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

@Override
public User findById(int id) {
String sql = "select * from user where id = ?";
return template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), id);
}
}

编写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
<%@ 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="重置" />
<input class="btn btn-default" type="button" value="返回"/>
</div>
</form>
</div>
</body>
</html>

编写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
@WebServlet("/updateUserServlet")
public class UpdateUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.设置编码
request.setCharacterEncoding("utf-8");
//2.获取map
Map<String, String[]> map = request.getParameterMap();
//3.封装对象
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}

//4.调用Service修改
UserService service = new UserServiceImpl();
service.updateUser(user);

//5.跳转到查询所有Servlet
response.sendRedirect(request.getContextPath()+"/userListServlet");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}

编写UserServiceImpl实现更新用户信息方法

1
2
3
4
5
6
7
8
public class UserServiceImpl implements UserService {
private UserDao dao = new UserDaoImpl();

@Override
public void updateUser(User user) {
dao.update(user);
}
}

编写UserDaoImpl实现更新用户信息方法

1
2
3
4
5
6
7
8
9
10
public class UserDaoImpl implements UserDao {

private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

@Override
public void update(User user) {
String sql = "update user set name = ?,gender = ? ,age = ? , address = ? , qq = ?, email = ? where id = ?";
template.update(sql, user.getName(), user.getGender(), user.getAge(), user.getAddress(), user.getQq(), user.getEmail(), user.getId());
}
}

1.5 删除选中功能

业务流程图

image-20191130204745603

修改list.jsp页面,将选中id通过表单发送

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
<%@ 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();
}

}

}
}

</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标签点击选中输入框--%>
<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>&nbsp;
<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">
</c:if>

<c:if test="${pb.currentPage != 1}">
<li>
</c:if>


<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">&laquo;</span>
</a>
</li>


<c:forEach begin="1" end="${pb.totalPage}" var="i" >


<c:if test="${pb.currentPage == i}">
<li class="active"><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
</c:if>
<c:if test="${pb.currentPage != i}">
<li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
</c:if>

</c:forEach>


<li>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
<span style="font-size: 25px;margin-left: 10px;">
共${pb.totalCount}条记录,共${pb.totalPage}页
</span>

</ul>
</nav>


</div>


</div>


</body>
</html>

编写DeleteSelectedServlet删除选中功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@WebServlet("/delSelectedServlet")
public class DelSelectedServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获取所有id
String[] ids = request.getParameterValues("uid");
//2.调用service删除
UserService service = new UserServiceImpl();
service.delSelectedUser(ids);

//3.跳转查询所有Servlet
response.sendRedirect(request.getContextPath()+"/userListServlet");
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}

编写UserServiceImpl实现删除选中功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class UserServiceImpl implements UserService {
private UserDao dao = new UserDaoImpl();

@Override
public void delSelectedUser(String[] ids) {
if(ids != null && ids.length > 0){
//1.遍历数组
for (String id : ids) {
//2.调用dao删除
dao.delete(Integer.parseInt(id));
}
}

}

}

编写UserDaoImpl实现删除选中功能

1
2
3
4
5
6
7
8
9
10
11
12
13
public class UserDaoImpl implements UserDao {

private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

@Override
public void delete(int id) {
//1.定义sql
String sql = "delete from user where id = ?";
//2.执行sql
template.update(sql, id);
}

}

1.6 完善删除选中功能

编辑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
<%@ 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();
}

}

}
//1.获取第一个cb
document.getElementById("firstCb").onclick = function(){
//2.获取下边列表中所有的cb
var cbs = document.getElementsByName("uid");
//3.遍历
for (var i = 0; i < cbs.length; i++) {
//4.设置这些cbs[i]的checked状态 = firstCb.checked
cbs[i].checked = this.checked;

}

}

}
</script>
</head>
<body>
<div class="container">
<h3 style="text-align: center">用户信息列表</h3>

<div style="float: left;">

<form class="form-inline" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post">
<div class="form-group">
<%--label标签点击选中输入框--%>
<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>&nbsp;
<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">
</c:if>

<c:if test="${pb.currentPage != 1}">
<li>
</c:if>


<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">&laquo;</span>
</a>
</li>


<c:forEach begin="1" end="${pb.totalPage}" var="i" >


<c:if test="${pb.currentPage == i}">
<li class="active"><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
</c:if>
<c:if test="${pb.currentPage != i}">
<li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
</c:if>

</c:forEach>


<li>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
<span style="font-size: 25px;margin-left: 10px;">
共${pb.totalCount}条记录,共${pb.totalPage}页
</span>

</ul>
</nav>


</div>


</div>


</body>
</html>

1.7 分页查询功能

好处

  1. 减轻服务器内存开销
  2. 提升用户体验

业务流程图

image-20191202211113727

image-20191203111549292

编写PageBean类,包含分页所需参数

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
import java.util.List;

/**
* 分页对象
*/
public class PageBean<T> {
private int totalCount; // 总记录数
private int totalPage ; // 总页码
private List<T> list ; // 每页的数据
private int currentPage ; //当前页码
private int rows;//每页显示的记录数

public int getTotalCount() {
return totalCount;
}

public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}

public int getTotalPage() {
return totalPage;
}

public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}

public List<T> getList() {
return list;
}

public void setList(List<T> list) {
this.list = list;
}

public int getCurrentPage() {
return currentPage;
}

public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}

public int getRows() {
return rows;
}

public void setRows(int rows) {
this.rows = rows;
}

@Override
public String toString() {
return "PageBean{" +
"totalCount=" + totalCount +
", totalPage=" + totalPage +
", list=" + list +
", currentPage=" + currentPage +
", rows=" + rows +
'}';
}
}

编写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
@WebServlet("/findUserByPageServlet")
public class FindUserByPageServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");

//1.获取参数
String currentPage = request.getParameter("currentPage");//当前页码
String rows = request.getParameter("rows");//每页显示条数

if(currentPage == null || "".equals(currentPage)){

currentPage = "1";
}


if(rows == null || "".equals(rows)){
rows = "5";
}

//获取条件查询参数
Map<String, String[]> condition = request.getParameterMap();


//2.调用service查询
UserService service = new UserServiceImpl();
PageBean<User> pb = service.findUserByPage(currentPage,rows,condition);

System.out.println(pb);

//3.将PageBean存入request
request.setAttribute("pb",pb);
request.setAttribute("condition",condition);//将查询条件存入request
//4.转发到list.jsp
request.getRequestDispatcher("/list.jsp").forward(request,response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}

在service实现类中创建findUserByPage方法

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
public class UserServiceImpl implements UserService {
private UserDao dao = new UserDaoImpl();

@Override
public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {

int currentPage = Integer.parseInt(_currentPage);
int rows = Integer.parseInt(_rows);

if(currentPage <=0) {
currentPage = 1;
}
//1.创建空的PageBean对象
PageBean<User> pb = new PageBean<User>();
//2.设置参数
pb.setCurrentPage(currentPage);
pb.setRows(rows);

//3.调用dao查询总记录数
int totalCount = dao.findTotalCount(condition);
pb.setTotalCount(totalCount);
//4.调用dao查询List集合
//计算开始的记录索引
int start = (currentPage - 1) * rows;
List<User> list = dao.findByPage(start,rows,condition);
pb.setList(list);

//5.计算总页码
int totalPage = (totalCount % rows) == 0 ? totalCount/rows : (totalCount/rows) + 1;
pb.setTotalPage(totalPage);


return pb;
}
}

在Dao实现类中创建findTotalCount和findByPage方法

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

public class UserDaoImpl implements UserDao {

private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

@Override
public int findTotalCount(Map<String, String[]> condition) {
//1.定义模板初始化sql
String sql = "select count(*) from user where 1 = 1 ";
StringBuilder sb = new StringBuilder(sql);
//2.遍历map
Set<String> keySet = condition.keySet();
//定义参数的集合
List<Object> params = new ArrayList<Object>();
for (String key : keySet) {

//排除分页条件参数
if("currentPage".equals(key) || "rows".equals(key)){
continue;
}

//获取value
String value = condition.get(key)[0];
//判断value是否有值
if(value != null && !"".equals(value)){
//有值
sb.append(" and "+key+" like ? ");
params.add("%"+value+"%");//?条件的值
}
}
System.out.println(sb.toString());
System.out.println(params);

return template.queryForObject(sb.toString(),Integer.class,params.toArray());
}

@Override
public List<User> findByPage(int start, int rows, Map<String, String[]> condition) {
String sql = "select * from user where 1 = 1 ";

StringBuilder sb = new StringBuilder(sql);
//2.遍历map
Set<String> keySet = condition.keySet();
//定义参数的集合
List<Object> params = new ArrayList<Object>();
for (String key : keySet) {

//排除分页条件参数
if("currentPage".equals(key) || "rows".equals(key)){
continue;
}

//获取value
String value = condition.get(key)[0];
//判断value是否有值
if(value != null && !"".equals(value)){
//有值
sb.append(" and "+key+" like ? ");
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());
}
}

改造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
<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>&nbsp;
<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">
</c:if>

<c:if test="${pb.currentPage != 1}">
<li>
</c:if>


<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">&laquo;</span>
</a>
</li>


<c:forEach begin="1" end="${pb.totalPage}" var="i" >


<c:if test="${pb.currentPage == i}">
<li class="active"><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
</c:if>
<c:if test="${pb.currentPage != i}">
<li><a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${i}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}">${i}</a></li>
</c:if>

</c:forEach>


<li>
<a href="${pageContext.request.contextPath}/findUserByPageServlet?currentPage=${pb.currentPage + 1}&rows=5&name=${condition.name[0]}&address=${condition.address[0]}&email=${condition.email[0]}" aria-label="Next">
<span aria-hidden="true">&raquo;</span>
</a>
</li>
<span style="font-size: 25px;margin-left: 10px;">
共${pb.totalCount}条记录,共${pb.totalPage}页
</span>

</ul>
</nav>


</div>

1.8 复杂条件查询

业务流程图

image-20191203133201361

更改list.jsp,完成表单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<div style="float: left;">

<form class="form-inline" action="${pageContext.request.contextPath}/findUserByPageServlet" method="post">
<div class="form-group">
<%--label标签点击选中输入框--%>
<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>

更改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
@WebServlet("/findUserByPageServlet")
public class FindUserByPageServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");

//1.获取参数
String currentPage = request.getParameter("currentPage");//当前页码
String rows = request.getParameter("rows");//每页显示条数

if(currentPage == null || "".equals(currentPage)){

currentPage = "1";
}


if(rows == null || "".equals(rows)){
rows = "5";
}

//获取条件查询参数
Map<String, String[]> condition = request.getParameterMap();


//2.调用service查询
UserService service = new UserServiceImpl();
PageBean<User> pb = service.findUserByPage(currentPage,rows,condition);

System.out.println(pb);

//3.将PageBean存入request
request.setAttribute("pb",pb);
request.setAttribute("condition",condition);//将查询条件存入request
//4.转发到list.jsp
request.getRequestDispatcher("/list.jsp").forward(request,response);
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}

修改UserServiceImpl完成条件查询

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
public class UserServiceImpl implements UserService {
private UserDao dao = new UserDaoImpl();

@Override
public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {

int currentPage = Integer.parseInt(_currentPage);
int rows = Integer.parseInt(_rows);

if(currentPage <=0) {
currentPage = 1;
}
//1.创建空的PageBean对象
PageBean<User> pb = new PageBean<User>();
//2.设置参数
pb.setCurrentPage(currentPage);
pb.setRows(rows);

//3.调用dao查询总记录数
int totalCount = dao.findTotalCount(condition);
pb.setTotalCount(totalCount);
//4.调用dao查询List集合
//计算开始的记录索引
int start = (currentPage - 1) * rows;
List<User> list = dao.findByPage(start,rows,condition);
pb.setList(list);

//5.计算总页码
int totalPage = (totalCount % rows) == 0 ? totalCount/rows : (totalCount/rows) + 1;
pb.setTotalPage(totalPage);


return pb;
}
}

修改UserDaoImpl完成条件查询

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
public class UserDaoImpl implements UserDao {

private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());

@Override
public int findTotalCount(Map<String, String[]> condition) {
//1.定义模板初始化sql
String sql = "select count(*) from user where 1 = 1 ";
StringBuilder sb = new StringBuilder(sql);
//2.遍历map
Set<String> keySet = condition.keySet();
//定义参数的集合
List<Object> params = new ArrayList<Object>();
for (String key : keySet) {

//排除分页条件参数
if("currentPage".equals(key) || "rows".equals(key)){
continue;
}

//获取value
String value = condition.get(key)[0];
//判断value是否有值
if(value != null && !"".equals(value)){
//有值
sb.append(" and "+key+" like ? ");
params.add("%"+value+"%");//?条件的值
}
}
System.out.println(sb.toString());
System.out.println(params);

return template.queryForObject(sb.toString(),Integer.class,params.toArray());
}

@Override
public List<User> findByPage(int start, int rows, Map<String, String[]> condition) {
String sql = "select * from user where 1 = 1 ";

StringBuilder sb = new StringBuilder(sql);
//2.遍历map
Set<String> keySet = condition.keySet();
//定义参数的集合
List<Object> params = new ArrayList<Object>();
for (String key : keySet) {

//排除分页条件参数
if("currentPage".equals(key) || "rows".equals(key)){
continue;
}

//获取value
String value = condition.get(key)[0];
//判断value是否有值
if(value != null && !"".equals(value)){
//有值
sb.append(" and "+key+" like ? ");
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());
}
}
0%