分页查询功能&带条件的分页查询
分页查询流程:
PageBean
建一个实体类,用于封装当前页,总记录数,总页数,分页显示的数据,每页记录数。便于前台接受数据。
package cn.itcast.domain;
import java.util.List;
public class PageBean<T> {
private Integer currentPage; //当前页
private Integer totalCount; //总记录数
private Integer totalPage; //总页数
private List<T> list; //分页显的数据
private Integer rows; //每页记录数
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public Integer getRows() {
return rows;
}
public void setRows(Integer rows) {
this.rows = rows;
}
}
UserDao.java
/**
* 分页查询数据
* @param start 起始位置
* @param rows 每页条数
* @return
*/
public List<User> findByPage(int start,int rows);
/**
* 查询总记录数
* @return
*/
public int findTotalCount();
UserDaoImpl.java
@Override
public List<User> findByPage(int start, int rows) {
String sql = "select * from user limit ?,?";
List<User> list = template.query(sql, new BeanPropertyRowMapper<>(User.class), start, rows);
return list;
}
@Override
public int findTotalCount() {
String sql = "select count(*) from user";
int totalCount=0;
try {
totalCount = template.queryForObject(sql, Integer.class);
}catch(Exception ex){
}
return totalCount;
}
UserService.java
/**
* 分页查询
* @param currentPage 当前页
* @param rows 每页记录数
* @return
*/
PageBean<User> findByPage(int currentPage, int rows);
UserServiceImpl.java
@Override
public PageBean<User> findByPage(int currentPage, int rows) {
//查询总记录数
int totalCount = userDao.findTotalCount();
//查询总页数
int totalPage=totalCount%rows==0?totalCount/rows:totalCount/rows+1;
PageBean<User> pb = new PageBean<>();
//判断如果前台传过来的当前页小于1,则让当前页重置为1
if(currentPage<1){
currentPage=1;
}
//判断如果前台传过来的当前页大于总页数,则让当前页为总页数
if(currentPage>totalPage){
currentPage=totalPage;
}
//查询分页内容
int start= (currentPage-1)*rows;
List<User> list =userDao.findByPage(start,rows);
pb.setList(list);
pb.setCurrentPage(currentPage);
pb.setRows(rows);
pb.setTotalCount(totalCount);
pb.setTotalPage(totalPage);
return pb;
}
UserPageServlet
@WebServlet(value = "/UserPageServlet")
public class UserPageServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//接收前台传过来的当前页和每页显示记录数
String _currentPage = request.getParameter("currentPage");
String _rows = request.getParameter("rows");
//如果用户没有传当前页和每页显示记录数,默认值就给1和4
int currentPage=1;
if(_currentPage!=null&&!_currentPage.equals("")){
currentPage=Integer.parseInt(_currentPage);
}
int rows=4;
if(_rows!=null&&!_rows.equals("")){
rows=Integer.parseInt(_rows);
}
UserService userService = new UserServiceImpl();
PageBean<User> pb = userService.findByPage(currentPage, rows);
//将分页对象(PageBean)传到list.jsp
request.setAttribute("pb",pb);
request.getRequestDispatcher("/list.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
前台页面
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>首页</title>
<!-- 1. 导入CSS的全局样式 -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- 2. jQuery导入,建议使用1.9以上的版本 -->
<script src="js/jquery-2.1.0.min.js"></script>
<!-- 3. 导入bootstrap的js文件 -->
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div align="center">
<h2>欢迎您!${sessionScope.user.name}</h2>
<a
href="${pageContext.request.contextPath}/UserPageServlet" style="text-decoration:none;font-size:33px">查询所有用户信息
</a>
</div>
</body>
</html>
list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
<!-- 指定字符集 -->
<meta charset="utf-8">
<!-- 使用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 del(uid){
var result = confirm("您确定要删除吗?");
if(result){
window.location.href="${pageContext.request.contextPath}/DelUserServlet?id="+uid;
}
}
//删除选中的多条记录
function delSelected(){
var flag=false;
//判断有没有记录被选中
var ids = document.getElementsByName("ids");
for(var i=0; i<ids.length; i++){
if(ids[i].checked){
flag =true;
break;
}
}
if(flag){
var result= confirm("您确定要删除吗?");
if(result){
document.getElementById("form2").submit(); //javascript用于提交表单
}
}else{
alert("没有用户被选中");
}
}
window.οnlοad=function(){
//为selectAll多选框添加事件
document.getElementById("selectall").οnclick=function(){
var ids =document.getElementsByName("ids");
for(var i=0; i<ids.length; i++){
ids[i].checked = this.checked;
}
}
}
</script>
</head>
<body>
<div class="container">
<h3 style="text-align: center">用户信息列表</h3>
<div style="float:left;margin: 10px">
<form class="form-inline" id="form1">
<div class="form-group">
<label for="exampleInputName2">用户名</label>
<input type="text" class="form-control" id="exampleInputName2" >
</div>
<div class="form-group">
<label for="exampleInputaddress">籍贯</label>
<input type="email" class="form-control" id="exampleInputaddress" >
</div>
<div class="form-group">
<label for="exampleInputEmail2">邮箱</label>
<input type="email" class="form-control" id="exampleInputEmail2" >
</div>
<button type="submit" class="btn btn-default">查询</button>
</form>
</div>
<div style="float: right;margin: 10px">
<a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加联系人</a>
<a class="btn btn-primary" href="javascript:delSelected()">删除选中</a>
</div>
<form id="form2" action="${pageContext.request.contextPath}/DelSelectedServlet" method="post">
<table border="1" class="table table-bordered table-hover">
<tr class="success">
<th><input type="checkbox" id="selectall" /> </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="temp" >
<tr>
<td><input type="checkbox" name="ids" value="${temp.id}"/> </td>
<td>${temp.id}</td>
<td>${temp.name}</td>
<td>${temp.gender}</td>
<td>${temp.age}</td>
<td>${temp.address}</td>
<td>${temp.qq}</td>
<td>${temp.email}</td>
<td>
<a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/FindUserServlet?id=${temp.id}">修改</a>
<a class="btn btn-default btn-sm" href="javascript:del(${temp.id})" >删除</a></td>
</tr>
</c:forEach>
</table>
</form>
<div>
<nav>
<ul class="pagination">
<c:if test="${pb.currentPage>1}">
<li>
<a href="${pageContext.request.contextPath}/UserPageServlet?currentPage=${pb.currentPage-1}&rows=4" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:if test="${pb.currentPage<=1}">
<li class="disabled">
<a href="${pageContext.request.contextPath}/UserPageServlet?currentPage=${pb.currentPage-1}&rows=4" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach begin="1" end="${pb.totalPage}" var="i">
<c:if test="${pb.currentPage==i}">
<li class="active"><a href="${pageContext.request.contextPath}/UserPageServlet?currentPage=${i}&rows=4">${i}</a></li>
</c:if>
<c:if test="${pb.currentPage!=i}">
<li ><a href="${pageContext.request.contextPath}/UserPageServlet?currentPage=${i}&rows=4">${i}</a></li>
</c:if>
</c:forEach>
<c:if test="${pb.currentPage<pb.totalPage}">
<li>
<a href="${pageContext.request.contextPath}/UserPageServlet?currentPage=${pb.currentPage+1}&rows=4" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<c:if test="${pb.currentPage>=pb.totalPage}">
<li class="disabled">
<a href="${pageContext.request.contextPath}/UserPageServlet?currentPage=${pb.currentPage+1}&rows=4" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<span style="font-size:25px;margin-left: 10px">共${pb.totalCount}条记录,共${pb.totalPage}页</span>
</ul>
</nav>
</div>
</div>
</body>
</html>
带条件的分页查询
UserDao.java
List findByPage(int start,int rows,User user);
int findTotalCount(User user);
只需要在两个方法里面加上User user参数。
UserDaoImpl.java
@Override
public List<User> findByPage(int start, int rows,User user) {
StringBuilder sb = new StringBuilder("select * from user where 1=1");
//为“?”封装参数值
List params = new ArrayList();
if(user.getName()!=null&&!user.getName().equals("")){
sb.append( " and name like ?");
params.add("%"+user.getName()+"%");
}
if(user.getAddress()!=null&&!user.getAddress().equals("")){
sb.append( " and address like ?");
params.add("%"+user.getAddress()+"%");
}
if(user.getEmail()!=null&& !user.getEmail().equals("")){
sb.append(" and email like ?");
params.add("%"+user.getEmail()+"%");
}
sb.append(" limit ?,?");
params.add(start);
params.add(rows);
List<User> list = template.query(sb.toString(), new BeanPropertyRowMapper<>(User.class), params.toArray());
return list;
}
@Override
public int findTotalCount(User user) {
StringBuilder sb = new StringBuilder("select count(*) from user where 1=1");
List params = new ArrayList();
if(user.getName()!=null&&!user.getName().equals("")){
sb.append( " and name like ?");
params.add("%"+user.getName()+"%");
}
if(user.getAddress()!=null&&!user.getAddress().equals("")){
sb.append( " and address like ?");
params.add("%"+user.getAddress()+"%");
}
if(user.getEmail()!=null&& !user.getEmail().equals("")){
sb.append(" and email like ?");
params.add("%"+user.getEmail()+"%");
}
int totalCount=0;
try {
totalCount = template.queryForObject(sb.toString(), Integer.class,params.toArray());
}catch(Exception ex){
}
return totalCount;
}
UserService.java & UserService.java
参数中加上User user就行。
UserPageServlet.java
需要接受前台查询框中输入的内容,封装进user对象中传给后台。
//处理请求乱码
request.setCharacterEncoding("utf-8");
//接收查询条件
Map<String, String[]> parameterMap = request.getParameterMap();
//将查询条件封装到User对象中
User user = new User();
try {
BeanUtils.populate(user,parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
list.jsp
list页面中超链的位置需要回显查询输入的内容,所有分页链接的位置都要加上。
<li ><a href="${pageContext.request.contextPath}/UserPageServlet?currentPage=${i}&rows=4&name=${user.name}&address=${user.address}&email=${user.email}">${i}</a></li>
大体功能基本上已经完成了,一个小小的案例就做了几天了,难受啊,接下来再学习几天做一个网页javaweb阶段的学习就结束了。