今天写了个jsp的分页程序,以前在做jsp项目的时候,分页采用的是“首页,尾页,上一页,下一页”的形式,虽然分页没有问题,但总感觉不够友好,现在很多论坛都采用这种模式,即根据用户请求的页面,列出请求页面和该页面的前几页和后几页,看上去比较舒服,今天就模仿“编程中国论坛”的分页风格练了练,后台查询数据库的分页代码与之前做过的基本没有变化,主要是在jsp页面上多了些判断,效果实现了,至于效率我就不好说了,如果哪位看过下面代码的朋友有什么好方法,还望大家能够一起交流,共同进步。
该程序采用了MVC设计模式,代码中的ServletX为总控制器,根据model值将请求转至相应模块,后台数据库为Oracle,由于emp表中数据只有15条,所以我每页只显示一条记录,效果如图:
1,用户登录,若登录成功转到main.jsp页面,以下为用户控制器代码:
package controls;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import entitys.User;
import routines.Translation;
import operater.*;
import java.util.*;
public class UserServlet extends HttpServlet {
/** *//**
* Constructor of the object.
*/
public UserServlet() {
super();
}
/** *//**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/** *//**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String event = request.getParameter("event");
if(event.equals("login")){
String userName = Translation.transCode(request.getParameter("userName"));
String password = Translation.transCode(request.getParameter("password"));
User user = new User();
user.setUserName(userName);
user.setPassword(password);
OperUser obj = new OperUser();
if(obj.isExist(user)){
this.mySet(request,"1");
request.getRequestDispatcher("main.jsp").forward(request, response);
return;
}else{
System.out.println("失败");
}
}
}
private void mySet(HttpServletRequest request,Object pageNo){
OperEmp emp = new OperEmp();
//向请求中存储关于分页的信息
ArrayList aryInfo = emp.getEmp(pageNo);
request.setAttribute("data", aryInfo.get(0));
request.setAttribute("pageNo", aryInfo.get(1));
request.setAttribute("pageCount", aryInfo.get(2));
request.setAttribute("rowsCount", aryInfo.get(3));
ArrayList aryNumber = new ArrayList();
for(int i=1;i<=10;i++){
aryNumber.add(new Integer(i));
}
request.setAttribute("number", aryNumber);
ArrayList aryNumberR = new ArrayList();
for(int i=9;i>=0;i--){
aryNumberR.add(new Integer(i));
}
request.setAttribute("numberR", aryNumberR);
//向请求中存储关于职位的信息
ArrayList aryJob = emp.getJob();
request.setAttribute("job", aryJob);
//向请求中存储关于部门编号的信息
OperDept dept = new OperDept();
ArrayList aryDeptno = dept.getDeptno();
request.setAttribute("deptno", aryDeptno);
}
/** *//**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
/** *//**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
2,main.jsp页面,即显示分页的页面的代码:
<%@page contentType="text/html" pageEncoding="GBK"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>职员信息</title>
<script type="text/javascript">
function go(){
var page = document.frmMain.pageNo.value;
window.location.href = 'ServletX?model=emp&event=partitionPage&pageNo=' + page;
return;
}
</script>
</head>
<body>
<form name="frmMain" action="ServletX" method="get">
<table border="1" align="center">
<caption>
职员信息表
</caption>
<tr>
<th onclick="selectAll(this)" style="cursor:hand">全选</th>
<th>职员编号</th>
<th>职员姓名</th>
<th>职位</th>
<th>直接上司</th>
<th>入职时间</th>
<th>薪金</th>
<th>奖金</th>
<th>部门编号</th>
<th>操作</th>
</tr>
<c:forEach var="obj" items="${requestScope.data}">
<tr>
<td align="center"><input type="checkbox" name="${obj.empNo}"/></td>
<td>${obj.empNo}</td>
<td>${obj.ename}</td>
<td>${obj.job}</td>
<td>${obj.mgr}</td>
<td>${obj.hireDate}</td>
<td>${obj.sal}</td>
<td>${obj.comm}</td>
<td>${obj.deptno}</td>
<td><input type="button" value="编辑"/></td>
</tr>
</c:forEach>
<tr>
<td colspan="10" align="left">
总记录数:${requestScope.rowsCount}
<c:choose>
<c:when test="${requestScope.pageCount <= 10}">
<c:if test="${requestScope.pageNo != 1}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo - 1}"><<</a>
</c:if>
<c:forEach var="num" begin="0" end="${requestScope.pageCount - 1}" items="${requestScope.number}">
<c:choose>
<c:when test="${requestScope.pageNo != num}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=${num}">${num}</a>
</c:when>
<c:otherwise>
<font color="red">${requestScope.pageNo}</font>
</c:otherwise>
</c:choose>
</c:forEach>
<c:if test="${requestScope.pageNo != requestScope.pageCount}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo + 1}">>></a>
</c:if>
</c:when>
<c:otherwise>
<c:choose>
<c:when test="${requestScope.pageNo > 3 && requestScope.pageNo < requestScope.pageCount - 7}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=1">1</a>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo - 1}"><<</a>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo - 2}">${requestScope.pageNo - 2}</a>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo - 1}">${requestScope.pageNo - 1}</a>
<font color="red">${requestScope.pageNo}</font>
<c:forEach var="num" items="${requestScope.number}" begin="0" end="6">
<c:if test="${requestScope.pageNo + num <= pageCount}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo + num}">${requestScope.pageNo + num}</a>
</c:if>
</c:forEach>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo + 1}">>></a>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageCount}">..${requestScope.pageCount}</a>
</c:when>
<c:when test="${requestScope.pageNo > 3 && requestScope.pageNo >= requestScope.pageCount -7 && requestScope.pageNo != requestScope.pageCount}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=1">1</a>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo - 1}"><<</a>
<c:forEach var="numR" items="${requestScope.numberR}" begin="0">
<c:choose>
<c:when test="${requestScope.pageCount - numR != requestScope.pageNo}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageCount - numR}">${requestScope.pageCount - numR}</a>
</c:when>
<c:otherwise>
<font color="red">${requestScope.pageNo}</font>
</c:otherwise>
</c:choose>
</c:forEach>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo + 1}">>></a>
</c:when>
<c:when test="${requestScope.pageNo <= 3 && requestScope.pageNo > 1}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo - 1}"><<</a>
<c:forEach var="num" items="${requestScope.number}">
<c:choose>
<c:when test="${requestScope.pageNo != num}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=${num}">${num}</a>
</c:when>
<c:otherwise>
<font color="red">${requestScope.pageNo}</font>
</c:otherwise>
</c:choose>
</c:forEach>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo + 1}">>></a>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageCount}">..${requestScope.pageCount}</a>
</c:when>
<c:when test="${requestScope.pageNo == 1}">
<c:forEach var="num" items="${requestScope.number}">
<c:choose>
<c:when test="${requestScope.pageNo != num}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=${num}">${num}</a>
</c:when>
<c:otherwise>
<font color="red">${requestScope.pageNo}</font>
</c:otherwise>
</c:choose>
</c:forEach>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo + 1}">>></a>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageCount}">..${requestScope.pageCount}</a>
</c:when>
<c:when test="${requestScope.pageNo == requestScope.pageCount}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=1">1</a>
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo - 1}"><<</a>
<c:forEach var="numR" items="${requestScope.numberR}" begin="0">
<c:choose>
<c:when test="${requestScope.pageCount - numR != requestScope.pageNo}">
<a href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageCount - numR}">${requestScope.pageCount - numR}</a>
</c:when>
<c:otherwise>
<font color="red">${requestScope.pageNo}</font>
</c:otherwise>
</c:choose>
</c:forEach>
</c:when>
</c:choose>
</c:otherwise>
</c:choose>
<input name="pageNo" type="text" size="3"/>
<input type="button" onclick="go()" value="GO"/>
</td>
</tr>
<tr>
<td colspan="10" align="center">
<input type="button" value="增加" onclick="addRow()"/>
<input type="submit" value="保存" onclick="saveRow()"/>
<input type="submit" value="删除" onclick="deleteRow()"/>
</td>
</tr>
</table>
</form>
</body>
</html>
3,用户点击相应页面链接或通过文本框请求页面时,即emp表的控制器,方法类似于用户登录成功后的处理,代码如下:
/**//*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controls;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import entitys.Emp;
import routines.Translation;
import operater.*;
import java.util.*;
/** *//**
*
* @author Administrator
*/
public class EmpServlet extends HttpServlet {
/** *//**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/**//* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet EmpServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet EmpServlet at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
*/
} finally {
out.close();
}
}
/** *//**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String event = request.getParameter("event");
if(event.equals("partitionPage")){
String pageNo = request.getParameter("pageNo");
this.mySet(request, pageNo);
request.getRequestDispatcher("main.jsp").forward(request, response);
return;
}
}
private void mySet(HttpServletRequest request, Object pageNo) {
OperEmp emp = new OperEmp();
//向请求中存储关于分页的信息
ArrayList aryInfo = emp.getEmp(pageNo);
request.setAttribute("data", aryInfo.get(0));
request.setAttribute("pageNo", aryInfo.get(1));
request.setAttribute("pageCount", aryInfo.get(2));
request.setAttribute("rowsCount", aryInfo.get(3));
ArrayList aryNumber = new ArrayList();
for (int i = 1; i <= 10; i++) {
aryNumber.add(new Integer(i));
}
request.setAttribute("number", aryNumber);
ArrayList aryNumberR = new ArrayList();
for (int i = 9; i >=0; i--) {
aryNumberR.add(new Integer(i));
}
request.setAttribute("numberR", aryNumberR);
//向请求中存储关于职位的信息
ArrayList aryJob = emp.getJob();
request.setAttribute("job", aryJob);
//向请求中存储关于部门编号的信息
OperDept dept = new OperDept();
ArrayList aryDeptno = dept.getDeptno();
request.setAttribute("deptno", aryDeptno);
}
/** *//**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
/** *//**
* Returns a short description of the servlet.
*/
public String getServletInfo() {
return "Short description";
}
}
4,该类为分页查询代码,用户可随需要改变页面显示的记录行数,代码如下:
package operater;
import java.sql.*;
import entitys.Emp;
import db.DataBase;
import java.util.*;
/** *//**
*该类用于完成对用户信息表操作的业务逻辑
* @author 非凡DZ
*/
public class OperEmp {
private Connection con = null;
private PreparedStatement pstn = null;
private ResultSet rs = null;
private int pageCount = 0;//记录总页数
private int pageNo = 0;//记录要前往的页数
private int pageRows = 6;//记录每页的行数
private int rowsCount = 0;//记录总行数
private int i = 0;//用于控制循环次数
/** *//**
* 根据请求的页数得到相应的数据
* @param page 请求的页码
* @return 请求页码中的信息,请求页码及总页数
*/
public ArrayList getEmp(Object page){
if(page == null){
pageNo = 1;
}else{
pageNo = Integer.parseInt(page.toString());
}
if(pageNo < 1){
pageNo = 1;
}
DataBase db = new DataBase();
con = db.getConnection();
String sql = "select * from emp";
ArrayList aryInfo = new ArrayList();
ArrayList aryEmp = new ArrayList();//记录所有
try {
pstn = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = pstn.executeQuery();
rs.last();
rowsCount = rs.getRow();
pageCount = (rowsCount + pageRows - 1) / pageRows;
if(pageNo > pageCount){
pageNo = pageCount;
}
if(pageCount > 0){
rs.absolute((pageNo - 1) * pageRows + 1);
}
while(i < pageRows && !rs.isAfterLast()){
Emp emp = new Emp();
emp.setEmpNo(rs.getInt(1));
emp.setEname(rs.getString(2));
emp.setJob(rs.getString(3));
emp.setMgr(rs.getInt(4));
emp.setHireDate(rs.getString(5));
emp.setSal(rs.getFloat(6));
emp.setDeptno(rs.getInt(7));
aryEmp.add(emp);
rs.next();
i++;
}
} catch (Exception e) {
System.out.println("分页异常"+e.getMessage());
}
aryInfo.add(aryEmp);
aryInfo.add(new Integer(pageNo));//当前页数
aryInfo.add(new Integer(pageCount));//总页数
aryInfo.add(new Integer(rowsCount));//总行数
return aryInfo;
}
/** *//**
* 得到所有职位
* @return
*/
public ArrayList getJob(){
DataBase db = new DataBase();
con = db.getConnection();
boolean flag = false;
String sql = "select job from emp";
ArrayList aryJob = new ArrayList();
try{
pstn = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
rs = pstn.executeQuery();
while (rs.next()) {
flag = false;
for (int i = 0; i < aryJob.size(); i++) {
String job = (String) aryJob.get(i);
if (job.equals(rs.getString(1))) {
flag = true;
break;
}
}
if (!flag) {
aryJob.add(rs.getString(1));
}
}
}catch(Exception e){
System.out.println("职位查询异常"+e.getMessage());
}
return aryJob;
}
}
以上程序中有一些代码是用于编辑数据用的,如用于存储职位,部门编号的集合等