A highly efficient and concise method for struts paging

Source: Internet
Author: User
Tags config count header int size key sql string access
Pagination on the Internet to see a few structs pagination, feeling is not very perfect, so according to their own experience, wrote a relatively efficient and concise method of paging. Because of my limited level, if we have any better ideas, welcome to enlighten us.
  
   I. Development environment
  
My development environment is: JBuilder x + Weblogic 8.1 + Oracle 9i + Windows 2003, if your friends ' development environment is not the same.
  
   second, the development of ideas
  
Since it's about struts, it's natural to be out of MVC, as is the paging display.
  
1, the establishment of the database and the corresponding table, the table of this example is tcertificate.
  
2, set up the appropriate model components, corresponding to the database you want to query the table. This section is implemented by the DAO data Access layer, if some friends are unfamiliar with DAO, you can check the relevant information. This example is implemented by Certificatedao.java.
  
3, to establish the required model components of pagination, by JavaBean to act as, and Certificatedao implementation. Many of the methods introduced on the Web have the phenomenon of the coupling of data and paging components, which is the main difference between this method and other paging methods.
  
4, the establishment of controller components, this part by the action in struts to achieve. It is primarily responsible for instantiating the Certificatedao, taking only the data records to be displayed, depositing the ArrayList object and then returning, and putting it in the request. The paging section is constructed separately according to the paging condition, avoiding the situation that is mixed with DAO. Some of the other paging methods introduced on the Web are basically reading out all the query data at once and then constructing the paging-related component. In this way, if the amount of data is large, it is easy to create bottlenecks. In this example, because it is not a one-time read all the data of the query, but only read out a page to display the data records, which saves a lot of unnecessary data transmission, improve efficiency. This example is Certificateaction.java.
  
5, the establishment of the view component, this part by the JSP to act as, in order not to appear Java code, we use struts to provide a tag library, mainly responsible for removing the object from request just put in, by repeatedly calling Certificateaction and action parameters, and implement pagination display. This example is listcertificate.jsp.
  
6, establish and configure Struts-config.xml.
  
   Third, the instance code
  
After you have identified the development ideas above, the code can be implemented in a single way.
  
1, build the database and the corresponding table.
  
2, the data logic layer of the relevant code.
  
1), the common DAO Class: Commondao.java
  
This is a generic DAO class that a lot of DAO are going to inherit, and I've summed it up in terms of practice, and this shows only the code associated with this example in order to reduce space.
  
Java code:
  
Code:
--------------------------------------------------------------------------------
Package com.xindeco.business;
Import java.io.*;
Import java.sql.*;
Import java.util.*;
Import javax.sql.*;
Import java.lang.IllegalAccessException;
Import java.lang.reflect.InvocationTargetException;
Import Org.apache.commons.beanutils.BeanUtils;
public class DAO
{
protected DataSource ds;
/**
* Note: Get the total number of records of the current query
*/
public int getRows ()
{
return this.count;
}
public void Rshandler (ResultSet rs, int offset, int limit)
{
Try
{
Count = 0;
Rs.absolute (-1);
Count = Rs.getrow ();
if (offset <= 0)
{
Rs.beforefirst ();
}
Else
{
Rs.absolute (offset);
}
}
catch (Exception e)
{
E.printstacktrace ();
}
}
Public DAO (DataSource DS) {
This.ds = ds;
}
  
public void Setdatasource (DataSource ds) {
This.ds = ds;
}
  
protected void Close (ResultSet rs) {
if (Rs!= null) {
try {
Rs.close ();
catch (SQLException e) {
}
rs = null;
}
}
  
protected void Close (PreparedStatement pstmt) {
if (pstmt!= null) {
try {
Pstmt.close ();
catch (SQLException e) {
}
pstmt = null;
}
}
protected void Close (Connection conn) {
IF (conn!= null) {
try {
Conn.close ();
catch (SQLException e) {
E.printstacktrace ();
}
conn = null;
}
}
  
protected void rollback (Connection conn) {
IF (conn!= null) {
try {
Conn.rollback ();
catch (SQLException e) {
E.printstacktrace ();
}
conn = null;
}
}
}
  
This class is mainly through the subclass of advanced result set, get the total number of records of the query, and the database connection for simple management.
  
2), access to the database: Certificatedao.java
  
Java code:
  
Code:
--------------------------------------------------------------------------------
Package com.xindeco.business;
  
Import java.io.*;
Import java.sql.*;
Import java.util.*;
Import javax.sql.*;
  
Import Com.xindeco.common.dbconn.DbConn;
  
public class Certificatedao extends DAO
{
  
Public Nationdao (DataSource DS) {
Super (DS);
}
  
Public List findcertificatelist (int offset,int limit) throws SQLException
{
int countrows = 0;
ArrayList list = null;
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Try
{
conn = Ds.getconnection ();
String sql =
"Select Certificateid, Certificatecode,certificatename,photourl,"
+ "Description,graduateid from Tcertificate";
pstmt = conn.preparestatement (sql);
rs = Pstmt.executequery ();
/* Handles cursors, Rshandler method in parent DAO
This.rshandler (Rs,offset,limit);
if (Rs!= null && rs.next ())
{
List = new ArrayList ();
Todo
{
countrows++;
List.add (Rs2vo (RS));
}
while ((countrows++ < limit) && Rs.next ());
}
Close (RS);
Close (pstmt);
catch (SQLException e) {
Close (RS);
Close (pstmt);
ROLLBACK (conn);
E.printstacktrace ();
}
finally {
Close (conn);
}
return list;
}
  
Private Certificatevo Rs2vo (ResultSet rs)
{
Try
{
Certificatevo Certificatevo = new Certificatevo ();
Certificatevo.setcertificateid (Rs.getint ("Certificateid"));
Certificatevo.setcertificatecode (rs.getstring ("Certificatecode"));
Certificatevo.setcertificatename (rs.getstring ("Certificatename"));
Certificatevo.setphotourl (rs.getstring ("Photourl"));
Certificatevo.setdescription (rs.getstring ("description"));
Certificatevo.setgraduateid (Rs.getint ("Graduateid"));
return Certificatevo;
}
catch (Exception ex)
{
Ex.printstacktrace ();
return null;
}
}
}
  
findcertificatelist (int offset,int limit) is all the data to be displayed and put into the ArrayList. Have seen some examples on the internet, the data records into the ArrayList of the action process directly in the loop body to complete, if the word Gedo, will cause a way too pet big, and not beautiful. Here, the data records into the ArrayList action process by the Rs2vo method completes, is more neat. In addition, if (RS!= null && rs.next ()) in conjunction with while ((countrows++ < limit) && Rs.next ()) is considered for the robustness of the program, a little analysis is not difficult to conclude the knot On.
  
3, the establishment of controller components: Certificateaction.java
  
Java code:
  
Code:
--------------------------------------------------------------------------------
Package com.xindeco.presentation;
  
Import javax.sql.*;
Import java.util.*;
  
Import javax.servlet.http.*;
Import javax.servlet.*;
  
Import org.apache.struts.action.*;
Import org.apache.struts.util.*;
  
Import Com.xindeco.common.Pager;
Import Com.xindeco.business.graduatedata.CertificateDAO;
  
public class Certificateaction
Extends Action
{
private static final int page_length = 5; Display 5 records per page
Public Actionforward Execute (actionmapping mapping, Actionform form,
HttpServletRequest request,
HttpServletResponse response)
{
Actionforward myforward = null;
String myaction = Mapping.getparameter ();
  
if (iscancelled (Request))
{
Return Mapping.findforward ("failure");
}
if ("". Equalsignorecase (Myaction))
{
Myforward = Mapping.findforward ("failure");
}
else if ("LIST". Equalsignorecase (Myaction))
{
Myforward = performlist (mapping, form, request, response);
}
Else
{
Myforward = Mapping.findforward ("failure");
}
return myforward;
}
  
Private Actionforward performlist (actionmapping mapping,
Actionform Actionform,
HttpServletRequest request,
HttpServletResponse response)
{
Try
{
DataSource ds = (DataSource) servlet.getservletcontext (). getattribute (Action.data_source_key);
  
Certificatedao Certificatedao = new Certificatedao (DS);
  
int offset = 0; Cursor where the start record is when the page is leafed
int length = Page_length;
String Pageoffset = Request.getparameter ("Pager.offset");
if (Pageoffset = null | | pageoffset.equals ("")) {
offset = 0;
} else {
offset = Integer.parseint (pageoffset);
}
List certificatelist = Certificatedao. Findcertificatelist (Offset,length);
int size = Certificatedao.getrows (); Total number of records obtained
String URL = request.getcontextpath () + "/" +mapping.getpath () + ". Do";
String Pagerheader = pager.generate (offset, size, length, url); Page-handling
  
Request.setattribute ("Pager", Pagerheader);
Request.setattribute ("list", certificatelist);
}
catch (Exception e)
{
E.printstacktrace ();
Return Mapping.findforward ("error");
}
Return Mapping.findforward ("Success");
}
}
  
Certificateaction.java mainly takes the data out of the DAO, and puts it into a ArrayList, and then through the configuration file the JSP page of the software view.
  
5, the Establishment view listcertificate.jsp file.
  
JSP Code:
  
Code:
--------------------------------------------------------------------------------
  
<%@ page contenttype= "text/html; CHARSET=GBK "%>
<%@ taglib uri= "/web-inf/struts-template.tld" prefix= "template"%>
<%@ taglib uri= "/web-inf/struts-html.tld" prefix= "html"%>
<%@ taglib uri= "/web-inf/struts-bean.tld" prefix= "Bean"%>
<%@ taglib uri= "/web-inf/struts-logic.tld" prefix= "logic"%>
  
<table bgcolor= "#666666" cellpadding= "1" cellspacing= "0" border= "0" width= ">"
<tr>
<td>
<table cellpadding= "0" cellspacing= "0" border= "0" width= ">"
<tr>
&LT;TD bgcolor= "#fecc51" >&</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table cellpadding= "0" cellspacing= "0" border= "0" width= ">"
<tr>
&LT;TD bgcolor= "#d6e0ed" >
&&<bean:message key= "Label.list4certificate"/>
</td>
</tr>
<tr bgcolor= "#FFFFFF" >
&LT;TD width= "5%" ></td><td width= "19%" ></td><td width= "76%" ></td>
</tr>
<tr>
<td>
<table bgcolor= "#f2f2f2" width= "cellspacing=" 0 "border=" 0 ">
<tr bgcolor= "#bacce1" >
<td><b><bean:message key= "Certificate.select"/> </b></td>
<td><b><bean:message key= "Certificate.certificateid"/> </b></td>
<td><b><bean:message key= "Certificate.certificatecode"/></b></td>
<td><b><bean:message key= "Certificate.certificatename"/></b></td>
<td><b><bean:message key= "Certificate.view"/></b></td>
</tr>
  
<bean:write name= "Pager" property= "description"/>
<logic:equal name= "Pager" property= "hasprevious" value= "true" >
<a href= "/graduatedata/list.do?viewpage=<bean:write name=" pager "property=" PreviousPage "/>" class= "A02" >
Previous
</a>
</logic:equal>
<logic:equal name= "Pager" property= "Hasnext" value= "true" >
<a href= "/graduatedata/list.do?viewpage=<bean:write name=" pager "property=" NextPage "/>" class= "A02" >
Next
</a>
</logic:equal>
  
<logic:notempty name= "list" scope= "Request" >
<logic:iterate id= "certificate" name= "list" type= "Com.xindeco.business.graduatedata.CertificateVO" scope= " Request ">
<tr bgcolor= "#FFFFFF" >
<td></td>
<td> <bean:write name= "certificate" property= "Certificateid" scope= "page"/></td>
<td> <bean:write name= "certificate" property= "Certificatecode" scope= "page"/></td>
<td> <bean:write name= "certificate" property= "Certificatename" scope= "page"/></td>
<td> <bean:write name= "certificate" property= "Photourl" scope= "page"/></td>
</tr>
</logic:iterate>
</logic:notEmpty>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
  
6, the corresponding configuration file struts-config.xml.
  
Java code:
  
Code:
--------------------------------------------------------------------------------
<?xml version= "1.0" encoding= "UTF-8"?>
<! DOCTYPE struts-config Public "-//apache Software foundation//dtd struts Configuration 1.1//en" "http:// Jakarta.apache.org/struts/dtds/struts-config_1_1.dtd ">
<struts-config>
<form-beans>
<form-bean name= "Certificateform" type= "Com.xindeco.presentation.graduatedata.Certificateform"/>
</form-beans>
<global-forwards>
<forward name= "error" path= "/error/error.jsp"/>
</global-forwards>
<action-mappings>
<action name= "Certificateform" parameter= "LIST" path= "/graduatedata/list" scope= "Request" type= " Com.xindeco.presentation.graduatedata.CertificateAction "validate=" True >
<forward name= "Success" path= "/graduatedata/listcertificate.jsp"/>
</action>
</action-mappings>
......
</struts-config>
  
7, the last of course is the most important paging code: Pager.java
  
Java code:
  
Code:
--------------------------------------------------------------------------------
Package Com.xindeco.common;
  
Import java.util.*;
public class Pager {
private static int max_page_index = 10; How many pages does the footer display
private static String HEADER = "Result page";
  
public static String Generate (int offset, int length, int size, String URL) {
if (length > size) {
String pref;
if (Url.indexof ("?") >-1) {
Pref = "&";
} else {
Pref = "?";
}
String Header = "<font face= ' Helvetica ' size= '-1 ' >" +header+ ":";
if (Offset > 0) {
Header + + "&<a href=\" "+url+pref+" pager.offset= "+ (offset-size) +" \ ">[<< prev]</a>\n";
}
int start;
int radius = max_page_index/2*size;
if (offset < radius) {
start = 0;
else if (offset < Length-radius) {
start = Offset-radius;
} else {
Start = (length/size-max_page_index) *size;
}
for (int i=start;i<length && i < start + max_page_index*size;i+=size) {
if (i = = offset) {
Header + + "<b>" + (i/size+1) + "</b>\n";
} else {
Header + + "&<a href=\" "+url+pref+" pager.offset= "+i+" \ ">" + (i/size+1) + "</a>\n";
}
}
if (offset < length-size) {
Header = = "&<a href=\" "+url+pref+" pager.offset= "+ (int) offset+ (int) size) +" \ ">[next >>]</a>\n ";
}
Header = = "</font>";
return header;
} else {
Return "";
}
}
}
  
The implementation of this part of the code is fairly straightforward, but it's enough to do what you need.

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.