Efficient and simple Struts paging method
Title A Efficient Simple Struts Paging Method (Original) Select Blog of 9CBS Bibiye's Blog Replacement Text A Efficient Simple Struts Paging Method (Original) Source
I saw a few Structs pagings on the Internet, I didn't feel very perfect, so according to my own experience, I wrote a relatively highly efficient and simple paging method. Because I have limited level, if you have any better ideas, welcome to enlighten me. First, the development environment My development environment is: JBuilder X WebLogic 8.1 Oracle 9i Windows 2003, if the friend's development environment is different. Second, the development of thinking is Struts, which naturally cannot be causing MVC, and the pagination display is also the case. 1. Establish a database and a corresponding table, the table of this example is Tcertificate. 2. Establish an appropriate model component, and you should query the table in the database. This part is implemented by the DAO data access layer, if some friends are not familiar with DAO, I can query the relevant information. This example is implemented by CertificateDao.java. 3. Creating the model components required for paging, serve as JavaBean, and separates with the CertificateDao. Many methods introduced online have the phenomenon of data and paging components, which is also the main difference between this method and other paging methods. 4, establish a controller component, which is implemented by the action in Struts. It is mainly responsible for instantiating CertificateDao, only takes the data record to be displayed, and stores the ArrayList object and then returns and put it in the Request. The paging sections are constructed separately according to the paging conditions, avoiding the case where the DAO is mixed. In some paging methods for online other paging methods, all queries are read out at once, and then constructs by paging related components. In this way, if the amount of data is large, it is easy to form a bottleneck. In this case, since all data is read out from one-time reading, just read the data records to be displayed in a page, which saves a lot of unnecessary data transmission and improves efficiency. This example is CertificateAction.java. 5. Create a view component, which is served by JSP. In order not to appear Java code, we use the label library provided by Struts, which is mainly responsible for taking out the object that just put into the request, and implements paging by repeatedly calling the CertificateAction and the Action parameters. display. This example is ListCertificate.jsp. 6, establish and configure Struts-config.xml. Third, the instance code determines the above development ideas, the implementation of the code can be followed. 1, build a database and corresponding table. 2, the relevant code of the data logic layer. 1), universal DAO class: CommonDao.java This is a common DAO class that is to be inherited by a lot of Dao.
Java code:
Package com.xindeco.business;
Import java.io. *;
Import java.sql. *;
Import java.util. *;
Import javax.sql. *;
Import java.lang.illegaCCssexception;
Import java.lang.reflect.InvocationTargeTexception;
Import org.apache.commons.beanutils.BeanUtils;
Public Class Dao
{
Protected DataSource DS;
/ **
* Description: Number of total records obtained by getting 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 advanced results set passed by the subclass, and the total number of records is obtained, and the database connection is simple management. 2) Visit the database: CertificateDao.java
Java 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, CERTIFICATECIDE, CERTIFICATENAME, PHOTOURL," "Description, GraduateId from Tcertificate"
PSTMT = conn.preparestatement (SQL);
RS = pstmt.executeQuery ();
/ * Treatment of the cursor, RSHandler method in the parent class DAO * /
THIS.RSHANDLER (RS, Offset, Limit);
IF (rs! = null && ney =xt ())
{
List = new arraylist ();
DO
{
Countrows ;
List.Add (RS2VO (RS));
}
While ((Countrows } 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.SetPhotOr (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 found all the data to be displayed and put it in ArrayList. I have seen some examples of online, putting data records in ArrayList's action process is done in the While cycle, if the field is more, it will cause the method to be too favored, and not beautiful. Here, the data record is put into the ARRAYLIST's action process is completed by the RS2VO method, which is more tidy. In addition, IF (RS! = Null && =xt ()) is in conjunction with While ((CountRows Java 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; // 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.forward ("failure"); } Else IF ("List" .Equalsignorecase (MyAction)) { MyForward = PerformList (Mapping, Form, Request, Response); } Else { myforward = mapping.forward ("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 CertificateAo = New CertificateDao (DS); INT offset = 0; // The starting record when page turning INT length = Page_Length; String PageOffset = Request.GetParameter ("Pager.offset"); IF (PageOffset == Null || PageOffset.Equals (")) { OFFSET = 0; } else { OFFSET = Integer.Parseint (PageOffset); } List certificatelist = ceertificatedao .findCertificateList (Offset, Length); INT size = certificatedao.getrows (); // acquired a total record number String Url = request.getContextPath () "/" mapping.getpath () ". do"; String PagerHeader = Pager.Generate (Offset, size, length, url); // paging processing Request.setttribute ("Pager", PagerHeader; Request.setttribute ("List", CertificateList); } Catch (Exception E) { E.PrintStackTrace (); Return mapping.findforward ("error"); } Return mapping.findforward ("Success"); } } CertificateAction.java mainly removes data from DAO and puts in an ArrayList and then re-software View's JSP page. 5. Create a view listcertificate.jsp file. Java 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"%> TR> TABLE> td> TR> && TR> TR> ? / TR> Previous logic: Equal> ? a href = "/ graduatedata / list.do? Viewpage = NEXT ? / a> logic: Equal> ? TD> td> ? TD> ? TD> ? TD> ? TD> TR> logic: Iterate> logic: NOTEMPTY> TABLE> td> TR> TABLE> td> TR> TABLE> 6. The corresponding configuration file struts-config.xml. Java code: XML Version = "1.0" encoding = "UTF-8"?> form-beans> action> action-mappings> ...... Struts-Config> 7. Finally, it is the most important paging code: Pager.java Java code: Package com.xindeco.common; Import java.util. *; Public class facue { Private static int max_page_index = 10; // How many pages are displayed Private static string header = "result page"; Public Static String Generate (int offset, int layth, int size, string url) { IF (Length> size) { String pref; IF (URL.INDEXOF ("?")> -1) { pref = "&"; } else { PREF = "?"; } String header = "" header ":"; IF (Offset> 0) { HEADER = "& [<< prev] a> / n"; } Int start; INT RADIUS = MAX_PAGE_INDEX / 2 * size; IF (Offset START = 0; } else if (offset START = OFFSET - RADIUS; } else { START = (length / size-max_page_index) * size; } For (int i = start; i IF (i == offset) { Header = "" (i / size 1) " b> / n";} else { Header = "& " (i / size 1) " / n "; } } IF (Offset Header = "& [Next >>] / n" ; } HEADER = " font>"; Return header; } else { ""; " } } } The implementation of this part of the code is quite simple, but it is enough to complete the required. Author Blog: http://blog.9cbs.net/bibiye/
& td>
td> td> td>