Struts paging one implementation
In the web application, the page always makes our developers feel a headache, not because of how difficult the technology is, but the same problem is not too many relationships, you have to spend a lot of effort. If you don't care, you will be more depressed. A project I have now has to go to the processing paging. I feel that I have dealt with it before, so this time I have changed, the basic goal is based on the code (unpiped) code, try to make minimize minimize it. And the same code can be applied to the paging of different modules. Here is my way:
First, considering that the vast majority of the page occurs in a list, it is also required to be used in combination queries. In my project, the Action of the list is Listxxxactioin, such as the customer list is ListClientSAction, and more. Before not paging, the ListxxxAction will take all objects, put it in the request.setttribute (), then turn the request to the list (for example, listclients.jsp) ", you may say not in action Playing business logic, but now this is not the focus of our consideration). After the paging, we only take those objects corresponding to the user request page. In order to maximize the code reuse, I did the following work:
1. Newly built a Pager class, which has an int type attribute, and Total, etc. Page Display Page Navigation is used. Note that the currentPage property begins with 0.
2, create a new AbstractListactioIn and let all ListxxxActions inherit it. In this class, the Execute () method can be overcute () method, which can be determined here, etc., and execute an ABSTRACT ACT () method after judging the permissions, this ACT () is implemented by listXxxAction.
3. Add a getPage () method to add the getPage () method to get the page number requested from Request (if not requested, it is considered to be page 0):
protected
int
getPage (httpservletRequest request) {string p
=
Request.getParameter
"
p
"
);
IF
(p
==
NULL
)
Return
0
;
Else
Try
{
Return
Integer.Parseint (P);
Catch
Numberformatexception E) {
Return
0
}}
4. Add the MakePager () method in AbstractListion to add an instance of a Pager class to the Request for JSP page display page navigation:
Protected Pager MakePager (httpservletRequest Request,
int
Total) {Pager Pager
=
New
Pager (); Pager.Settotal (Total); Pager.GetInstance (). Getpagesize ()); Pager.SetBeginPage
0
Pager.setenDpage ((Pager.gettotal ())
-
1
)
/
Pager.getpageSize ()
1
Pager.SetCurrentPage (getPage (Request));
Return
PAGER;
Note that in my project, the number per page is written in the configuration file. If you don't have a configuration file, the parameters of the fourth line above setPageSize () can be filled with, such as Pager.SetPageSize (10);
5, so, all ListxxxAction can be used with getPage () to get the requested page, and can be easily enabled by the MakePager () constructor. Pager objects in the Request. Now do some modifications on the code from the data library, that is, take the part of the data required. This modification is not very difficult because I use Hibernate in my project. Before I don't paise, I get all the client in my listclientsaction, now I get the entire client, now, just add two words after constructed this query:
Query Query
=
;
//
Construct Query's statement
int
Total
=
;
//
Get the total number of records
Pager Pager
=
Makepager (Request, Total);
//
Call the method in the parent class to construct a Pager instance
Query.setMaxResults (Pager.getPagesize ());
//
Set the number of records per page
Query.setFirstResult (Pager.getCurrentPage ()
*
Pager.getpagesize ());
//
Set the start location
Request.setttribute (Pager.class.getName (), PAGER);
//
Place Pager in Request
Request.setttribute (client.class.getname (), query.list ());
There is currently a problem, that is, in the second sentence of the above code, it should be a total number of records, but I have no particularly good way to get all the objects and directly get the number of records, which can only be very horrible "int total = Query.list (). size (); ", sweat ...
6. Finally, I wrote a page navigation JSP page Pager.jsp, for the JSP of each display list to include, the code is as follows:
<%
Pager Pager
=
(PAGER) (Pager.class.getName ());
%>
<
Table Width
=
"
90%
"
Border
=
"
0
"
Align
=
"
Center
"
Cellpadding
=
"
2
"
Cellspacing
=
"
1
"
Bgcolor
=
"
#Cccccc
"
>
<
TR
>
<
TD BGColor
=
"
#Eeeeee
"
Align
=
"
Right
"
>
<
Bean: Message Key
=
"
PROMPT.PAGER
"
arg0
=
"
<% =
""
Pager.gettotal ()%> "
/>
[
<%
String URL
=
Request.getRequestURL (). TOSTRING ();
for
(
int
i
=
Pager.getbeginPage (); i
<
Pager.GETENDPAGE (); i
) {
IF
(i
==
Pager.getcurrentpage ()) {
%>
<% =
(i
1
)
%>
<%
}
Else
{String QS
=
Request.GetQueryString ()
==
NULL
?
""
: request.getQueryString (); String OP
=
"
p =
"
Pager.getcurrentpage ();
//
Original Page Parameter EXPRESSION
String NP
=
"
p =
"
i;
//
New Expression
IF
(QS.Indexof (OP)
== -
1
QS
=
NP
"
&
"
QS; QS
=
QS.ReplaceAll (OP, NP);
%>
<
a href
=
"
<% = URL
"
?
"
QS%>
"
> <% =
(i
1
)
%>
a
>
<%
}
%>
<%
IF
(i
<
Pager.GETENDPAGE ()
-
1
) {
%>
&
NBSP;
<%
}
%>
<%
}
%>
]
TD
>
TR
>
TABLE
>
I think it is necessary to explain that in the above code, the URL corresponding to each page is handled. Take Request.getRequestURL (). ToString () and request.getQueryString (), where the former does not need to change, and the latter may contain "Q = 2" page requests may not contain the default request page 0 Therefore, it is removed by the replaceall () method, and then the corresponding page number request string (such as "Q = 3") is added in front of QS. The advantage of this is that each module can use this page navigation and will not lose other parameters in the URL (for example, after the ordering function will be added, "DIR = DESC" parameters may be included).
In list JSP (ListClients.jsp), it is very simple to include it (whose
<
Logic: NOTEMPTY NAME
=
"
<% = Client.class.getname ()%>
"
>
<%
@Include file
=
"
/Pager.jsp
"
%>
Logic: NOTEMPTY
>
After the processing above, my customer list has been paged, and the effect is shown below. If you also need paging in another module, such as a list of sectors, only 1. Modify ListDeptsAction, 2, add setMaxResults () and setFirstResults () methods in ListDeptsAction, 3, in ListDepts.jsp Include in ListDepts.jsp Include Page navigation, it is possible, and the change is quite small.
Finally, if you want the result of the combined query, you must specify the Method property of the combination query form to "get" so that the query requires that the query will be recorded in the URL, and the pages navigation can be normal (query each time you change the page. Requirements and request page submitted). One implementation of paging in Struts
Paging feature in my project
1, ideas
Use a page control class, which record page information, such as page, next page, current page, etc. In the action of the query, this control class and query conditions are passed to the database access bean and then save the two parameters in the user session. In paging control Action, the BEAN access to the database is called using the received paging parameters.
2, realize
(1) Pieces Control class
/ * @Author Nick
* CREATED ON 2004-3-18
* File Name: PageController.java
*
*
* /
Package com.tower.util;
/ **
* @Author Nick
* 2004-3-18
* Used to turn page control
*
* /
Public class pageController {
INT TOTALROWSAMOUNT; / / total number
Boolean rowsamountset; // Whether to set TOTALROWSAMOUNT
INT PageSize = 2; // Variety per page
INT CurrentPage = 1; // Current page number
Int nextpage;
INT Previouspage;
INT TOTALPAGES; / / total page
Boolean Hasnext; // Is there a next page
Boolean Hasprevious; // Is there a previous page
String description;
INT PagestartRow;
Int pagendrow;
Public pageController (int Totalrow) {
SetTotAlrowsAmount (TotalRows);
}
Public pageController () {}
/ **
* @Param I
* Set the total number of lines
* /
Public void settotalrowsamount (int i) {
IF (! this.rowsamountset) {
Totalrowsamount = i;
Totalpages = Totalrowsamount / Pagesize 1;
SetCurrentPage (1);
THIS.ROWSAMOUNTSET = TRUE;
}
}
/ **
* @Param I
*
* current page
*
* /
Public void setCurrentPage (INT i) {
CurrentPage = i;
NextPage = CURRENTPAGE 1;
PreviousPage = CURRENTPAGE-1;
// Calculate the current page to start rows and end lines
CurrentPage * Pagesize PageEndrow = CURRENTPAGE * PAGESIZE; PageStartrow = PageEndrow-Pagesize 1; } else { PageEndrow = TotalRowsamount; PageStartrow = PageSize * (Totalpages-1) 1; } / / Is there a previous page and IF (NextPage> Totalpages) { Hasnext = FALSE; } else { Hasnext = True; } IF (previouspage == 0) { HaspRevious = false; } else { Hasprevious = true; } System.out.println (this.Description ()); } / ** * @Return * / Public int getcurrentpage () { Return CurrentPage; } / ** * @Return * / Public boolean ishasnext () { Return hasnexT; } / ** * @Return * / Public boolean ishasis () { Return Hasprevious; } / ** * @Return * / Public int getNextPage () { Return nextpage; } / ** * @Return * / Public int getpagesize () { Return PageSize; } / ** * @Return * / Public int getPreviouspage () { Return Previouspage; } / ** * @Return * / Public int gettotalpages () { Return Totalpages; } / ** * @Return * / Public int gettotalrowsamount () { Return TotalrowsAmount; } / ** * @Param B * / Public void sethasnext (boolean b) { Hasnext = B; } / ** * @Param B * / Public void setHasprevious (Boolean B) { HaspRevious = B; } / ** * @Param I * / Public void setnextPage (INT i) { NextPage = i; } / ** * @Param I * / Public void setpageSize (int i) { PageSize = i; } / ** * @Param I * / Public void setpreviouspage (int i) { Previouspage = i; } / ** * @Param I * / Public void setTotalpages (INT I) { Totalpages = i; } / ** * @Return * / Public int getpagendrow () { Return PageEndRow; } / ** * @Return * / Public int getpagestRow () { Return PagestartRow; } Public string getdescription () { String description = "Total:" this.gettotalrowsamount () "items" this.gettotalpages () "Pages"; // this.currentpage "previous" this.hasprevious // "Next:" this.hasnext // "START ROW:" this.pagestRow // "End Row:" this.pageendrow; Return description; } Public string description () { String description = "Total:" this.gettotalrowsamount () "items" this.gettotalpages () "Pages, Current Page:" THIS.CURRENTPAGE "previous" this.hasprevious Next: " this.hasnext "START ROW:" this.pagestRrow "End Row:" this.pageendrow; Return description; } Public static void main (string args []) { PageController PC = New PageController (3); System.out.println (pc.getdescription ()); // pc.setcurrentpage (2); // system.out.println (pc.description ()); // pc.setcurrentpage (3); // system.out.println (pc.description ()); } } (2) Query the code snippet of Action Public ActionForward Execute ActionMapping mapping, Actionform Form, HTTPSERVLETREQUEST REQUEST, Httpservletresponse response Throws exception { Base queryform = (base) form; IF (! queryform.getname (). Equals ("")) { PageController PC = New PageController (); Employeebase service = new EmployeeBase (); ArrayList Result = (arraylist) Service.Search (Queryform, PC); HttpSession session = request.getations (); Session.setttribute ("Queryform", queryform); Session.SetaTRibute ("PageController", Service.getPageController ()); Request.setattribute ("QueryResult", Result; Request.SetaTRibute ("PageController", Service.getPageController ()); Return mapping.findforward ("haveresult"); } else { Return mapping.findforward ("noresult"); } } (3), page the code snippet Public ActionForward Execute ActionMapping mapping, Actionform Form, HTTPSERVLETREQUEST REQUEST, Httpservletresponse response Throws exception { // Read forward page parameters TurnPageform Turnpageform = (TurNPageform) Form; / / Take the query information from the PageController and use the call interface processing result provided by Bean. HttpSession session = request.getations (); PageController PC = (pageController) session.getattribute ("PageController"); Base Queryform = (Base) session.getattribute ("queryform"); Pc.SetCurrentPage (TurnPageform.getViewPage ()); Employeebase service = new EmployeeBase (); ArrayList Result = (arraylist) Service.Search (Queryform, PC); / / Write data to request according to parameters Request.RemoveAttribute ("queryResult"); Request.RemoveAttribute ("PageController"); Request.setattribute ("QueryResult", Result; Request.setttribute ("PageController", PC); // forward to the display page Return mapping.findforward ("haveresult"); } (4) Database Access to Pieces in Beans Public Collection Search (Base Base, PageController PC) Throws sqlexception { ArrayList Emps = new arraylist (); ResultSet RS = GetSearchResult (BASE); Rs.absolute (-1); Pc.SettotAlrowsamount (Rs.Getrow ()); SETPAGECONTROLLER (PC); IF (rs.getrow ()> 0) { rs.absolute (pc.getpagestartrow ()); Do { System.out.println ("in loop" qGetrow ()); Base b = new base (); B.setname (rs.getstring ("name"); B.setidcard (rs.getstring ("iDCard")); System.out.println ("from DB:" rs.getstring ("iDCard")); Emps.Add (b); IF (! rs.next ()) { Break; } } while (rs.getrow () <(pc.getpageendrow () 1)); } Return EMPS; } (5) Code pieces in JSP Previous logic: Equal> NEXT logic: Equal> In this way, the functionality of the page can be expressed to the client in the way you like.