bootstrap框架下使用Servlet和JSP实现分页功能

这是不使用注解的情况下完成的分页功能,换言之就是没有使用任何框架。
首先,创建一个分页的工具类:

package zz.winterWork.domain;

import java.util.List;

/**
 * @author Administrator 分页
 * @param <T>
 */
public class PageBean<T> {
	private int currentPage = 1; // 当前页, 默认显示第一页
	private int pageCount = 4; // 每页显示的行数(查询返回的行数), 默认每页显示4行
	private int totalCount; // 总记录数
	private int totalPage; // 总页数 = 总记录数 / 每页显示的行数 (+ 1)
	private List<T> pageData; // 分页查询到的数据

	// 返回总页数
	public int getTotalPage() {
		if (totalCount % pageCount == 0) {
			totalPage = totalCount / pageCount;
		} else {
			totalPage = totalCount / pageCount + 1;
		}
		return totalPage;
	}

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

	public int getCurrentPage() {
		return currentPage;
	}

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

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public int getTotalCount() {
		return totalCount;
	}

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

	public List<T> getPageData() {
		return pageData;
	}

	public void setPageData(List<T> pageData) {
		this.pageData = pageData;
	}
}

这里以employee为例:
先创建一个实体类:

package zz.winterWork.domain;

import java.util.Date;

public class Employee {
	private Long id;
	private String eName;
	private Integer age;
	private Integer sex;
	private Long phone;
	private String email;
	private Date inDate;

	public String getdName() {
		return dName;
	}

	public void setdName(String dName) {
		this.dName = dName;
	}

	private Integer deptId;
	private String dName;

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String geteName() {
		return eName;
	}

	public void seteName(String eName) {
		this.eName = eName;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public Integer getSex() {
		return sex;
	}

	public void setSex(Integer sex) {
		this.sex = sex;
	}

	public Long getPhone() {
		return phone;
	}

	public void setPhone(Long phone) {
		this.phone = phone;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}


	public Integer getDeptId() {
		return deptId;
	}

	public void setDeptId(Integer deptId) {
		this.deptId = deptId;
	}

	@Override
	public String toString() {
		return "[id=" + id + ", eName=" + eName + ", age=" + age + ", sex=" + sex + ", phone=" + phone + ", email="
				+ email + ", date=" + inDate + ", deptId=" + deptId + "]";
	}

	public Date getInDate() {
		return inDate;
	}

	public void setInDate(Date inDate) {
		this.inDate = inDate;
	}
}

然后创建dao层方法:

package zz.winterWork.Dao;

import java.util.List;

import zz.winterWork.domain.Employee;
import zz.winterWork.domain.PageBean;

/**
 * @author Administrator
 *	员工表
 */
public interface EmpDao {
	/*增加员工*/
	void addEmp(Employee emp);
	/*显示所有员工信息*/
	List<Employee> serachAll();
	/*显示所有员工信息*/
	void serachSome(String str,PageBean<Employee> pb);
	/*获取分页数据*/
	void getAll(PageBean<Employee> pb);
	/*数据总行数*/
	int getTotalCount();
	/*修改员工信息*/
	void editEmp(Employee emp);
	/*根据ID查询员工信息*/
	Employee serachById(Long id);
	/*删除员工*/
	void delete(Long id);
}

dao层方法实现:

package zz.winterWork.DaoImp;

import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import zz.winterWork.Dao.EmpDao;
import zz.winterWork.domain.Employee;
import zz.winterWork.domain.PageBean;
import zz.winterWork.util.DbcpUtils;

public class EmpDaoImp implements EmpDao {

	private QueryRunner qr = new QueryRunner(DbcpUtils.getDataSource());

	/*
	 * (non-Javadoc)
	 * 
	 * @see zz.winterWork.Dao.EmpDao#addEmp(zz.winterWork.domain.Employee) 添加员工
	 */
	@Override
	public void addEmp(Employee emp) {
		String sql = "insert into q_emp(eName,age,sex,phone,email,inDate,deptId) values(?,?,?,?,?,?,?)";
		try {
			qr.update(sql, emp.geteName(), emp.getAge(), emp.getSex(), emp.getPhone(), emp.getEmail(), emp.getInDate(),
					emp.getDeptId());
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see zz.winterWork.Dao.EmpDao#serachAll() 查询所有员工
	 */
	@Override
	public List<Employee> serachAll() {
		String sql = "select e.*,d.dName from q_emp e,q_dept d where e.deptId=d.deptId order by e.id desc";
		try {
			return qr.query(sql, new BeanListHandler<Employee>(Employee.class));
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see zz.winterWork.Dao.EmpDao#editEmp(zz.winterWork.domain.Employee)
	 * 修改员工信息
	 */
	@Override
	public void editEmp(Employee emp) {
		String sql = "update q_emp set eName=?,age=?,sex=?,phone=?,email=?,inDate=?,deptId=? where id=?";
		try {
			qr.update(sql, emp.geteName(), emp.getAge(), emp.getSex(), emp.getPhone(), emp.getEmail(), emp.getInDate(),
					emp.getDeptId(), emp.getId());
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see zz.winterWork.Dao.EmpDao#serachById(java.lang.Long) 根据ID定位员工
	 */
	@Override
	public Employee serachById(Long id) {
		String sql = "select * from q_emp where id=?";
		try {
			return qr.query(sql, new BeanHandler<Employee>(Employee.class), id);
		} catch (Exception e) {
			// TODO: handle exception
		}
		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see zz.winterWork.Dao.EmpDao#delete(java.lang.Long) 根据ID删除员工
	 */
	@Override
	public void delete(Long id) {
		String sql = "delete from q_emp where id=?";
		try {
			qr.execute(sql, id);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	@Override
	public void serachSome(String str,PageBean<Employee> pb) {
		String str2 = str.replace("*", "count(*)");
		try {
			// 执行查询, 返回结果的第一行的第一列
			Long c2 = qr.query(str2, new ScalarHandler<Long>());
			int vae = c2.intValue();
			pb.setTotalCount(vae);
			
			// 判断
			if (pb.getCurrentPage() <= 0) {
				pb.setCurrentPage(1); // 把当前页设置为1
			} else if (pb.getCurrentPage() > pb.getTotalPage()) {
				pb.setCurrentPage(pb.getTotalPage()); // 把当前页设置为最大页数
			}

			// 1. 获取当前页: 计算查询的起始行、返回的行数
			int currentPage = pb.getCurrentPage();
			int index = (currentPage - 1) * pb.getPageCount(); // 查询的起始行
			int count = pb.getPageCount(); // 查询返回的行数
			// 3. 分页查询数据; 把查询到的数据设置到pb对象中
			str +=" order by id desc limit ?,?";
			List<Employee> some = qr.query(str, new BeanListHandler<Employee>(Employee.class), index, count);
			// 设置到pb对象中
			pb.setPageData(some);
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see zz.winterWork.Dao.EmpDao#getAll(zz.winterWork.domain.PageBean) 获取总页数
	 */
	@Override
	public void getAll(PageBean<Employee> pb) {
		// 2. 查询总记录数; 设置到pb对象中
		int totalCount = this.getTotalCount();
		pb.setTotalCount(totalCount);
		/*
		 * 问题: jsp页面,如果当前页为首页,再点击上一页报错! 如果当前页为末页,再点下一页显示有问题!
		 *  解决: 1. 如果当前页 <= 0, 当前页设置当前页为1; 
		 *  2. 如果当前页 > 最大页数; 当前页设置为最大页数
		 */
		// 判断
		if (pb.getCurrentPage() <= 0) {
			pb.setCurrentPage(1); // 把当前页设置为1
		} else if (pb.getCurrentPage() > pb.getTotalPage()) {
			pb.setCurrentPage(pb.getTotalPage()); // 把当前页设置为最大页数
		}

		// 1. 获取当前页: 计算查询的起始行、返回的行数
		int currentPage = pb.getCurrentPage();
		int index = (currentPage - 1) * pb.getPageCount(); // 查询的起始行
		int count = pb.getPageCount(); // 查询返回的行数
		// 3. 分页查询数据; 把查询到的数据设置到pb对象中
		String sql = "select e.*,d.dName from q_emp e,q_dept d where e.deptId=d.deptId order by e.id desc limit ?,?";

		try {
			// 根据当前页,查询当前页数据(一页数据)
			List<Employee> pageData = qr.query(sql, new BeanListHandler<Employee>(Employee.class), index, count);
			// 设置到pb对象中
			pb.setPageData(pageData);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see zz.winterWork.Dao.EmpDao#getTotalCount() 获取总数据的行数
	 */
	@Override
	public int getTotalCount() {
		String sql = "select count(*) from q_emp";
		try {
			// 执行查询, 返回结果的第一行的第一列
			Long count = qr.query(sql, new ScalarHandler<Long>());
			return count.intValue();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}

controller控制层代码:

package zz.winterWork.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itsource.annotation.Controller;
import cn.itsource.annotation.RequestMapping;
import zz.winterWork.Dao.AdminDao;
import zz.winterWork.Dao.DeptDao;
import zz.winterWork.Dao.EmpDao;
import zz.winterWork.DaoImp.AdminDaoImp;
import zz.winterWork.DaoImp.DeptDaoImp;
import zz.winterWork.DaoImp.EmpDaoImp;
import zz.winterWork.domain.Admin;
import zz.winterWork.domain.Dept;
import zz.winterWork.domain.Employee;
import zz.winterWork.domain.PageBean;
import zz.winterWork.util.MyBeanUtils;
import zz.winterWork.util.UpLoadUtils;

@Controller("/login")
public class Controller2 {

	/* 创建引用对象 */
	private AdminDao adD = new AdminDaoImp();
	private DeptDao dD = new DeptDaoImp();
	private EmpDao eD = new EmpDaoImp();
	private EmpDao emp = new EmpDaoImp();
	// 跳转资源
	private String uri;
	
	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.
	 * HttpServletRequest, javax.servlet.http.HttpServletResponse) 跳转页面,显示所有员工
	 */
	@RequestMapping("doGet.do")
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try {
			// 1. 获取“当前页”参数; (第一次访问当前页为null)
			String currPage = request.getParameter("currentPage");
			// 判断
			if (currPage == null || "".equals(currPage.trim())) {
				currPage = "1"; // 第一次访问,设置当前页为1;
			}
			// 转换
			int currentPage = Integer.parseInt(currPage);
			// 2. 创建PageBean对象,设置当前页参数; 传入service方法参数
			PageBean<Employee> pageBean = new PageBean<Employee>();
			pageBean.setCurrentPage(currentPage);

			// 3. 调用service
			emp.getAll(pageBean); // 【pageBean已经被dao填充了数据】

			// 4. 保存pageBean对象,到request域中
			request.setAttribute("pageBean", pageBean);
			// 5. 跳转
			uri = "/employee.jsp";
		} catch (Exception e) {
			e.printStackTrace(); // 测试使用
			// 出现错误,跳转到错误页面;给用户友好提示
			uri = "/error.jsp";
		}
		request.getRequestDispatcher(uri).forward(request, response);

	}

	@RequestMapping("doPost.do")
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
}

前端分页代码:

<!-- 分页 -->
					<ul class="pagination" style="margin-left: 210px;">
						<li><a>当前${requestScope.pageBean.currentPage }/${requestScope.pageBean.totalPage }页
						</a></li>
						<li><a
							href="${pageContext.request.contextPath }/login/doGet.do?currentPage=${requestScope.pageBean.currentPage-1}">&laquo;</a></li>
						<li><a
							href="${pageContext.request.contextPath }/login/doGet.do?currentPage=1">首页</a></li>
						<li><a
							href="${pageContext.request.contextPath }/login/doGet.do?currentPage=${requestScope.pageBean.totalPage}">末页</a></li>
						<li><a
							href="${pageContext.request.contextPath }/login/doGet.do?currentPage=${requestScope.pageBean.currentPage+1}">&raquo;</a>
						</li>
						<li>
							<div style="padding: 0px 340px;">
								<form class="bs-example bs-example-form" role="form">
									<div class="row">
										<div class="col-lg-6">
											<div class="input-group">
												<input type="text" id="page" placeholder="页数" class="form-control"> <span
													class="input-group-btn">
													<button class="btn btn-primary" "getPage();" type="button">Go!
													</button>
												</span>
											</div>
											<!-- /input-group -->
										</div>
										<!-- /.col-lg-6 -->
									</div>
									<!-- /.row -->
								</form>
							</div>
						</li>
					</ul>

跳页的JS代码:

function getPage() {
		var page = document.getElementById('page').value;
		if (page<=0) {
			alert("请正确输入页码数!!");
		} else {
			location.href = "/ojbk/login/doGet.do?currentPage=" + page;
		}
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值