Jsp分页原代码,及用法

 

Jsp分页原代码,及用法

.定义一个分页的Tag Bean,以便用户在Jsp页中使用自定义标签,用户在使用时可以相应的描述

 

package BSC.tree;

 

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.tagext.TagSupport;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionServlet;

import java.sql.*;

import BSC.pool.*;

import java.util.*;

//import java.util.regex.Pattern;

import pubBean.Patten;

import BSC.tree.pagetag.*;

/**

 * @author 丁小龙(DingXiaolong)

 * @version 1.1

 * @deprecated 能够通过SQL语句产生一个GRID并且可通过相应的CSS设置相应的属性

 * @param strSQL 需要执行的查询SQL语句

 * @param pageSize Grid每一页所生的记录行数(Row)

 * @param action  当点分页素引号码所要跳转的页面名称,必须是使用本标志页面的名称

 * @param style 整个GridCSSCLASS的设置

 * @param ctrPageBeanSessionNM 内部使用

 * @param pageTileBeanSessionNM 未使用,暂保留

 * @param databeanNM 存储Grid所有数据集合,如果和ScriptTag对应的标志类合用时候,必须与其name使用相同值

 * @param loginIndexSessionNM 存储物理数据与逻辑数据的索引对应的集合名称,如果和ScriptTag对应的标志类合用时候,必须与其loginIndexSessionNM使用相同值

 * @param caption Grid表头标题,各列(Col)的标题用逗号(",")隔开,且数量必须和SQL语句所列出的字段一致

 * @param isHidden Grid各列是否显示(0--显示,1--为不显示),各列(Col)是否显示值用逗号(",")隔开,且数量必须和SQL语句所列出的字段一致

 * @param trStyle Grid各行的CSS设置值

 * @param tableWidth  Grid表的宽度,可以是绝对值的表达方式,也可以是相对值的表达方式

 * @param tdWidth Grid各列(col)之宽度,各列(Col)宽度用逗号(",")隔开,且数量必须和SQL语句所列出的字段一致

 * @param database Sturts-config中设置的datasource key

 */

 

public class PageScriptTag

    extends BodyTagSupport {

 

  private String strSQL;

  private String pageSize = "1";

  private String action;

  private String style;

  private String currentSize = "1";

  private String ctrPageBeanSessionNM;

  private String pageTileBeanSessionNM;

  private String displayCol;

  private String logicIndex;

  private String databeanNM;

  private String loginIndexSessionNM;

  private String caption;

  private String isHidden;

  protected static int scope = 2;

  private String trStyle;

  private String headTrStyle;

  private String headTdStyle;

  private String tdStyle;

  private String tableWidth;

  private String tdWidth;

  private String urlPara;

  private String oddTrStyle; //Grid 奇行cssclass设置

  private String evenTrStyle;

  private String database;//Grid 奇行cssclass设置

  public PageScriptTag() {

  }

 

  public String getAction() {

    return action;

  }

 

  public String getCtrPageBeanSessionNM() {

    return ctrPageBeanSessionNM;

  }

 

  public String getCurrentSize() {

    return currentSize;

  }

 

  public String getDisplayCol() {

    return displayCol;

  }

 

  public String getPageSize() {

    return pageSize;

  }

 

  public String getPageTileBeanSessionNM() {

    return pageTileBeanSessionNM;

  }

 

  public String getStrSQL() {

    return strSQL;

  }

 

  public String getStyle() {

    return style;

  }

 

  public void setStyle(String style) {

    this.style = style;

  }

 

  public void setStrSQL(String strSQL) {

    this.strSQL = strSQL;

  }

 

  public void setPageTileBeanSessionNM(String pageTileBeanSessionNM) {

    this.pageTileBeanSessionNM = pageTileBeanSessionNM;

  }

 

  public void setPageSize(String pageSize) {

    this.pageSize = pageSize;

  }

 

  public void setDisplayCol(String displayCol) {

    this.displayCol = displayCol;

  }

 

  public void setCurrentSize(String currentSize) {

    this.currentSize = currentSize;

  }

 

  public void setCtrPageBeanSessionNM(String ctrPageBeanSessionNM) {

    this.ctrPageBeanSessionNM = ctrPageBeanSessionNM;

  }

 

  public void setAction(String action) {

    this.action = action;

  }

 

  public int doEndTag() throws javax.servlet.jsp.JspException {

    /**@todo Override this javax.servlet.jsp.tagext.BodyTagSupport method*/

    System.out.println("In Class PageScriptTag's doEndTag");

    System.out.println("The scope is "+this.scope);

    Connection conn=null;

  //本类可以参考本人发表的 定义自己的Connection Pool”

    PoolBean datasource=null;

 

    try {

              //初始化数据库连接

             //得到数据库开始,用户可以使用自己的连接池类 datasource=(PoolBean)pageContext.getAttribute(this.getDatabase(),3);

              if(datasource==null){

                 DB_Operate db_oper=new DB_Operate();

                 datasource=db_oper.getDataSource(this.getDatabase());

              }

              conn=datasource.getConnection();

       //得到数据库结束

              Patten strP=new Patten();

 

              if (getStrSQL() != null) {

                strP.compile("<");

                String[] strsqlarr = strP.split(getStrSQL());

                String tmpstr="";

                String strLink="";

                for(int strI=0;strI<strsqlarr.length;strI++)

                {

                   tmpstr+=strLink+strsqlarr[strI];

                   strLink="<";

                }

                this.setStrSQL(tmpstr);

             }

 

 

      System.out.println(this.getStrSQL());

 

 

      PageDataBean databean = (PageDataBean)this.pageContext.getAttribute(

          getDatabeanNM(), scope);

      if (databean == null) {

        databean = new PageDataBean(this.getStrSQL(), conn);

      }

      else {

        if (databean.getIsFlg().equals("0")) {

            databean.setStrSQL(this.getStrSQL());

            databean.init(conn);

            System.out.println("Initialing the PageDataBean.........");

            databean.setIsFlg("1");

         }

      }

 

      int colCount = (new Integer(databean.getColCount())).intValue();

      JspWriter out = this.pageContext.getOut();

      String tmpDis = this.getDisplayCol();

      //Patten类参考我发表的 java正则表达式

      Patten p = new Patten();

      p.compile(",");

 

 

      String ctrPageBeanNM;

      if (this.getCtrPageBeanSessionNM() == null) {

        ctrPageBeanNM = "CTRPAGE";

 

      }

      else {

        ctrPageBeanNM = getCtrPageBeanSessionNM();

 

      }

      CtrPageBean ctrpge = (CtrPageBean) pageContext.getAttribute(ctrPageBeanNM,

          scope);

 

      Vector datas = databean.getDataList();

      Hashtable dataarry = databean.getDataArray();

 

      if (ctrpge == null) {

 

        ctrpge = new CtrPageBean(datas.size() + "", getPageSize());

 

      }

 

      String tmpLoginIndexSessionNM = "";

      if (this.getLoginIndexSessionNM() == null) {

        tmpLoginIndexSessionNM = "tmpLoginIndexSessionNM";

      }

      else {

        tmpLoginIndexSessionNM = this.getLoginIndexSessionNM();

 

        //返回的资料库本栏位开始的位置

      }

      int colcapstar = databean.getColnameindex().size() - colCount;

      //初始化是否要隐藏

      String tmpIsHidden = this.getIsHidden();

      String[] tmpIsHiddenArray = p.split(tmpIsHidden);

      for (int hidindex = colcapstar;

           hidindex < tmpIsHiddenArray.length + colcapstar; hidindex++) {

        databean.getIsHiddenArray().put( (String) databean.getColnameindex().

                                        elementAt(hidindex),

                                        tmpIsHiddenArray[hidindex - colcapstar]);

      }

 

      //初始化Grid的标题

      String tmpCaption = this.getCaption();

      String[] tmpCaptionArr = p.split(tmpCaption);

 

      for (int capindex = colcapstar;

           capindex < tmpCaptionArr.length + colcapstar; capindex++) {

        databean.getCaptionArray().put( (String) databean.getColnameindex().

                                       elementAt(capindex),

                                       tmpCaptionArr[capindex - colcapstar]);

      }

      //初奴化Gridcol的宽度

      String tdwidflg="0";

 

      String tmpWidth=this.getTdWidth();

      if(tmpWidth!=null){

        String[] tmpWidthArr = p.split(tmpWidth);

        for (int widindex = colcapstar;

             widindex < tmpWidthArr.length + colcapstar; widindex++) {

          databean.getWidthArray().put( (String) databean.getColnameindex().

                                       elementAt(widindex),

                                       tmpWidthArr[widindex - colcapstar]);

        }

        tdwidflg="1";

      }

 

 

      String[] tmpLogicIndexs = null;

      Vector logicIndexs = (Vector) pageContext.getAttribute(

          tmpLoginIndexSessionNM, scope);

      if (logicIndexs == null) {

        logicIndexs = new Vector();

      }

      if (this.getLogicIndex() != null) {

        tmpLogicIndexs = p.split(this.getLogicIndex());

        if (tmpLogicIndexs.length != colCount) {

          int oldsize = logicIndexs.size();

          logicIndexs.removeAllElements();

          for (int i = 1; i <= colCount + oldsize; i++) {

            int tmp = i - 1;

            logicIndexs.addElement("" + tmp);

          }

 

        }

        else {

          for (int i = 1; i <= colCount; i++) {

            logicIndexs.addElement("" + tmpLogicIndexs[i - 1]);

          }

 

        }

      }

      else {

        int oldsize = logicIndexs.size();

        logicIndexs.removeAllElements();

        for (int i = 1; i <= colCount + oldsize; i++) {

          int tmp = i - 1;

          logicIndexs.addElement("" + tmp);

        }

 

      }

 

      Hashtable ScriptObj = new Hashtable();

      Hashtable CaptionObj = new Hashtable();

      Hashtable isHiddenObj = new Hashtable();

      Hashtable  widthObj= new Hashtable();

      Hashtable TDObj = new Hashtable();

      for (int i = 0; i < logicIndexs.size(); i++) {

        // int lgcIndex=new Integer((String)logicIndexs.elementAt(i)).intValue();

 

        String colkey =(String) databean.getColnameindex().elementAt(i);

        String lgcIndex = (String) logicIndexs.elementAt(i);

        CaptionObj.put(lgcIndex, databean.getCaptionArray().get(colkey));

        isHiddenObj.put(lgcIndex, databean.getIsHiddenArray().get(colkey));

        widthObj.put(lgcIndex,databean.getWidthArray().get(colkey));

 

        if (colkey.indexOf("Script,,,") == -1) {

 

          if (databean.getDataArray().get(colkey) != null) {

            ScriptObj.put(lgcIndex, databean.getDataArray().get(colkey));

            TDObj.put(lgcIndex, colkey);

          }

        }

        else {

          String strScript = (String) databean.getDataArray().get(colkey);

          Vector vecScript = new Vector();

 

          for (int k = 0; k < databean.getDataList().size(); k++) {

            vecScript.addElement(strScript);

          }

          ScriptObj.put(lgcIndex, vecScript);

          TDObj.put(lgcIndex, "Script___");

        }

      }

 

      ctrpge.setCurrent(getCurrentSize());

      int start = (ctrpge.getInteger(ctrpge.getCurrent()) - 1) *

          ctrpge.getInteger(ctrpge.getPageSize());

      int offset = (ctrpge.getInteger(ctrpge.getCurrent())) *

          ctrpge.getInteger(ctrpge.getPageSize());

 

      out.print("<table  border=/"0/" cellspacing=/"1/" ");

 

     if(this.getTableWidth()!=null){

        out.print(" width=/""+this.getTableWidth()+"/" ");

      }

      if (this.getStyle() != "") {

        out.print(" class=/"");

        out.print(style);

        out.print("/"");

      }

      out.println(">");

      out.print("<tr  ");

      if(this.getHeadTrStyle()!=null)

               out.println(" class=/""+this.getHeadTrStyle()+"/" >");

      for (int capindex = 0; capindex < CaptionObj.size(); capindex++) {

        out.print(" <td  align='center' ");

        if ( ( (String) isHiddenObj.get("" + capindex)).equals("1")) {

          out.print(" style=/"display:none/" ");

        }

        if(tdwidflg.equals("1")){

           out.print(" width=/""+(String)widthObj.get(""+capindex)+"/"");

        }

        if(this.getHeadTdStyle()!=null)

               out.print(" class=/""+this.getHeadTdStyle()+"/" >");

 

        out.println(">");

        out.println( (String) CaptionObj.get("" + capindex));

        out.println(" </td>");

      }

      out.println("</tr>");

      int Rec_count = 0;

      for (int i = start, k = 0; i < offset && i < datas.size(); k++, i++) {

        String tdstyle = "td";

 

        out.println("<tr id='TmpGridID_" + k + "' style='cursor: hand'");

 

        out.print(" onMouseOver=/"f_onclick(this," + k + "," + ScriptObj.size() +

                  ")/" ");

        if(k%2==0&&this.getEvenTrStyle()!=null){

          out.print(" class=/"");

          out.print(this.getEvenTrStyle()+"/"");

        }

        if(k%2!=0&&this.getOddTrStyle()!=null){

          out.print(" class=/"");

          out.print(this.getOddTrStyle()+"/"");

        }

        if(this.getTrStyle()!=null&&this.getEvenTrStyle()==null&&k%2==0){

          out.print(" class=/"");

          out.print(this.getTrStyle()+"/"");

        }

        if(this.getTrStyle()!=null&&this.getOddTrStyle()==null&&k%2!=0){

          out.print(" class=/"");

          out.print(this.getTrStyle()+"/"");

        }

 

 

 

        out.print(" >");

        for (int j = 0; j < ScriptObj.size(); j++) {

          Vector tdvalues = (Vector) ScriptObj.get("" + j);

          String td_id = (String) TDObj.get("" + j);

 

          out.print(" <td  align='left'");

 

          out.print(" id='TD_" + td_id + "_" + i + "_" + j + "'");

 

          if ( ( (String) isHiddenObj.get("" + j)).equals("1")) {

            out.print(" style=/"display:none/" ");

          }

          if(this.getTdStyle()!=null){

            out.print(" class=/"");

            out.print(this.getTdStyle()+"/"");

          }

 

          out.println(">");

          String tdval = (String) tdvalues.elementAt(i);

          if (!td_id.equals("Script___")) {

            out.println("<input type='hidden' id='TDVal_" + td_id + "_" + k +

                        "' value='" + tdval + "'>");

 

          }

          out.println(tdval);

          out.println(" </td>");

        }

        out.println("</tr>");

        Rec_count++;

      }

      out.println("<input type='hidden' name='TmpGrid_RecordCount' value='" +

                  Rec_count + "' >");

 

      out.println("</table>");

      //输出分页检索的页码

      String hyperlink = null;

      if (ctrpge.getInteger(ctrpge.getMax()) > 1 && this.getAction() != null) {

 

        hyperlink = ( (HttpServletResponse) pageContext.getResponse()).

            encodeURL(this.getAction());

 

        if (hyperlink != null) {

          out.println("<br>");

          out.println

              (

              "<table  width='100%' border=/"0/" cellspacing=/"0/" cellpadding=/"0/"");

          /* if (style != "") {

                    out.println(" class=/"");

                    out.println(style);

                    out.println("/"");

                }*/

          out.print(">");

 

          out.println("<tr>");

 

          out.println(" <td align='center' width='10%'>");

          out.print("" + ctrpge.getMax() + "");

          out.print("当前为第" + ctrpge.getCurrent() + " ");

          out.println("页数检索:&nbsp;");

 

          out.print("<a href=/"");

          String propmt = "";

          if (this.getAction().indexOf('?') == -1) {

            propmt = "?";

          }

          out.print(hyperlink);

          out.print(propmt + "index=" + 1);

          out.print("/"");

          out.print(">");

          out.print("[第一页]");

          out.print("</a>");

          out.println("&nbsp;");

 

          out.print("<a href=/"");

          out.print(hyperlink);

          out.print(propmt + "index=" + ctrpge.getLast());

          if(this.getUrlPara()!=null){

             out.print("&"+this.getUrlPara());

           }

 

          out.print("/"");

          out.print(">");

          out.print("上一页");

          out.print("</a>");

          out.println("&nbsp;");

 

          int indexmax = ctrpge.getInteger(ctrpge.getMax());

          int indexcur = ctrpge.getInteger(ctrpge.getCurrent());

          int indexstart = indexcur - indexcur % 10 + 1;

          int indexoffect = indexcur - indexcur % 10 + 10;

          for (int mindex = indexstart;

               mindex <= indexoffect && mindex <= indexmax; mindex++) {

 

            out.print("<a href=/"");

            out.print(hyperlink);

            out.print(propmt + "index=" + mindex);

            if(this.getUrlPara()!=null){

              out.print("&"+this.getUrlPara());

            }

            out.print("/"");

            out.print(">");

            out.print(mindex);

            out.print("</a>");

 

            out.println("&nbsp;");

 

          }

 

          out.print("<a href=/"");

          out.print(hyperlink);

          out.print(propmt + "index=" + ctrpge.getNext());

          if(this.getUrlPara()!=null){

              out.print("&"+this.getUrlPara());

            }

 

          out.print("/"");

          out.print(">");

          out.print("下一页");

          out.print("</a>");

          out.println("&nbsp;");

 

          out.print("<a href=/"");

          out.print(hyperlink);

          out.print(propmt + "index=" + ctrpge.getMax());

          if(this.getUrlPara()!=null){

              out.print("&"+this.getUrlPara());

            }

 

          out.print("/"");

          out.print(">");

          out.print("[最末页]");

          out.print("</a>");

          out.println("&nbsp;");

 

          out.println("  </td>");

          out.println(" </tr>");

          out.println("</table>");

        }

 

      }

      pageContext.setAttribute(ctrPageBeanNM, ctrpge, scope);

      pageContext.setAttribute(tmpLoginIndexSessionNM, logicIndexs, scope);

 

    }

    catch (Exception e) {

      System.out.println("PageScriptTag Error:" + e.getMessage());

    }

    finally{

      try{

        if(conn!=null)

          conn.close();

      }catch(SQLException sqle){

        sqle.printStackTrace();

      }

    }

    return super.doEndTag();

  }

 

  public String getLogicIndex() {

    return logicIndex;

  }

 

  public void setLogicIndex(String logicIndex) {

    this.logicIndex = logicIndex;

  }

 

  public String getDatabeanNM() {

    return databeanNM;

  }

 

  public void setDatabeanNM(String databeanNM) {

    this.databeanNM = databeanNM;

  }

 

  public String getLoginIndexSessionNM() {

    return loginIndexSessionNM;

  }

 

  public void setLoginIndexSessionNM(String loginIndexSessionNM) {

    this.loginIndexSessionNM = loginIndexSessionNM;

  }

 

  public String getCaption() {

    return caption;

  }

 

  public void setCaption(String caption) {

    this.caption = caption;

  }

 

  public String getIsHidden() {

    return isHidden;

  }

 

  public void setIsHidden(String isHidden) {

    this.isHidden = isHidden;

  }

  public String getTrStyle() {

    return trStyle;

  }

  public void setTrStyle(String trStyle) {

    this.trStyle = trStyle;

  }

  public String getHeadTrStyle() {

    return headTrStyle;

  }

  public void setHeadTrStyle(String headTrStyle) {

    this.headTrStyle = headTrStyle;

  }

  public String getHeadTdStyle() {

    return headTdStyle;

  }

  public void setHeadTdStyle(String headTdStyle) {

    this.headTdStyle = headTdStyle;

  }

  public String getTdStyle() {

    return tdStyle;

  }

  public void setTdStyle(String tdStyle) {

    this.tdStyle = tdStyle;

  }

  public String getTableWidth() {

    return tableWidth;

  }

  public void setTableWidth(String tableWidth) {

    this.tableWidth = tableWidth;

  }

  public String getTdWidth() {

    return tdWidth;

  }

  public void setTdWidth(String tdWidth) {

    this.tdWidth = tdWidth;

  }

  public String getUrlPara() {

    return urlPara;

  }

  public void setUrlPara(String urlPara) {

    this.urlPara = urlPara;

  }

  public String getOddTrStyle() {

    return oddTrStyle;

  }

  public void setOddTrStyle(String oddTrStyle) {

    this.oddTrStyle = oddTrStyle;

  }

  public String getEvenTrStyle() {

    return evenTrStyle;

  }

  public void setEvenTrStyle(String evenTrStyle) {

    this.evenTrStyle = evenTrStyle;

  }

  public String getDatabase() {

    return database;

  }

  public void setDatabase(String database) {

    this.database = database;

  }

 

}

 

2.定义次Tag Bean,它是一个用呈现特殊html组件,如text,button

package BSC.tree;

 

import javax.servlet.jsp.*;

import javax.servlet.jsp.tagext.*;

import javax.servlet.jsp.tagext.TagSupport;

import javax.servlet.http.HttpServletResponse;

import java.sql.*;

 

import java.util.*;

import pubBean.*;

import BSC.tree.pagetag.*;

 

public class ScriptTag

    extends BodyTagSupport {

  private String name;

  private String property;

  private String value;

  private String index;

  private String loginIndexSessionNM;

  private String caption;

  private String isHidden;

  protected static int scope = 2;

  private String width;

  public ScriptTag() {

  }

 

  public String getName() {

    return name;

  }

 

  public void setName(String name) {

    this.name = name;

  }

 

  public String getProperty() {

    return property;

  }

 

  public void setProperty(String property) {

    this.property = property;

  }

 

  public String getValue() {

    return value;

  }

 

  public void setValue(String value) {

    this.value = value;

  }

 

  public int doEndTag() throws javax.servlet.jsp.JspException {

    /**@todo Override this javax.servlet.jsp.tagext.BodyTagSupport method*/

    System.out.println("In Class ScriptTag 's doEndTag()");

    try {

 

      System.out.println("The scope is "+this.scope);

      PageDataBean databean = (PageDataBean)this.pageContext.getAttribute(this.

          getName(), scope);

      Vector logicIndexs = (Vector)this.pageContext.getAttribute(this.

          getLoginIndexSessionNM(), scope);

      if (databean == null) {

        System.out.println("Create the DataBean...");

        databean = new PageDataBean();

 

      }

      if (logicIndexs == null) {

        logicIndexs = new Vector();

      }

 

      logicIndexs.addElement(this.getIndex());

      databean.getColnameindex().addElement("Script,,," + this.getProperty());

      databean.getDataArray().put("Script,,," + this.getProperty(),

                                  this.getValue());

      databean.getCaptionArray().put("Script,,," + this.getProperty(),

                                     this.getCaption());

      databean.getIsHiddenArray().put("Script,,," + this.getProperty(),

                                      this.getIsHidden());

      databean.getWidthArray().put("Script,,,"+this.getProperty(),

                                   this.getWidth());

 

      pageContext.setAttribute(this.getName(), databean, scope);

      pageContext.setAttribute(this.getLoginIndexSessionNM(), logicIndexs,

                               scope);

 

    }

    catch (Exception e) {

      System.out.println("ScriptTag Error:" + e.getMessage());

    }

    return super.doEndTag();

  }

 

  public String getIndex() {

    return index;

  }

 

  public void setIndex(String index) {

    this.index = index;

  }

 

  public String getLoginIndexSessionNM() {

    return loginIndexSessionNM;

  }

 

  public void setLoginIndexSessionNM(String loginIndexSessionNM) {

    this.loginIndexSessionNM = loginIndexSessionNM;

  }

 

  public String getCaption() {

    return caption;

  }

 

  public void setCaption(String caption) {

    this.caption = caption;

  }

 

  public String getIsHidden() {

    return isHidden;

  }

 

  public void setIsHidden(String isHidden) {

    this.isHidden = isHidden;

  }

  public String getWidth() {

    return width;

  }

  public void setWidth(String width) {

    this.width = width;

  }

 

}

3.定义一个用于执行sql查询语句,并将相应的数保存到该Bean里面

package BSC.tree.pagetag;

import java.sql.*;

import java.util.*;

public class PageDataBean {

 

  private Vector dataList=new Vector();

  private String strSQL="";

  private String colCount="0";

  private java.util.Hashtable dataArray=new Hashtable();

  private java.util.Vector colnameindex=new Vector();

  private java.util.Hashtable captionArray=new Hashtable();

  private java.util.Hashtable isHiddenArray=new Hashtable();

  private String isFlg="0";

  private java.util.Hashtable widthArray=new Hashtable();

  public PageDataBean(String strSQL,Connection conn) {

    this.setStrSQL(strSQL);

 

    init(conn);

  }

  public PageDataBean(){

 

  }

  public Vector getDataList() {

    return dataList;

  }

   protected void setDataList(java.util.Vector dataList) {

    this.dataList = dataList;

  }

  public String getStrSQL() {

    return strSQL;

  }

  public void setStrSQL(String strSQL) {

    this.strSQL = strSQL;

  }

  public void init(Connection conn){

    try{

     // Statement stat=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);

      Statement stat=conn.createStatement();

      ResultSet rs=stat.executeQuery(this.getStrSQL());

      ResultSet tmrs=null;

      if(rs!=null){

         int colcount=rs.getMetaData().getColumnCount();

         this.setColCount(""+colcount);

 

         int reccount=0;

         while(rs.next()){

            reccount++;

            Vector rowDate=new Vector();

           for(int i=1;i<=colcount;i++){

              rowDate.addElement(notNull(rs.getString(i)));

           }

           this.getDataList().addElement(rowDate);

         }

         for(int i=1;i<=colcount;i++){

            this.getColnameindex().addElement(rs.getMetaData().getColumnName(i));

         }

         if(reccount!=0){

           for (int i = 1; i <= colcount; i++) {

 

             //rs.first();

             tmrs=stat.executeQuery(this.getStrSQL());

             Vector cols = new Vector();

             while (tmrs.next()) {

               cols.addElement(notNull(tmrs.getString(i)));

 

 

             }

             this.addNode(tmrs.getMetaData().getColumnName(i), cols);

             tmrs.close();

           }

         }

 

 

      }

 

    }catch(Exception e){

       System.out.print("PageDataBean Error: "+e.getMessage());

    }

  }

  public String getColCount() {

    return colCount;

  }

  protected void setColCount(String colCount) {

    this.colCount = colCount;

  }

  public java.util.Hashtable getDataArray() {

    return dataArray;

  }

  public void setDataArray(java.util.Hashtable dataArray) {

    this.dataArray = dataArray;

  }

  void addNode(String name,Object obj) throws IllegalArgumentException {

 

        synchronized (dataArray) {

 

            if (dataArray.containsKey(name))

                throw new IllegalArgumentException("Column name '" + name +

                                                   "' is not unique");

 

            dataArray.put(name, obj);

        }

 

    }

    void addCaptionNode(String name,String obj) throws IllegalArgumentException {

 

        synchronized (captionArray) {

 

            if (dataArray.containsKey(name))

                throw new IllegalArgumentException("Column name '" + name +

                                                   "' is not unique");

 

            captionArray.put(name, obj);

        }

 

    }

 

  public java.util.Vector getColnameindex() {

    return colnameindex;

  }

  public void setColnameindex(java.util.Vector colnameindex) {

    this.colnameindex = colnameindex;

  }

  public java.util.Hashtable getCaptionArray() {

    return captionArray;

  }

  public void setCaptionArray(java.util.Hashtable captionArray) {

    this.captionArray = captionArray;

  }

  public java.util.Hashtable getIsHiddenArray() {

    return isHiddenArray;

  }

  public void setIsHiddenArray(java.util.Hashtable isHiddenArray) {

    this.isHiddenArray = isHiddenArray;

  }

  public String getIsFlg() {

    return isFlg;

  }

  public void setIsFlg(String isFlg) {

    this.isFlg = isFlg;

  }

  public java.util.Hashtable getWidthArray() {

    return widthArray;

  }

  public void setWidthArray(java.util.Hashtable widthArray) {

    this.widthArray = widthArray;

  }

 

  /**

   * notNull

   *

   * @param aStr String

   */

  public String notNull(String aStr) {

    if(aStr!=null)

      return aStr.trim();

    else

      return "";

  }

 

}

4.定义一个主控类,用于保存分页Grid的页面信息

package BSC.tree.pagetag;

 

public class CtrPageBean {

 

  private String next="1";

  private String last="1";

  private String current="1";

  private String size="0";

  private String max="1";

  private String pageSize="0";

  public CtrPageBean(String size,String pageSize) {

 

    if(this.getInteger(size)!=0){

      if(this.getInteger(pageSize)<0)

        this.setPageSize(size);

      this.setSize(size);

      this.setPageSize(pageSize);

      if (this.getInteger(pageSize) > this.getInteger(size)) {

        this.setPageSize(size);

      }

      if (pageSize == "0")

        this.setPageSize("1");

      int leval = this.getInteger(getSize()) % this.getInteger(this.getPageSize());

      int maxv = 0;

      if (leval == 0) {

        maxv = this.getInteger(getSize()) / this.getInteger(this.getPageSize());

      }

      else {

        maxv = this.getInteger(getSize()) / this.getInteger(this.getPageSize()) +

            1;

      }

 

      this.setMax("" + maxv);

    }

 

  }

  public String getMax() {

    return max;

  }

  protected void setMax(String max) {

    this.max = max;

  }

  public String getNext() {

    return next;

  }

  public void setNext(String next) {

    this.next = next;

  }

  public String getLast() {

    return last;

  }

  public void setLast(String last) {

    this.last = last;

  }

  public String getCurrent() {

    return current;

  }

  public void setCurrent(String current) {

    this.current = current;

    if(this.getInteger(this.getCurrent())==this.getInteger(this.getMax())){

       this.setNext("1");

    }

    else{

       int cur=getInteger(this.current) + 1;

        this.setNext(""+cur);

    }

    if(this.getInteger(this.getCurrent())!=1){

      int lastv = getInteger(this.current) - 1;

      this.setLast(""+lastv);

    }

    else

      this.setLast("1");

 

 

  }

  public String getSize() {

    return size;

  }

  protected void setSize(String size) {

    this.size = size;

  }

  protected void init(String size){

 

  }

  public String getPageSize() {

    return pageSize;

  }

  public void setPageSize(String pageSize) {

    this.pageSize = pageSize;

  }

  public int getInteger(String val){

    Integer vals=new Integer(val);

    return vals.intValue();

  }

}

5.定义一个名叫page_table.tldtld文件,并将其存放到/WEB-INF目录下内容

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

  <tlibversion>1.0</tlibversion>

  <jspversion>1.1</jspversion>

  <shortname>PAGETABLE</shortname>

  <uri>helloworld</uri>

  <info>OUT TABLE</info>

   <tag>

    <name>ScriptTag</name>

    <tagclass>BSC.tree.ScriptTag</tagclass>

    <bodycontent>empty</bodycontent>

    <attribute>

      <name>name</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>property</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>value</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>index</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>loginIndexSessionNM</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>caption</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>isHidden</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>width</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

     <!--attribute>

      <name>isFlush</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute-->

   </tag>

   <tag>

    <name>PageScriptTag</name>

    <tagclass>BSC.tree.PageScriptTag</tagclass>

    <bodycontent>empty</bodycontent>

    <attribute>

      <name>strSQL</name>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>pageSize</name>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>action</name>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>style</name>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>currentSize</name>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>ctrPageBeanSessionNM</name>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>pageTileBeanSessionNM</name>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>displayCol</name>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

     <attribute>

      <name>loginIndexSessionNM</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>logicIndex</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>databeanNM</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>caption</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>isHidden</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

   

    <attribute>

      <name>trStyle</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>tdStyle</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>headTrStyle</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>headTdStyle</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>tableWidth</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>tdWidth</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>urlPara</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>oddTrStyle</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>evenTrStyle</name>

      <required>false</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

    <attribute>

      <name>database</name>

      <required>true</required>

      <rtexprvalue>true</rtexprvalue>

    </attribute>

   </tag>

  

 

</taglib>

6.在jsp中使用,

<%@ page contentType="text/html; charset=Big5" %>

<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>

<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

<%@ taglib uri="/WEB-INF/page_table.tld" prefix="pagetab"%>

<%@ page import="BSC.pool.*" %>

<html>

<head>

<title>

login

</title>

<link href="css/wfr_css.css" rel="stylesheet" type="text/css"></head>

<script language="JavaScript" src="js/PubFun.js" type="text/javascript"> </script>

</head>

<body bgcolor="#ffffff">

  <logic:present name="userManageForm">

    <bean:write name="userManageForm" property="email"/>

  </logic:present>

  <logic:notPresent name="userManageForm">

    addddddddddd

  </logic:notPresent>

<!--bean:write name="userManageForm" property="email"/-->

 

<%

//以下就是产生分页Grid的代码

        String index="1";

        index=request.getParameter("index");

        if(index==null)

        index="1";

 

%>

 

<pagetab:PageScriptTag

                 logicIndex="0,1"

                 pageSize="10"

                 isHidden="0,0"

                 action="TestGrid.jsp"

                 style="outtable"

                 currentSize="<%=index%>"

                 strSQL="select ttid,Type from Trans_Type"

                 databeanNM="databeanname"

                 loginIndexSessionNM="loginIndexSessionNM"

                 caption="县市ID,县市名称"

                 headTrStyle="text1"

                 tdWidth="5%,20%"

                 database="resources.SQLServerDB"

                 />

</body>

</html>

自己收集的jsp分页代码。对于北大青鸟Y2的学员可能有用吧。自己也在做这个项目。这里有增、删、该、查加分页。有上一页、下一页、首页、尾页、第几页、还有带数字和点的分页。可以说是非常好的分页代码。想要的朋友自己处下载 <%@ page contentType="text/html; charset=GB2312" language="java" import="java.sql.*" errorPage="" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <% java.sql.Connection sqlCon; //数据库连接对象 java.sql.Statement sqlStmt; //SQL语句对象 ResultSet sqlRst=null; //java.sql.ResultSet sqlRst; //结果集对象 java.lang.String strCon; //数据库连接字符串 java.lang.String strSQL; //SQL语句 int intPageSize; //一页显示的记录数 int intRowCount; //记录总数 int intPageCount; //总页数 int intPage; //待显示页码 java.lang.String strPage; int i; //设置一页显示的记录数 intPageSize = 2; //取得待显示页码 strPage = request.getParameter("page"); if(strPage==null){ //表明在QueryString中没有page这一个参数,此时显示第一页数据 intPage = 1; } else{ //将字符串转换成整型 intPage = java.lang.Integer.parseInt(strPage); if(intPage<1) intPage = 1; } %><% String DBUser="sa"; String DBPassword="88029712"; //String DBServer="127.0.0.1"zjprice; String DBUrl="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs"; //创建语句对象 //Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); sqlCon=java.sql.DriverManager.getConnection(DBUrl,DBUser,DBPassword); sqlStmt=sqlCon.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY); //执行SQL语句并获取结果集 String sql=null; String search=""; String ToPage=request.getParameter("ToPage"); if(request.getParameter("search")!=null &&!request.getParameter("search").equals("")) {search=new String(request.getParameter("search").trim().getBytes("8859_1")); } sql="select top 50 au_id,au_lname from authors "; /*sql="select*from ta,tb where id like'%"+search+"%'"; sql=sql+"or title like'%"+search+"%'"; sql=sql+"or time like'%"+search+"%'"; sql=sql+"or con like'%"+search+"%'"; sql=sql+"order by id";*/ sqlRst=sqlStmt.executeQuery(sql); //获取记录总数 sqlRst.last(); intRowCount = sqlRst.getRow(); //记算总页数 intPageCount = (intRowCount+intPageSize-1) / intPageSize; //调整待显示的页码 if(intPage>intPageCount) intPage = intPageCount; %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>test</title> </head> <body> <table border="1" cellspacing="0" cellpadding="0"> <tr> <th>标题id</th> <th>内容表</th> </tr> <% if(intPageCount>0) { //将记录指针定位到待显示页的第一条记录上 sqlRst.absolute((intPage-1) * intPageSize + 1); //显示数据 i = 0; while(i<intPageSize && !sqlRst.isAfterLast()){ %> <tr> <td> <%=sqlRst.getString(1)%> </td> <td> <%=sqlRst.getString(2)%> </td> </tr> <% sqlRst.next(); i++; } } %> <tr><td colspan="8">共有<font color=red><%= intRowCount %></font>条记录 当前<font color=red><%=intPage%>/<%=intPageCount%></font>页  <% if(intPageCount > 1){ %> <% if(intPage !=0){%> <a href="mysqlpage.jsp">首页</a> <%}if(intPage != 1){%><a href="mysqlpage.jsp?page=<%= intPage - 1 %>">上一页</a> <%}if(intPage<intPageCount){%><a href="mysqlpage.jsp?page=<%=intPage+1%>">下一页</a><%}%> <a href="mysqlpage.jsp?page=<%= intPageCount %>">尾页</a> <% } %>跳转到 <select name="page" onChange="javascript:this.form.submit();"> <% for(i=1;i<=intPageCount;i++){%> <option value="<%= i %>" <% if(intPage == i){%>selected<% } %>><%= i %></option> <% } %> </select>页 <%int m,n,p; %> <%if (intPage>1){ if(intPage-2>0){ m=intPage-2;} else { m=1;} if(intPage+2<intPageCount){ n=intPage+2;} else{ n=intPageCount; }%> 转到页码: [ <% for(p=m;p<=n;p++) { if (intPage==p){ %> <font color="black"><%=p %></font> <% } else{%> <a href=?page=<%=p %>><font color=red>[<%=p %>]</font></a> <% } }%>]<%} %> </td></tr> </table> </body> </html> <% //关闭结果集 sqlRst.close(); //关闭SQL语句对象 sqlStmt.close(); //关闭数据库 sqlCon.close(); %>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值