One implementation of struts paging

Source: Internet
Author: User

First of all, consider the majority of paging occurs in the list, the combination of queries also need to use. In my project, the list action is usually named Listxxxactioin, such as the customer list is listclientsaction and so on. Before paging, all objects are taken out of the listxxxaction and placed in the request by Request.setattribute (). The request is then directed to the list of JSPs (for example, listclients.jsp) to be displayed (you might say don't put business logic in action, but now this is not the focus of our consideration). After paging, we only take those objects that correspond to the user request page. To maximize code reuse, I did the following:

1. Create a new pager class that has attributes of type int such as Beginpage, EndPage, CurrentPage, pagesize, and total, representing the start page, end page, current page, number of records per page, and number of records, respectively. It is primarily for JSP pages to display the page navigation used. Note that the CurrentPage property starts at 0.

2, create a new Abstractlistactioin class, and let all listxxxaction inherit it. Override the Execute () method in this class, where you can judge permissions and so on, and execute an abstract act () method after the permission is passed, and this Act () is implemented by Listxxxaction.

3. Add the GetPage () method in abstractlistaction to get the page number requested by the user from request (No. 0 page if not requested):

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 the Abstractlistaction to add an instance of the pager class to the request, for the JSP page to display the page navigation:

Protected Pager Makepager (httpservletrequest request, int total) {     Pager pager=new Pager ();     Pager.settotal (total);     Pager.setpagesize (Config.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 of records per page is written in the configuration file, if you do not have a configuration file, the above 4th line setpagesize () parameters directly fill in the number, such as pager.setpagesize (10);

5, in this way, all listxxxaction can use GetPage () to get the requested page number, and can easily through the Makepager () to construct the pager object that needs to be placed in the request. Now it's time to make some more changes to the code that takes the data from the database, which is just the part of the data you need. Because hibernate is used in my project, this modification is not very difficult. Before paging, in my listclientsaction by constructing a query to get all the client, now, as long as you construct this query and add two sentences (Setmaxresults and Setfirstresult) can:

query query =  ;//construct query with the statement  int  total =;//Get the overall record number  Pager Pager = Makepager (request, totals);// Call a 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 start position Request.setattribute (Pager.class.getName (), Pager);//Put Pager in Request Request.setattribute ( Client.class.getName (), query.list ());

There is a problem, that is, in the second sentence of the above code, should be the total number of records, but I do not have a particularly good way not to get all the objects and directly get the number of records, can only be very scary with "int total = Query.list (). Size ();", Khan ...

6, finally, I wrote a page navigation jsp page pager.jsp, for each display list of JSP to include, the code is as follows:

<%pager pager= (Pager) Request.getattribute (Pager.class.getName ());%><table width= "90%" border= "0" align= " Center "cellpadding=" 2 "cellspacing=" 1 "bgcolor=" #CCCCCC "><tr> <td bgcolor=" #EEEEEE "align=" right "> & Lt;bean:message key= "Prompt.pager" arg0= "<%=string.valueof (Pager.gettotal ())%>"/> [<%for (int i=pager.g Etbeginpage (); I<=pager.getendpage (); i++) {if (I==pager.getcurrentpage ()) {%> <%= (i+1)%> <%}e        lse{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 corresponding URL for each page is handled as such. Request.getquerystring () may contain page requests such as "q=2", or it may not contain the No. 0 page of the default request, so the ReplaceAll () method is used to remove it, and the corresponding page number request string (such as "q=3") is added to the front of the QS. The advantage of this is that each module can use this page navigation, and no other parameters in the URL will be lost (for example, the URL may contain parameters such as "Direction=desc" after joining the sorting function).

05-4-14 Update: I found that in Tomcat4.1 and Websphere5.0, the Request.getrequesturl () method gets the same address, so for compatibility, each page link uses a link relative to this page.

In the list JSP (listclients.jsp), it is very simple to include it (the reason to put it in <logic:notEmpty> is to not show the page navigation when no record can be displayed):

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

After a few steps above, my customer list has been able to achieve the pagination, the effect is seen. If you need to page in another module, such as the department list, only need 1, modify listdeptsaction inherit abstractlistaction,2, add Setmaxresults in Listdeptsaction () and Setfirstresults () method, 3, the appropriate position in the listdepts.jsp include page navigation, you can, the changes are quite small.

Finally, if you want the results of a combined query to be paginated, you must specify that the method property of the combined query form is "GET", so that the query request is recorded in the URL, and the paging is done properly (each page is submitted with the query request and the requested page number).

One implementation of struts paging

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.