struts.分页

 --------------------------------------------------------------------------------
 ********分页类Pager.java,负责生成分页导航条********

package page;

/**
 * 分页代码
 * <p>Title: 分页</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: BCS</p>
 * @author Alex
 * @version 1.0
 */
public class Pager {
  private int offset;
  private int size;
  private int length;
  private String url;
  private String pageHeader;
  public Pager(int offset, int size, int length, String url, String pageHeader) {
    this.offset = offset;
    this.size = size;
    this.length = length;
    this.url = url;
    this.pageHeader = pageHeader;
  }

  /**
   * 返回分页导航条
   * @param offset int 起始记录的位置
   * @param size int 总记录数
   * @param length int 步长
   * @param url String .do的url
   * @param pageHeader String 导航条的前缀文字提示
   * @return String
   */
  public String getPageNavigation() {
    String pageNavigation = ""; //最终返回的分页导航条
    //记录数超过一页,需要分页
    if (size > length) {
      String pref; //前缀
      if (url.indexOf("?") > -1) {
        //如果url中已经包含了其他的参数,就把offset参数接在后面
        pref = "&";
      }
      else {
        //如果url中没有别的参数
        pref = "?";
      }
      //如果导航条包含header
      if (pageHeader != null && pageHeader.length() > 0) {
        pageNavigation = pageHeader + " : ";
      }
      //如果不是第一页,导航条将包含“<<”(第一页)和“<”(前一页)
      if (offset > 0) {
        pageNavigation += "<a href='" + url + pref + "offset=0'>[<<]</a>\n" +
            "<a href='" + url + pref + "offset=" + (offset - length) +
            "'>[<]</a>\n";
      }
      //导航条中,排头的那一页的offset值
      int startOffset;
      //位于导航条中间的那一页的offset值(半径)
      int radius = constants.MAX_PAGE_INDEX / 2 * length;
      //如果当前的offset值小于半径
      if (offset < radius || this.pageCount() <= constants.MAX_PAGE_INDEX) {
        //那么第一页排头
        startOffset = 0;
      }
      else if (offset < size - radius) {
        startOffset = offset - radius;
      }
      else {
        startOffset = (size / length - constants.MAX_PAGE_INDEX) * length;
      }
      for (int i = startOffset;
           i < size && i < startOffset + constants.MAX_PAGE_INDEX * length;
           i += length) {
        if (i == offset) {
          //当前页号,加粗显示
          pageNavigation += "<b>" + (i / length + 1) + "</b>\n";
        }
        else {
          //其他页号,包含超链接
          pageNavigation += "<a href='" + url + pref + "offset=" + i + "'>" +
              (i / length + 1) + "</a>\n";
        }
      }
      //如果不是最后一页,导航条将包含“>”(下一页)和“>>”(最后一页)
      if (offset < size - length) {
        pageNavigation += "<a href='" + url + pref + "offset=" +
            (offset + length) + "'>[>]</a>\n" +
            "<a href='" + url + pref + "offset=" + lastPageOffset() +
            "'>[>>]</a>\n";
      }
//      System.out.println("radius : " + radius);
//      System.out.println("start offset : " + startOffset);
      return pageNavigation;
    }
    //记录不超过一页,不需要分页
    else {
      return "";
    }
  }

  /**
   * 返回分页后的总页数
   * @param size int 总记录数
   * @param length int 每页的记录数
   * @return int
   */
  public int pageCount() {
    int pagecount = 0;
    if (size % length == 0) {
      pagecount = size / length;
    }
    else {
      pagecount = size / length + 1;
    }
    return pagecount;
  }

  /**
   * 返回最后一页的记录数
   * @param size int 总记录数
   * @param length int 每页的记录数
   * @return int
   */
  public int lastPageSize() {
    int lastpagesize = 0;
    if (size % length == 0) {
      lastpagesize = length;
    }
    else {
      lastpagesize = size % length;
    }
    return lastpagesize;
  }

  /**
   * 返回最后一页的起始记录位置
   * @param size int 总记录数
   * @param length int 每页的记录数
   * @return int
   */
  public int lastPageOffset() {
    return size - lastPageSize();
  }

  public int getOffset() {
    return offset;
  }

  public void setOffset(int offset) {
    this.offset = offset;
  }

  public int getSize() {
    return size;
  }

  public void setSize(int size) {
    this.size = size;
  }

  public int getLength() {
    return length;
  }

  public void setLength(int length) {
    this.length = length;
  }

  public String getUrl() {
    return url;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  public String getPageHeader() {
    return pageHeader;
  }

  public void setPageHeader(String pageHeader) {
    this.pageHeader = pageHeader;
  }
}

********数据处理类empDAO.java,负责访问DB,获取当前页面需要显示的记录********

package page;

import java.sql.*;
import java.util.*;

public class empDAO {
  public empDAO() {
  }

  /**
   * 从offset位置起始,返回length条记录
   * @param offset int 起始的记录位置
   * @param length int 步长
   * @param conn Connection 数据库连接
   * @return ArrayList
   */
  public ArrayList findAllEmp(int offset, int length, Connection conn) throws
      SQLException {
    PreparedStatement ps = null;
    ResultSet rs = null;
    ArrayList emps = new ArrayList();
    empVO empvo = null;
    String strSql = "select empno, ename from emp where rowid not in (select rowid from emp where rownum <= ?) and rownum <= ?";
    try {
      ps = conn.prepareStatement(strSql);
      ps.setInt(1, offset); //起始记录的位置
      ps.setInt(2, length); //步长
      rs = ps.executeQuery();
      while (rs != null && rs.next()) {
        empvo = new empVO();
        empvo.setEmpno(rs.getInt("empno"));
        empvo.setEname(rs.getString("ename"));
        emps.add(empvo);
      }
    }
    catch (SQLException ex) {
      ex.printStackTrace();
      throw ex;
    }
    return emps;
  }

  /**
   * 返回总的记录数
   * @param conn Connection
   * @throws SQLException
   * @return int
   */
  public int getRsTotalCount(Connection conn) throws SQLException {
    PreparedStatement ps = null;
    ResultSet rs = null;
    int rsCount = 0;
    String strSql = "select count(empno) as empCount from emp";
    try {
      ps = conn.prepareStatement(strSql);
      rs = ps.executeQuery();
      if (rs != null && rs.next()) {
        rsCount = rs.getInt("empCount");
      }
    }
    catch (SQLException ex) {
      ex.printStackTrace();
      throw ex;
    }
    return rsCount;
  }
}

********业务类empBO.java,调用empDAO类********

package page;

import java.util.*;

/**
 * BO类
 * <p>Title: 分页</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: BCS</p>
 * @author Alex
 * @version 1.0
 */
public class empBO {
  private DBPool db = DBPool.newInstance();
  private empDAO empdao = new empDAO();

  public empBO() {
  }

  /**
   * 从offset位置起始,返回length条记录
   * @param offset int 起始
   * @param length int 步长
   * @throws Exception
   * @return ArrayList
   */
  public ArrayList findAllEmp(int offset, int length) throws Exception {
    ArrayList emps = new ArrayList();
    try {
      emps = empdao.findAllEmp(offset, length, db.getConnection());
    }
    catch (Exception ex) {
      throw ex;
    }
    finally {
      db.release();
    }
    return emps;
  }

  /**
   * 返回总的记录数
   * @throws Exception
   * @return int
   */
  public int getRsTotalCount() throws Exception {
    int rsCount = 0;
    try {
      rsCount = empdao.getRsTotalCount(db.getConnection());
    }
    catch (Exception ex) {
      throw ex;
    }
    finally {
      db.release();
    }
    return rsCount;
  }
}


********ActionForm类empForm.java********

package page;

import javax.servlet.http.*;

import org.apache.struts.action.*;

public class empForm
    extends ActionForm {
  private int offset; //起始记录的位置//每页显示的记录数
  public ActionErrors validate(ActionMapping actionMapping,
                               HttpServletRequest httpServletRequest) {
    /**@todo: finish this method, this is just the skeleton.*/
    return null;
  }

  public void reset(ActionMapping actionMapping,
                    HttpServletRequest httpServletRequest) {
    this.offset = 0; //记录默认从第一条开始显示
  }

  public int getOffset() {
    return offset;
  }

  public void setOffset(int offset) {
    this.offset = offset;
  }

}


********Action类empAction.java,控制器,调用BO类,Pager类********

package page;

import java.util.*;
import javax.servlet.http.*;

import org.apache.struts.action.*;

/**
 * 分页测试的Action
 * <p>Title: 分页</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: BCS</p>
 * @author Alex
 * @version 1.0
 */
public class empAction
    extends Action {

  public ActionForward execute(ActionMapping actionMapping,
                               ActionForm actionForm,
                               HttpServletRequest httpServletRequest,
                               HttpServletResponse httpServletResponse) {
    empForm empform = (empForm) actionForm;
    return performList(actionMapping, actionForm, httpServletRequest,
                       httpServletResponse);
  }

  private ActionForward performList(ActionMapping actionMapping,
                                    ActionForm actionForm,
                                    HttpServletRequest request,
                                    HttpServletResponse response) {
    try {
      empBO empbo = new empBO();
      //获取外部传进来的起始记录号
      int offset = ( (empForm) actionForm).getOffset();
      //获取每页的记录数
      int pagesize = constants.PAGE_SIZE;
      //获取记录集合,从offset开始,取length条记录
      ArrayList emps = empbo.findAllEmp(offset, pagesize);
      //计算所有记录的条数(总记录数)
      int size = empbo.getRsTotalCount();
      //外部url地址,得到形如: http://localhost:8088/bugMIS/showlist.do 的String
      String url = request.getContextPath() + actionMapping.getPath() + ".do";
      //实例化分页类
      Pager p = new Pager(offset, size, pagesize, url, "Page Navigation");
      //获取分页导航条
      //String pageNavigation = p.getPageNavigation();
      //将url字符串和记录集合,存入request中
      request.setAttribute("pager", p);
      request.setAttribute("emps", emps);
    }
    catch (Exception e) {
      e.printStackTrace();
      return actionMapping.findForward("failure");
    }
    return actionMapping.findForward("success");
  }
}


********数据库连接池类DBPool.java,可以使用tomcat的连接池,也可以不用,这里关闭了********

package page;

import java.sql.*;
import javax.naming.*;
import javax.sql.*;

import org.apache.commons.logging.*;

/**
 * 系统连接池类
 * <p>Title: Gantoo@91.com</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: BCS</p>
 * @author Alex
 * @version 1.0
 */
public class DBPool {
  Log log = LogFactory.getLog("DBPool"); //日志机
  private DBPool() {
  }

  private Connection conn = null;

  /* true:使用连接池
     false:不使用连接池,采用JDBC直接连接 */
  private final static boolean USE_DB_POOL = false;
  private final static String jndi_DataSource = "jdbc/BugMIS_ora";
  private final static String jdbcdriver =
      "oracle.jdbc.driver.OracleDriver";
  private final static String url =
      "jdbc:oracle:thin:@localhost:1521:myo9";
  private final static String user = "scott";
  private final static String pass = "tiger";

  public static DBPool newInstance() {
    return new DBPool();
  }

  /**
   * 切换是否使用连接池
   * */
  public Connection getConnection() {
    if (USE_DB_POOL) {
      conn = getConnectionByDBPool();
    }
    else {
      conn = getConnectionDirect();
    }
    return conn;
  }

  /**
   * 直接采用JDBC连接数据库
   * */
  private Connection getConnectionDirect() {
    try {
      Class.forName(jdbcdriver).newInstance();
      conn = DriverManager.getConnection(url, user, pass);
    }
    catch (SQLException ex) {
      log.error("Error Connection! " + ex.getMessage());
    }
    catch (ClassNotFoundException ex) {
      log.error("Driver Not Found! " + ex.getMessage());
    }
    catch (IllegalAccessException ex) {
      log.error(ex.getMessage());
    }
    catch (InstantiationException ex) {
      log.error(ex.getMessage());
    }
    return conn;
  }

  /**
   * 采用连接池
   * */
  private Connection getConnectionByDBPool() {
    try {
      Context initCtx = new InitialContext();
      Context ctx = (Context) initCtx.lookup("java:/comp/env");
      DataSource ds = (DataSource) ctx.lookup(jndi_DataSource);
      conn = ds.getConnection();
    }
    catch (NamingException ex) {
      log.error("Data Source Not Found! " + ex.getMessage());
      //System.out.println("未找到数据源" + ex.getMessage());
    }
    catch (SQLException ex1) {
      log.error("Error Connection! " + ex1.getMessage());
      //System.out.println("错误的数据连接" + ex1.getMessage());
    }
    return conn;
  }

  /**
   * 释放连接
   * */
  public void release() {
    try {
      if (!conn.isClosed()) {
        conn.close();
      }
    }
    catch (SQLException ex) {
      log.error("Connection Closing Error! " + ex.getMessage());
      //System.out.println("连接关闭失败" + ex.getMessage());
    }
  }
}


********包含常量的类constants.java,常量********

package page;

/**
 * 定义工程中公用的常量
 * <p>Title: 分页</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2005</p>
 * <p>Company: BCS</p>
 * @author Alex
 * @version 1.0
 */
public final class constants {
  public static final int MAX_PAGE_INDEX = 5; //页脚显示多少页
  public static final int PAGE_SIZE = 2; //每页的记录数
}


********测试jsp页面index.jsp,为了方便测试,嵌入了java代码,能显示就行********

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ page contentType="text/html; charset=GBK" import="java.util.*,page.*"%>
<html:html>
<head>
<title></title>
<style type="text/css">
.pt9 {  font: 10pt "宋体"}
body { font: 10pt "宋体" ; margin: 15px}
td {  font-size: 10pt}
a:hover {  font-size: 10pt; color: red; text-decoration: underline}
a:link {  font-size: 10pt; color: blue; text-decoration: underline}
a:active {  font-size: 10pt; color: blue; text-decoration: underline}
a:visited { font-size: 10pt; color: blue; text-decoration: underline }
</style>
</head>
<body bgcolor="#ffffff">

<p><a href="http://localhost:8088/page/showEmp.do?offset=0">Show Me All Of The Emps</a></p>

<logic:present name="emps">
  <%
  ArrayList emps = (ArrayList)request.getAttribute("emps");
  Iterator it = emps.iterator();
  empVO empvo;
  while(it!=null && it.hasNext()){
    empvo = (empVO)it.next();
    out.print(empvo.getEmpno() + "  ");
    out.print(empvo.getEname() + "<br>");
  }
    out.print("当前页有 " + emps.size() + " 条记录<br>");
    out.print("<p>");
  %>
</logic:present>

<logic:present name="pager">
  <%
  Pager pager = (Pager)request.getAttribute("pager");
  out.print(pager.getPageNavigation() + "<p>");
  out.print("共有记录 " + pager.getSize() + " 条<br>");
  out.print("每页有 " + pager.getLength() + " 条记录<br>");
  out.print("共分 " + pager.pageCount() + " 页<br>");
  %>
</logic:present>
</body>
</html:html>

********配置文件struts-config.xml********

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
<struts-config>
  <form-beans>
    <form-bean name="empForm" type="page.empForm" />
  </form-beans>
  <action-mappings>
    <action input="/index.jsp" name="empForm" path="/showEmp" scope="request" type="page.empAction" validate="false">
      <forward name="faiure" path="/index.jsp" />
      <forward name="success" path="/index.jsp" />
    </action>
  </action-mappings>
</struts-config>

 

 


在网上看了几个Structs分页,感觉不是很完善,于是根据自己的经验,写了一个相对高效简洁的分页方法。由于本人水平有限,如果大家有什么更好的想法,欢迎不吝赐教。
  
  一、 开发环境
  
  我的开发环境是:JBuilder x + Weblogic 8.1 + Oracle 9i + Windows 2003 ,如果朋友们的开发环境不一样亦无妨。
  
  二、开发思路
  
  既然讲的是Struts,那自然离不了MVC,分页显示也是如此。
  
  1、 建立数据库和对应的表,本例的表是TCertificate。
  
  2、 建立适当的模型组件,对应你要查询数据库中的表。这部分由DAO数据访问层来实现,如果有的朋友对DAO不熟悉可以查询一下相关资料。本例由CertificateDAO.java来实现。
  
  3 、建立分页所需要的模型组件,由javaBean来充当,并与CertificateDAO实现分离。网上介绍的很多方法,都存在着数据与分页组件藕合的现象,这也是本方法与其它分页方法的主要不同之处。
  
  4、建立控制器组件,这部分由Struts 中的Action来实现。主要负责将实例化CertificateDAO,只取要显示的数据记录,存入ArrayList对象然后返回,并放到request中。而分页部分则根据分页条件,单独进行构造,避免了与DAO混在一起的情况发生。网上其它介绍的一些分页方法中,基本上都是一次性读出所有查询的数据,然后再由分页相关组件进行构造。这样,如果数据量大的话,很容易形成瓶颈。在本例中由于不是一次性地读出查询的所有数据,而只是读出一个页面要显示的数据记录,这就节省了很多不必要的数据传输,提高了效率。本例中为CertificateAction.java。
  
  5、建立视图组件,这部分由jsp来充当,为了不出现java 代码,我们使用Struts提供的标签库,主要负责从request中取出刚刚放入的对象,通过反复调用CertificateAction以及action参数,而实现分页显示。本例中为listcertificate.jsp。
  
  6、 建立并配置struts-config.xml。
  
  三、实例代码
  
  确定好上面的开发思路后,代码的实现就有单可循了。
  
  1、建数据库和相应的表。
  
  2、数据逻辑层的相关代码。
  
  1)、通用的DAO类:CommonDAO.java
  
  这是一个很多DAO都要继承到的通用DAO类,是我根据实践总结出来的,为了减少篇幅,这里只显示和本例相关的代码。
  
  java代码:
  
  代码:
  --------------------------------------------------------------------------------
  package com.xindeco.business ;
  import java.io.*;
  import java.sql.*;
  import java.util.*;
  import javax.sql.*;
  import java.lang.IllegalAccessException;
  import java.lang.reflect.InvocationTargetException;
  import org.apache.commons.beanutils.BeanUtils;
  public class DAO
  {
  protected DataSource ds;
  /**
  * 说明:取得当前查询的总记录数
  */
  public int getRows ()
  {
  return this.count;
  }
  public void rsHandler (ResultSet rs, int offset, int limit)
  {
  try
  {
  count = 0;
  rs.absolute ( -1) ;
  count = rs.getRow () ;
  if (offset <= 0)
  {
  rs.beforeFirst () ;
  }
  else
  {
  rs.absolute (offset) ;
  }
  }
  catch (Exception e)
  {
  e.printStackTrace () ;
  }
  }
  public DAO(DataSource ds) {
  this.ds = ds;
  }
  
  public void setDataSource(DataSource ds) {
  this.ds = ds;
  }
  
  protected void close(ResultSet rs) {
  if (rs != null) {
  try {
  rs.close();
  } catch (SQLException e) {
  }
  rs = null;
  }
  }
  
  protected void close(PreparedStatement pstmt) {
  if (pstmt != null) {
  try {
  pstmt.close();
  } catch (SQLException e) {
  }
  pstmt = null;
  }
  }
  protected void close(Connection conn) {
  if (conn != null) {
  try {
  conn.close();
  } catch (SQLException e) {
  e.printStackTrace();
  }
  conn = null;
  }
  }
  
  protected void rollback(Connection conn) {
  if (conn != null) {
  try {
  conn.rollback();
  } catch (SQLException e) {
  e.printStackTrace();
  }
  conn = null;
  }
  }
  }
  
  这个类主要是通过子类传进来的先进结果集,取得查询的记录总数,并对数据库连接进行简单的管理。
  
  2)、对数据库进行访问:CertificateDAO.java
  
  java代码:
  
  代码:
  --------------------------------------------------------------------------------
  package com.xindeco.business;
  
  import java.io.*;
  import java.sql.*;
  import java.util.*;
  import javax.sql.*;
  
  import com.xindeco.common.dbconn.DbConn;
  
  public class CertificateDAO extends DAO
  {
  
  public NationDAO(DataSource ds) {
  super(ds);
  }
  
  public List findCertificateList(int offset,int limit) throws SQLException
  {
  int countRows = 0 ;
  ArrayList list = null ;
  Connection conn = null;
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  try
  {
  conn = ds.getConnection();
  String sql =
  "SELECT certificateID, certificateCode,certificateName,photoURL,"
  + "description,graduateID FROM TCertificate " ;
  pstmt = conn.prepareStatement(sql);
  rs = pstmt.executeQuery();
  /*对游标进行处理,rsHandler 方法在父类DAO中*/
  this.rsHandler(rs,offset,limit);
  if (rs != null && rs.next ())
  {
  list = new ArrayList () ;
  do
  {
  countRows++ ;
  list.add (rs2VO (rs)) ;
  }
  while ( (countRows++ < limit) && rs.next ()) ;
  }
  close(rs);
  close(pstmt);
  } catch (SQLException e) {
  close(rs);
  close(pstmt);
  rollback(conn);
  e.printStackTrace();
  }
  finally {
  close(conn);
  }
  return list ;
  }
  
  private CertificateVO rs2VO (ResultSet rs)
  {
  try
  {
  CertificateVO certificateVO = new CertificateVO () ;
  certificateVO.setCertificateID (rs.getInt ("certificateID")) ;
  certificateVO.setCertificateCode (rs.getString ("certificateCode")) ;
  certificateVO.setCertificateName (rs.getString ("certificateName")) ;
  certificateVO.setPhotoURL (rs.getString ("photoURL")) ;
  certificateVO.setDescription (rs.getString ("description")) ;
  certificateVO.setGraduateID (rs.getInt ("graduateID")) ;
  return certificateVO ;
  }
  catch (Exception ex)
  {
  ex.printStackTrace () ;
  return null ;
  }
  }
  }
  
  findCertificateList(int offset,int limit)是查得所有要显示的数据,并放入ArrayList中。看过网上有些例子,把数据记录放入ArrayList的动作过程直接在while循环体里完成,如果字段多的话,会造成方法过于宠大,又不美观。 这里,数据记录放入ArrayList的动作过程由rs2VO方法完成,就比较整洁了。另外,if (rs != null && rs.next ()) 配合while ( (countRows++ < limit) && rs.next ()) 是为了程序的健壮性考虑的,稍分析一下不难得出结论。
  
  3、建立控制器组件:CertificateAction.java
  
  java代码:
  
  代码:
  --------------------------------------------------------------------------------
  package com.xindeco.presentation;
  
  import javax.sql.* ;
  import java.util.* ;
  
  import javax.servlet.http.* ;
  import javax.servlet.* ;
  
  import org.apache.struts.action.* ;
  import org.apache.struts.util.* ;
  
  import com.xindeco.common.Pager;
  import com.xindeco.business.graduatedata.CertificateDAO ;
  
  public class CertificateAction
  extends Action
  {
  private static final int PAGE_LENGTH = 5 ; //每页显示5条记录
  public ActionForward execute (ActionMapping mapping, Actionform form,
  HttpServletRequest request,
  HttpServletResponse response)
  {
  ActionForward myforward = null ;
  String myaction = mapping.getParameter () ;
  
  if (isCancelled (request))
  {
  return mapping.findForward ("failure") ;
  }
  if ("".equalsIgnoreCase (myaction))
  {
  myforward = mapping.findForward ("failure") ;
  }
  else if    ("LIST".equalsIgnoreCase (myaction))
  {
  myforward = performList (mapping, form, request, response) ;
  }
  else
  {
  myforward = mapping.findForward ("failure") ;
  }
  return myforward ;
  }
  
  private ActionForward performList (ActionMapping mapping,
  Actionform actionform,
  HttpServletRequest request,
  HttpServletResponse response)
  {
  try
  {
  DataSource ds = (DataSource) servlet.getServletContext().getAttribute(Action.DATA_SOURCE_KEY);
  
  CertificateDAO  certificateDAO = new CertificateDAO (ds) ;
  
  int offset = 0;  //翻页时的起始记录所在游标
  int length = PAGE_LENGTH;
  String pageOffset = request.getParameter("pager.offset");
  if (pageOffset == null || pageOffset.equals("")) {
  offset = 0;
  } else {
  offset = Integer.parseInt(pageOffset);
  }
  List certificateList = certificateDAO .findCertificateList (offset,length) ;
  int size = certificateDAO.getRows(); // 取得总记录数
  String url = request.getContextPath()+"/"+mapping.getPath()+".do";
  String pagerHeader = Pager.generate(offset, size, length, url); //分页处理
  
  request.setAttribute ("pager", pagerHeader) ;
  request.setAttribute ("list", certificateList) ;
  }
  catch (Exception e)
  {
  e.printStackTrace();
  return mapping.findForward ("error") ;
  }
  return mapping.findForward ("success") ;
  }
  }
  
  CertificateAction.java主要是把数据从DAO中取出,并放入一个ArrayList 中,然后通过配置文件再软件View的JSP页。
  
  5、建立视图listcertificate.jsp文件。
  
  jsp代码:
  
  代码:
  --------------------------------------------------------------------------------
  
  <%@ page contentType="text/html; charset=GBK" %>
  <%@ taglib uri="/WEB-INF/struts-template.tld" prefix="template" %>
  <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
  <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
  <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
  
  <table bgcolor="#666666" cellpadding="1" cellspacing="0" border="0" width="500">
  <tr>
  <td>
  <table cellpadding="0" cellspacing="0" border="0" width="500">
  <tr>
  <td bgcolor="#fecc51">&</td>
  </tr>
  </table>
  </td>
  </tr>
  <tr>
  <td>
  <table cellpadding="0" cellspacing="0" border="0" width="500">
  <tr>
  <td bgcolor="#d6e0ed">
  &&<bean:message key="label.list4certificate"/>
  </td>
  </tr>
  <tr bgcolor="#FFFFFF">
  <td width="5%"></td><td width="19%"></td><td width="76%"></td>
  </tr>
  <tr>
  <td>
  <table bgcolor="#f2f2f2" width="500" cellspacing="0" border="0">
  <tr bgcolor="#bacce1">
  <td><b><bean:message key="Certificate.select"/> </b></td>
  <td><b><bean:message key="Certificate.certificateID"/> </b></td>
  <td><b><bean:message key="Certificate.certificateCode"/></b></td>
  <td><b><bean:message key="Certificate.certificateName"/></b></td>
  <td><b><bean:message key="Certificate.view"/></b></td>
  </tr>
  
  <bean:write name="pager" property="description"/>
  <logic:equal name="pager" property="hasPrevious" value="true">
  <a href="/graduatedata/list.do?viewPage=<bean:write name="pager" property="previousPage"/>" class="a02">
  Previous
  </a>
  </logic:equal>
  <logic:equal name="pager" property="hasNext" value="true">
  <a href="/graduatedata/list.do?viewPage=<bean:write name="pager" property="nextPage"/>" class="a02">
  Next
  </a>
  </logic:equal>
  
  <logic:notEmpty name="list" scope="request">
  <logic:iterate id="certificate" name="list" type="com.xindeco.business.graduatedata.CertificateVO"scope="request">
  <tr bgcolor="#FFFFFF">
  <td><html:text property="name" value="<bean:write name="certificate" property="certificateID" scope="page"/>"/>
  </td>
  <td> <bean:write name="certificate" property="certificateID" scope="page"/></td>
  <td> <bean:write name="certificate" property="certificateCode" scope="page"/></td>
  <td> <bean:write name="certificate" property="certificateName" scope="page"/></td>
  <td> <bean:write name="certificate" property="photoURL" scope="page"/></td>
  </tr>
  </logic:iterate>
  </logic:notEmpty>
  </table>
  </td>
  </tr>
  </table>
  </td>
  </tr>
  </table>
  
  6、对应的配置文件struts-config.xml。
  
  java代码:
  
  代码:
  --------------------------------------------------------------------------------
  <?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">
  <struts-config>
  <form-beans>
  <form-bean name="certificateform" type="com.xindeco.presentation.graduatedata.Certificateform" />
  </form-beans>
  <global-forwards>
  <forward name="error" path="/error/error.jsp" />
  </global-forwards>
  <action-mappings>
  <action name="certificateform" parameter="LIST" path="/graduatedata/list" scope="request" type="com.xindeco.presentation.graduatedata.CertificateAction" validate="true">
  <forward name="success" path="/graduatedata/listcertificate.jsp" />
  </action>
  </action-mappings>
  ……
  </struts-config>
  
  7、最后当然是最重要的分页代码了:Pager.java
  
  java代码:
  
  代码:
  --------------------------------------------------------------------------------
  package com.xindeco.common;
  
  import java.util.* ;
  public class Pager {
  private static int MAX_PAGE_INDEX = 10; //页脚显示多少页
  private static String HEADER = "Result page";
  
  public static String generate(int offset, int length, int size, String url) {
  if (length > size) {
  String pref;
  if (url.indexOf("?") > -1) {
  pref = "&";
  } else {
  pref = "?";
  }
  String header = "<font face='Helvetica' size='-1'>"+HEADER+": ";
  if (offset > 0) {
  header += "&<a href=\""+url+pref+"pager.offset="+(offset-size)+"\">[<< Prev]</a>\n";
  }
  int start;
  int radius = MAX_PAGE_INDEX/2*size;
  if (offset < radius) {
  start = 0;
  } else if(offset < length-radius) {
  start = offset - radius;
  } else {
  start = (length/size-MAX_PAGE_INDEX)*size;
  }
  for(int i=start;i<length && i < start + MAX_PAGE_INDEX*size;i+=size) {
  if (i == offset) {
  header += "<b>"+(i/size+1)+"</b>\n";
  } else {
  header += "&<a href=\""+url+pref+"pager.offset="+i+"\">"+(i/size+1)+"</a>\n";
  }
  }
  if(offset < length - size) {
  header += "&<a href=\""+url+pref+"pager.offset="+((int)offset+(int)size)+"\">[Next >>]</a>\n";
  }
  header += "</font>";
  return header;
  } else {
  return "";
  }
  }
  }
  
  这部分代码的实现相当简洁,但已经足够完成所需了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值