jsp分页

今天写了个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}
&nbsp;&nbsp;&nbsp;
                        
<c:choose>
                            
<c:when test="${requestScope.pageCount <= 10}">
                                
<c:if test="${requestScope.pageNo != 1}">
                                        
<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}">
                                            
<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}">
                                    
<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}">
                                        
<href="ServletX?model=emp&event=partitionPage&pageNo=1">1</a>
                                        
<href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo - 1}"><<</a>
                                        
<href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo - 2}">${requestScope.pageNo - 2}</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}">
                                                
<href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo + num}">${requestScope.pageNo + num}</a>
                                            
</c:if>
                                        
</c:forEach>
                                        
<href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo + 1}">>></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}">
                                        
<href="ServletX?model=emp&event=partitionPage&pageNo=1">1</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}">
                                                    
<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>
                                        
<href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo + 1}">>></a>
                                    
</c:when>
                                    
                                    
<c:when test="${requestScope.pageNo <= 3 && requestScope.pageNo > 1}">
                                        
<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}">
                                                    
<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>
                                        
<href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo + 1}">>></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}">
                                                    
<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>
                                        
<href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageNo + 1}">>></a>
                                        
<href="ServletX?model=emp&event=partitionPage&pageNo=${requestScope.pageCount}">..${requestScope.pageCount}</a>
                                    
</c:when>
                                    
                                    
<c:when test="${requestScope.pageNo == requestScope.pageCount}">
                                        
<href="ServletX?model=emp&event=partitionPage&pageNo=1">1</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}">
                                                    
<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;
    }

}

以上程序中有一些代码是用于编辑数据用的,如用于存储职位,部门编号的集合等

posted on 2008-04-30 17:30 非凡DZ 阅读(4250) 评论(11)  编辑  收藏 所属分类: J2EE

评论

# re: jsp分页 2008-04-30 18:41 yuxianghong

看了一下你写的,在数据库查询时,你好象是把所有的数据都查出来了,这样可能效率不是很好.  回复  更多评论   

# re: jsp分页 2008-05-03 15:01 fejay

学习了  回复  更多评论   

# re: jsp分页[未登录] 2008-05-03 20:10 jimmy

要是上百万条记录呢,不是没次都都查出来吧  回复  更多评论   

# re: jsp分页 2008-05-03 21:59 非凡DZ

确实就是效率问题 每次都需要查询所有的记录 这个程序只是简单的实现了下效果   回复  更多评论   

# re: jsp分页 2008-05-04 20:11 ky

分页显示学习了,再加上分页查询吧。  回复  更多评论   

# re: jsp分页 2008-05-05 15:37 爱上对方

晕,虽然实现了分页,但你看你页面代码,这么复杂,没有效率啊  回复  更多评论   

# re: jsp分页 2008-05-05 16:03 非凡DZ

其实页面代码我认为还不是特别复杂,可能是这个风格的blog宽度不够,所以初次看这个程序的代码比较繁琐
分页的时候无非就是根据每页记录数和总记录数得到总的页数,然后将总页数分成大于10和小于10两种情况,再分别就当前页进行一下判断就好了。
我看一些朋友提到效率问题,这两天我也是一直在想,如果真的有上千上万条,甚至百万条分页,恐怕也很少有人有耐心一直翻下去,况且需要用分页显示的数据恐怕也没有那么庞大吧  回复  更多评论   

# re: jsp分页 2008-05-14 17:14 咸鱼

@非凡DZ
会有上千上万条带分页的
我现在开发的系统 对于上百万条 是很平常的
而且经常会用此查询的。
不要觉得不可能 很多bug都是在否定的前提下 产生。
总觉得不可能发生 它就是那么发生了。  回复  更多评论   

# re: jsp分页 2008-08-16 12:54 hexiaozhen

spring+hibernate 3.0+struts 2.0的实现过程能否发下,我想看看实现过程,谢了  回复  更多评论   

# re: jsp分页 2008-08-18 20:39 非凡DZ

最近恐怕够呛,时间比较紧张,有时间的话会写的  回复  更多评论   

# re: jsp分页[未登录] 2008-09-16 16:32 Stephen

这样做太麻烦了,有没有更合理更简单的方法呢?比如在查询语句上做?  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航:
 
<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

常用链接

留言簿(2)

随笔分类(19)

随笔档案(19)

友情链接

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜