靈魂-放水

          為學日益,為道日損。

          BlogJava 首頁 新隨筆 聯系 聚合 管理
            296 Posts :: 10 Stories :: 274 Comments :: 0 Trackbacks

          漫談解決Struts分頁顯示??

          方案<一>

          ?? ChinaITLab 收集整理???? 2004-9-24??
          學習Struts已經有2個多月了,前幾天群里的朋友問我Struts分頁顯示的問題,覺得好像與在jsp中的差不多,但還是遇到了這樣那樣的問題,好不容易花了幾天時間把問題都搞清楚,覺得還是寫點東西跟大家分享一下的好!
          至于Struts的語法這里就不多介紹了,不懂的朋友可以先看網上的其他文章。
          一 開發環境
          Elicpse+Struts Studio+SqlServer2000+Tomcat。
          二 開發思路
          既然講的是Struts,那自然離不了MVC,分頁顯示也是如此。
          1 建立適當的模型組件,對應你要查詢數據庫中的表。這部分由我們熟悉的javaBean來充當。并在其中建立數據庫查詢方法,該方法需要一個java.sql.Conntection類型的參數,并返回一個ArrayList。在本例中為 Book.java
          2 建立分頁所需要的模型組件,也是由javaBean來充當,通過由Book中提供的ArrayList來構造。本例中為 PageBean.java.。
          3建立控制器組件,這部分由Struts 中的Action來實現。主要負責將實例化Book,并利用返回的ArrayList對象,構造PageBean。以及接收由視圖傳遞而來的action參數。從而在PageBean對象中調用不同的方法,該方法返回Book[] 對象。最后將 Book[]和PageBean放入request中。本例中為PageListAction.java。
          4建立視圖組件,這部分由jsp來充當,為了不出現java 代碼,我們使用Struts提供的標簽庫,主要負責從request中取出剛剛放入的對象,通過反復調用PageListAction以及action參數,而實現分頁顯示。本例中為pagetest.jsp.
          5 建立并配置struts-config.xml。
          6 建立數據庫。
          三 實例代碼
          1 Book.java
          package bean;
          import java.sql.*;
          import java.util.ArrayList;
          /**
          * Struts分頁顯示數據Bean,對應數據庫中Book表
          */
          public class Book {
          private String bookname; //書名
          private String author;  //作者
          private String price;  //價格

          public Book(String name,String author,String price){
          this.bookname=name;
          this.author=author;
          this.price=price;
          }

          public String getAuthor() {
          return author;
          }

          public void setAuthor(String author) {
          this.author = author;
          }

          public String getBookname() {
          return bookname;
          }

          public void setBookname(String bookname) {
          this.bookname = bookname;
          }

          public String getPrice(){
          return this.price;
          }

          public void setPrice(String price){
          this.price=price;
          }

          public static ArrayList getAllBook(Connection connection){
          String sql="select * from book";
          ArrayList arrayList = new ArrayList();
          try{
          Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
          ResultSet resultSet = statement.executeQuery(sql);
          System.out.println("BookBean 數據查詢已完成!");
          while(resultSet.next())
          {
          String name = resultSet.getString("name");
          String author = resultSet.getString("author");
          String price = resultSet.getString("price");
          System.out.println("開始數據封裝:name="+name+"author="+author+"price="+price);
          Book book = new Book(name,author,price);
          arrayList.add(book);
          }
          connection.close();
          resultSet.close();
          }catch(SQLException e)
          {
          System.out.println("數據庫異常"+e.toString());
          }

          return arrayList;
          }
          }

          2 PageBean.java
          package page;
          import bean.Book;
          import java.util.*;
          /**
          * Struts分頁顯示邏輯Bean
          */
          public class PageBean {

          int currentPage=1; //當前頁
          public int totalPages=0; //總頁數
          int pageRecorders=5;//每頁5條數據
          int totalRows=0; //總數據數
          int pageStartRow=0;//每頁的起始數
          int pageEndRow=0; //每頁顯示數據的終止數
          boolean hasNextPage=false; //是否有下一頁
          boolean hasPreviousPage=false; //是否有前一頁
          ArrayList arrayList;
          Iterator it;
          public PageBean(){}

          public PageBean(ArrayList arrayList){
          this.arrayList=arrayList;
          totalRows=arrayList.size();
          it=arrayList.iterator();
          hasPreviousPage=false;
          currentPage=1;
          if((totalRows%pageRecorders)==0)
          {
          totalPages=totalRows/pageRecorders;
          }
          else
          {
          totalPages=totalRows/pageRecorders+1;
          }

          if(currentPage>=totalPages)
          {
          hasNextPage=false;
          }
          else
          {
          hasNextPage=true;
          }


          if(totalRows<pageRecorders)
          {
          this.pageStartRow=0;
          this.pageEndRow=totalRows;
          }
          else
          {
          this.pageStartRow=0;
          this.pageEndRow=pageRecorders;
          }

          }

          /**
          * @return Returns the currentPage.
          */
          public String getCurrentPage() {
          return this.toString(currentPage);
          }
          /**
          * @param currentPage The currentPage to set.
          */
          public void setCurrentPage(int currentPage) {
          this.currentPage = currentPage;
          }
          /**
          * @return Returns the pageRecorders.
          */
          public int getPageRecorders() {
          return pageRecorders;
          }
          /**
          * @param pageRecorders The pageRecorders to set.
          */
          public void setPageRecorders(int pageRecorders) {
          this.pageRecorders = pageRecorders;
          }
          /**
          * @return Returns the pageEndRow.
          */
          public int getPageEndRow() {
          return pageEndRow;
          }
          /**
          * @return Returns the pageStartRow.
          */
          public int getPageStartRow() {
          return pageStartRow;
          }
          /**
          * @return Returns the totalPages.
          */
          public String getTotalPages() {

          return this.toString(totalPages);
          }
          /**
          * @return Returns the totalRows.
          */
          public String getTotalRows() {
          return this.toString(totalRows);
          }
          /**
          * @return Returns the hasNextPage.
          */
          public boolean isHasNextPage() {
          return hasNextPage;
          }
          /**
          * @param hasNextPage The hasNextPage to set.
          */
          public void setHasNextPage(boolean hasNextPage) {
          this.hasNextPage = hasNextPage;
          }
          /**
          * @return Returns the hasPreviousPage.
          */
          public boolean isHasPreviousPage() {
          return hasPreviousPage;
          }
          /**
          * @param hasPreviousPage The hasPreviousPage to set.
          */
          public void setHasPreviousPage(boolean hasPreviousPage) {
          this.hasPreviousPage = hasPreviousPage;
          }
          public Book[] getNextPage(){

          currentPage=currentPage+1;
          System.out.println("PageBean.getNextPage()正在執行;");
          System.out.println("參數currentPage="+currentPage);

          if((currentPage-1)>0)
          {
          hasPreviousPage=true;
          }
          else
          {
          hasPreviousPage=false;
          }
          if(currentPage>=totalPages)
          {
          hasNextPage=false;
          }
          else
          {
          hasNextPage=true;
          }
          System.out.println("參數hasNextPage="+hasNextPage);
          System.out.println("準備執行PageBean.getBooks()");
          Book[] books=getBooks();
          this.description();
          return books;
          }

          public Book[] getPreviouspage(){
          currentPage=currentPage-1;

          if(currentPage==0){currentPage=1;}

          if(currentPage>=totalPages)
          {
          hasNextPage=false;
          }
          else
          {
          hasNextPage=true;
          }
          if((currentPage-1)>0)
          {
          hasPreviousPage=true;
          }
          else
          {
          hasPreviousPage=false;
          }
          Book[] books=getBooks();
          this.description();
          return books;
          }

          public Book[] getBooks(){
          System.out.println("pageBean.getBooks()開始執行;");
          if(currentPage*pageRecorders<totalRows){//判斷是否為最后一頁
          pageEndRow=currentPage*pageRecorders;
          pageStartRow=pageEndRow-pageRecorders;
          }
          else{
          pageEndRow=totalRows;
          pageStartRow=pageRecorders*(totalPages-1);
          }
          Book[] books=new Book[pageEndRow-pageStartRow+1];

          System.out.println("pageStartRow="+pageStartRow);
          System.out.println("pageEndRow="+pageEndRow);
          int j=0;
          for(int i=pageStartRow;i<pageEndRow;i++)
          {
          Book book=(Book)arrayList.get(i);
          books[j++]=book;

          }
          System.out.println("要顯示的頁面數據已經封裝,具體信息如下:");
          this.description();
          return books;
          }

          public String toString(int temp)
          {
          String str=Integer.toString(temp);
          return str;
          }

          public void description()
          {
          String description="共有數據數:"+this.getTotalRows()+"共有頁數: "+this.getTotalPages() +"當前頁數為:"+this.getCurrentPage()+" 是否有前一頁: "+this.isHasPreviousPage() +" 是否有下一頁:"+this.isHasNextPage()+" 開始行數:"+this.getPageStartRow()+" 終止行數:"+this.getPageEndRow();
          System.out.println(description);
          }
          }
          3 PageListAction.java
          package page;
          import org.apache.struts.action.*;
          import javax.servlet.http.*;
          import comm.Constants;
          import bean.Book;
          import java.util.*;
          import javax.sql.DataSource;
          /**
          * Struts分頁顯示Action
          */
          public class PageListAction extends Action {

          public PageListAction(){}
          ArrayList arrayList=new ArrayList();
          PageBean pb;

          public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
          String action;
          action=request.getParameter("action");
          if(action==null || action.equals("null")){ //第一次讀取數據
          try{
          DataSource datasource=this.getDataSource(request,Constants.DATASOURCE_KEY);
          arrayList=Book.getAllBook(datasource.getConnection());
          System.out.println("第一步,數據已經成功傳遞到Action,action="+action);
          }catch(Exception e){
          e.printStackTrace();
          System.out.println("數據庫連接出現異常");
          }
          pb=new PageBean(arrayList);
          Book[] books=pb.getBooks();
          pb.description();
          request.setAttribute("result",books);
          request.setAttribute("page",pb);
          }
          else
          {
          if(action=="nextPage" || action.equals("nextPage"))
          {
          System.out.println("參數action="+action);
          System.out.println("函數pb.getNextPage()準備執行");
          Book[]books=pb.getNextPage();
          request.setAttribute("page",pb);
          request.setAttribute("result",books);
          }
          if(action=="previousPage" || action.equals("previousPage"))
          {
          System.out.println("參數action="+action);
          System.out.println("函數pb.getPreviouspage()準備執行");
          Book[] books=pb.getPreviouspage();
          request.setAttribute("page",pb);
          request.setAttribute("result",books);
          }
          }
          return (mapping.findForward("success"));
          }
          }
          4 pagetest.jsp
          <%@ 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=gb2312" language="java"%>
          <html:html locale="true">
          <head>
          <meta http-equiv="Content-Type" content="text/html; charset=gb2312">
          </head>
          <body>
          <table border="1">
          <tr><th>書名</th><th>作者</th><th>價格</th></tr>
          <logic:present name="result">
          <logic:iterate id="book" name="result" type="bean.Book" >
          <logic:present name="book">
          <tr>
          <td><bean:write name="book" property="bookname" /></td>
          <td> <bean:write name="book" property="author" /></td>
          <td><bean:write name="book" property="price" /></td>
          </tr>
          </logic:present>
          </logic:iterate>
          </logic:present>
          </table>
          <logic:equal name="page" property="hasNextPage" value="true">
          <html:link page="/page.do?action=nextPage">nextPage</html:link>
          </logic:equal>
          <logic:equal name="page" property="hasPreviousPage" value="true">
          <html:link page="/page.do?action=previousPage">PreviousPage</html:link>
          </logic:equal>
          共有數據總數<bean:write name="page" property="totalRows"/>;
          共分<bean:write name="page" property="totalPages"/>頁,當前是第
          <bean:write name="page" property="currentPage"/>頁
          </body>
          </html:html>
          5 struts-config.xml
          <?xml version="1.0" encoding="ISO-8859-1" ?>

          <!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
          "

          <struts-config>
          <data-sources>
          <data-source key="dataSource" type="org.apache.commons.dbcp.BasicDataSource">
          <set-property property="driverClassName" value="com.microsoft.jdbc.sqlserver.SQLServerDriver"/>
          <set-property property="url" value="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=eBookStore;SelectMethod=cursor"/>
          <set-property property="username" value="limq"/>
          <set-property property="password" value="1"/>
          <set-property property="maxActive" value="10"/>
          <set-property property="maxWait" value="5000"/>
          <set-property property="defaultAutoCommit" value="true"/>
          <set-property property="defaultReadOnly" value="false"/>
          </data-source>
          </data-sources>
          <form-beans>
          </form-beans>
          <global-forwards>
          </global-forwards>
          <action-mappings>
          <action path="/page" type="page.PageListAction" scope="request">
          <forward name="success" path="/pagetest.jsp"/>
          </action>
          </action-mappings>
          <controller>
          </controller>
          </struts-config>
          6 建立eBookStore數據庫,以及表book(name,author,parce);其中數據的配置可以根據你的不同情況在struts-config.xml中而定。
          7 Constants.java
          package comm;

          /**
          * this interface provides the constant string for applicator constant
          */
          public class Constants {
          /**
          * name of the User Object in HttpSession
          */
          public static String USER_KEY="user";
          /**
          * dataSource name
          */
          public static String DATASOURCE_KEY="dataSource";
          }

          方案<二>

          ●struts中的分頁實例- -

          ??????????????????????????????????????

          這僅是一個入門實例,簡潔實用,從網上整理而來,供參考。這里僅列出部分文件,其它文件、數據庫及目錄結構請從本站下載。下載源文件


          一、struts-config.xml配置,主要是配數據庫,這里用access。
          <?xml?version="1.0"?encoding="ISO-8859-1"??>

          <!DOCTYPE?struts-config?PUBLIC
          ??????????"-//Apache?Software?Foundation//DTD?Struts?Configuration?1.2//EN"
          ??????????"http://jakarta.apache.org/struts/dtds/struts-config_1_2.dtd">


          <struts-config>
          <data-sources>
          ???<data-source?key="dataSource"?type="org.apache.commons.dbcp.BasicDataSource">
          ????????????<set-property?property="driverClassName"?value="sun.jdbc.odbc.JdbcOdbcDriver"?/>
          ????????????<set-property?property="url"?value="jdbc:odbc:page"?/>
          ????????????<set-property?property="username"?value="admin"?/>
          ????????????<set-property?property="password"?value=""?/>
          ????????????<set-property?property="maxActive"?value="20"?/>
          ????????????<set-property?property="maxWait"?value="5000"?/>
          ????????????<set-property?property="defaultAutoCommit"?value="true"?/>
          ????????????<set-property?property="defaultReadOnly"?value="false"?/>
          ????????????<set-property?property="validationQuery"?value="SELECT?1"?/>
          ????????????<set-property?property="removeAbandoned"?value="true"?/>
          ????????????<set-property?property="removeAbandonedTimeout"?value="120"?/>????????????
          ????????????<set-property?property="encoding"?value="false"?/>????????????
          ????????</data-source>

          ?</data-sources>
          ??<form-beans>
          ??</form-beans>
          ??<global-forwards>
          ??</global-forwards>

          ??<action-mappings>
          ??<action?path="/page"?type="page.DataSourceAction"?scope="request">
          ??<forward?name="success"?path="/pagetest.jsp"/>
          ??</action>
          ??</action-mappings>

          ??<controller>
          ??</controller>
          </struts-config>

          二、Action類
          用?page.do?start=1?來顯示第一個頁面?
          參數說明:?
          ??list:信息列表?
          ??start:開始位置?
          ??page:每頁顯示的信息數目?
          ??pages:?總頁數
          ??previous:上頁開始位置?
          ??next:下頁開始位置?

          package?page;
          import?org.apache.struts.action.*;
          import?javax.servlet.http.*;

          import?java.util.*;
          import?javax.sql.*;
          import?java.sql.*;
          import?bean.*;

          public?class?DataSourceAction?extends?Action?{

          ?public?DataSourceAction(){}
          ?
          ?public?ActionForward?execute(ActionMapping?mapping,?ActionForm?form,?HttpServletRequest?request,?HttpServletResponse?response)?throws?Exception?{???
          ??try{
          ??????DataSource?ds=this.getDataSource(request,"dataSource");???
          ??????Connection?con?=?ds.getConnection();
          ??????Statement?stmt?=?con.createStatement();
          ??????ResultSet?resultSet?=?stmt.executeQuery("select?count(*)?from?book"?);?
          ??????resultSet.next();?
          ??????int?data_num=resultSet.getInt(1);?
          ??????int?start=1;
          ??????int?page?=?4;?//每頁的記錄數。
          ??????int?pages=data_num/page;
          ??????if(data_num%page!=0)
          ?????????pages++;
          ??????if(request.getParameter("start")!=null)
          ??????????start?=?Integer.parseInt(request.getParameter("start"));?
          ??????if(request.getParameter("go")!=null){
          ????????????????int?go?=?Integer.parseInt(request.getParameter("go"));?
          ????????????????if(go<=1)
          ??????????????????start=1;
          ????????????????else?if(go>pages)
          ??????????????????start=(pages-1)*page+1;
          ????????????????else?
          ???????????????????start=(go-1)*page+1;
          ???????}?
          ?????
          ??????String?sql?=?"SELECT?*?FROM?book?where?id>="+start+"?and?id<"+(start+page);
          ??????resultSet?=?stmt.executeQuery(sql);??
          ??????ArrayList?list?=?new?java.util.ArrayList();?
          ??????while(resultSet.next())
          ??????{??
          ????????int?id=resultSet.getInt("id");
          ????????String?name?=?resultSet.getString("name");
          ????????String?author?=?resultSet.getString("author");
          ????????String?price?=?resultSet.getString("price");
          ????????System.out.println("開始數據封裝:name="+name+"author="+author+"price="+price);
          ????????Book?book=?new?Book(id,name,author,price);???????
          ????????list.add(book);
          ??????}
          ????con.close();
          ????request.setAttribute("pages",new?Integer(pages));
          ????request.setAttribute("list",list);
          ????//request.setAttribute("start",?new?Integer(start));?
          ????request.setAttribute("page",?new?Integer(page));?

          ????????//?if?there?is?a?previous?page,?set?the?previous?variable?
          ????????int?previous?=?start-page;?
          ????????if?(?previous>=0?){?
          ????????????request.setAttribute("previous",?new?Integer(previous));?
          ????????????System.out.println?("previous:"?+?previous);?
          ????????}?

          ????????//?if?there?is?a?next?page,?set?the?next?variable?
          ????????int?next?=?start+page;?
          ????????if?(?next<=data_num?){?
          ????????????request.setAttribute("next",?new?Integer(next));?
          ????????????System.out.println?("next:"?+?next);?
          ????????}?

          ???}catch(SQLException?e){
          ??????????e.printStackTrace();
          ??????????System.out.println("數據庫連接出現異常");
          ??????}?
          ???
          ?????????????return?(mapping.findForward("success"));
          ??}?
          }


          三、bean類Book.java
          package?bean;
          import?java.sql.*;
          import?java.util.ArrayList;
          public?class?Book?{
          ?int?id;
          ?private?String?bookname;?//書名
          ?private?String?author;???//作者
          ?private?String?price;????//價格
          ?
          public?Book(int?id,String?name,String?author,String?price){
          ?this.id=id;
          ?this.bookname=name;
          ?this.author=author;
          ?this.price=price;
          }

          public?int?getId(){?
          ????????return?id;?
          ????}?

          ?public?String?getAuthor()?{
          ??return?author;
          ?}

          ?public?void?setAuthor(String?author)?{
          ??this.author?=?author;
          ?}

          ?public?String?getBookname()?{
          ??return?bookname;
          ?}

          ?public?void?setBookname(String?bookname)?{
          ??this.bookname?=?bookname;
          ?}
          ?
          ?public?String?getPrice(){
          ?????return?this.price;?
          ?}
          ?
          ?public?void?setPrice(String?price){
          ?????this.price=price;?
          ?}
          ?
          }
          四、分頁的jsp頁面pagetest.jsp,用了jstl中的c標記。
          <%@?page?contentType="text/html;?charset=gb2312"?language="java"%>
          <%@?page?import="java.util.*"?%>
          <%@?page?import="bean.*"?%>
          <%@?taglib?prefix="c"?uri="http://java.sun.com/jstl/core"?%>
          <%@?taglib?uri="/tags/struts-bean"?prefix="bean"?%>
          <%@?taglib?uri="/tags/struts-html"?prefix="html"?%>
          <%@?taglib?uri="/tags/struts-logic"?prefix="logic"?%>

          <logic:iterate?id="book"?name="list"?type="bean.Book">?
          ????????????<br><html:link??
          ????????????????????paramId="id"?paramName="book"?paramProperty="id"?
          ????????????????????page="/messagedetail.do">?
          ????????????????????<bean:write?name="book"?property="bookname"?/>?
          ????????????????</html:link>?
          </logic:iterate>?

          <form?action="/TestPage/page.do">
          ???<logic:present?name="previous">?
          ????????????<html:link??
          ????????????????????paramId="start"?paramName="previous"?
          ????????????????????page="/page.do">?
          ????????????????????上一頁?
          ????????????????</html:link>?
          ???</logic:present>?

          ???<logic:present?name="next">?
          ??????????????<html:link??
          ????????????????????paramId="start"?paramName="next"?
          ????????????????????page="/page.do">?
          ????????????????????下一頁?
          ????????????????</html:link>?
          ???</logic:present>?

          每頁<c:out?value="${page}"/>條記錄,共<c:out?value="${pages}"/>頁??跳到<input?type="text"??name="go"?size="3"?maxlength="30"?>
          <input?type="submit"?value="go"?>
          </form>
          ?????????



          OK!!!!
          五、測試,請下載本實例的目錄結構TestPage,放入tomcat的webapps下,在瀏覽器中輸入:
          ????http://127.0.0.1:8080/TestPage/page.do

          posted on 2006-12-11 16:37 放水老倌 閱讀(544) 評論(0)  編輯  收藏 所屬分類: J2EE
          主站蜘蛛池模板: 资阳市| 电白县| 会东县| 磐石市| 马关县| 青河县| 琼中| 安西县| 永康市| 青田县| 高邮市| 杭锦后旗| 定襄县| 宜宾县| 潍坊市| 康乐县| 当阳市| 农安县| 淮阳县| 连南| 辽中县| 江北区| 融水| 股票| 清流县| 博爱县| 赤水市| 双江| 玛曲县| 翁牛特旗| 太湖县| 临江市| 长泰县| 启东市| 介休市| 桃园市| 琼海市| 台江县| 苏尼特右旗| 肥城市| 隆子县|