One implementation of struts Paging

Source: Internet
Author: User

For Web ApplicationsProgramPages always make our developers feel a headache, not because of the technical difficulties, but because there is not much to do with the business, you have to spend a lot of time dealing with it. If you don't pay attention to it, it will be even more depressing if you encounter any problems from time to time. It is time to process the page for a project I am working on. I feel that I have not handled the page well before, so the basic goal of this change isIn the existing (non-Paging)CodeAnd the same Code can be applied to pages of different modules.. The following is my method:

First, consider that most pages occur in the list, and also need to be used in combination query. In my project, the List action is generally named listxxxactioin. For example, the list of customers is listclientsaction. Before pagination, all objects in listxxxaction are retrieved through the request. setattribute () is placed in the request, and then the request is directed to the list JSP (such as listclients. JSP) display (You may say you do not put the business logic in the action, but this is not the focus of our consideration ). After paging, we only take the objects corresponding to the user request page. To maximize code reuse, I have done the following:

1. Create a new pager class with int attributes such as beginpage, endpage, currentpage, pagesize, and total, it represents the start page, end page, current page, number of records on each page, and total number of records, which are mainly used for displaying page navigation on the JSP page. Note that the currentpage attribute starts from 0.

2. Create a New abstractlistactioin class and let all listxxxactions inherit it. This class overwrites the execute () method, where you can determine the permission and so on, and then execute an abstract act () method after the permission is passed. This Act () implemented by listxxxaction.

3. Add the getpage () method to abstractlistaction to get the page number of the user request from the request (if not requested, it is considered as 0th page ):

  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 to abstractlistaction to add a pager class instance to the request for the JSP page to display the page navigation:

 
ProtectedPager makepager (httpservletrequest request,IntTotal) {pager Pager=NewPager (); pager. settotal (total); pager. setpagesize (config. getinstance (). getpagesize (); pager. setbeginpage (0); Pager. setendpage (pager. gettotal ())-1)/pager. getpagesize () + 1); Pager. setcurrentpage (getpage (request ));ReturnPager ;} 

Note that in my project, the number of records on each page is written in the configuration file. If you do not have a configuration file, enter a number for the parameter of setpagesize () in the above 4th rows, for example, pager. setpagesize (10 );

5. In this way, all listxxxactions can use getpage () to obtain the page number of the request, and can easily construct the pager object to be placed in the request through makepager. Now we need to make some modifications to the Code for retrieving data from the database, that is, to retrieve only the part of the required data. Since Hibernate is used in my project, this modification is not very difficult. Before paging, in my listclientsaction, we construct a query to obtain all the clients. Now, we only need to add two more sentences (setmaxresults and setfirstresult) after constructing the query:

 query =;  //   construct a query statement   int  total =; ///   get the total number of records  pager = makepager (request, total );  //   call the methods 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 position  request. setattribute (pager.  class . getname (), pager); ///   put pager in request  request. setattribute (client.  class . getname (), query. list (); 

There is a problem currently, that is, in the second sentence of the above Code, it should be the total number of records, but I do not have a particularly good way to get the number of records without getting all objects, it can only be scary to use "int Total = query. list (). size (); ", Khan ......

6. Finally, I wrote a page navigation JSP page pager. jsp for each JSP that displays the list to include. The Code is as follows:

<% Pager = (PAGER) request. getattribute (pager. Class . Getname ()); %> <Table width = "90%" border = "0" align = "center" cellpadding = "2" cellspacing = "1" bgcolor = "# cccccccc"> <tr> <TD bgcolor = "# eeeeee" align = "right"> <Bean: message key = "prompt. pager "arg0 =" <% = string. valueof (pager. gettotal () %> "/> [ <% 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 = "<% = "? "+ 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 in this way. Request. getquerystring () may contain page number requests such as "q = 2" or 0th pages by default. Therefore, the replaceall () method is used to remove them, add the corresponding page number request string (such as "q = 3") to the front of Qs. The advantage of this is that each module can use this page navigation without losing other parameters in the URL (for example, after the sorting function is added in the future, the URL may contain parameters such as "ction = DESC ).

05-4-14 update: I found that in tomcat4.1 and websphere5.0, request. the address obtained by the getrequesturl () method is different. Therefore, considering the compatibility, links on each page use links relative to this page.

In the list JSP (listclients. JSP), it is very easy to include it (the reason to put it in <logic: notempty> is to do not display the page navigation when no record can be displayed ):

 
<Logic: notempty name = "<% = client. class. getname () %> "> <% @ include file ="/pager. JSP "%> </logic: notempty>

After several steps above, my customer list can be displayed by page. For more information, see. If you need paging in another module, such as the Department list, you only need 1. Modify listdeptsaction to inherit abstractlistaction; 2. Add setmaxresults () and setfirstresults () methods in listdeptsaction, 3. In listdepts. the appropriate location in JSP include page navigation. The changes are quite small.

Finally, if you want the combined query results to be paginated, you must specify the method attribute of the Combined Query Form as "get", so that the query requirements will be recorded in the URL, paging navigation can work properly (the query request and the requested page number are submitted each time the page is changed ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.