JSP page technology implementation [turn]

xiaoxiao2021-03-05  32

Original link: http://www.javaresearch.org/article/showArticle.jsp? Column = 106 & thread = 8893

Title: JSP Pedroll Technology Realization Summary: Using Tools Tool Class Implement Universal Points Processing Author: Evan_Zhaoemail: Evan_ZHAO@hotmail.com Currently, the paging method is currently cacked in httpsession or state beans, when turning is cached Remove one page data display. This approach has two main disadvantages: First, the user may see that expired data; the second is that the first query traversal assembly takes a long time if the data volume is very large, and the cached data will take up a lot of memory. The efficiency is significantly dropped. Other common methods include querying a database each time, taken only one page data from the ResultSet (using rs.last (); rs.getrow () get the total number of recordings, use rs.absolute () to locate This page started record). This approach is similar to the JDBC implementation of some databases (such as Oracle). It is also necessary to traverse all records. The experiment proves that the speed is very slow when the number of records is very slow. As for the cache result set, the method of ResultSet is completely a wrong approach. Because the ResultSet is closed when Statement or Connection is closed, if you want to make the ResultSet effect, you will always take up a database connection. Therefore, the better paging approach should be data from the block size of the page size from the database every time you turn pages. Thus, although the database is queried each time, the number of records that queries is small, the network transmission data is not large, and if the connection pool can be used, it can be skipped by the most time consuming database connection process. There are various mature optimization techniques in the database to improve query speed, which is much more effective than making a cache in the application server. The line number of the query result in the Oracle database uses a pseudo column ROWNUM (starting from 1). For example, Select * from Employee Where Rownum <10 Returns the top 10 records. However, because rownum is assigned before the query is sorted, Query Employee Press BirthDay Sort by BirthDay Sort by BirthDay, you should write: [pre] select * from (SELECT MY_TABLE. *, ROWNUM AS MY_ROWNUM FROM (SELECT NAME, BIRTHDAY from employee order by birthday) my_table where rownum <120) where my_rownum> = 100 [/ pre] mySQL LIMIT clause may be used: select name, birthday from employee order by birthday LIMIT 99,20 DB2 has RowNumber () function is used to obtain The number of current rows. SQL Server has not studied, you can refer to this article: http://www.9cbs.net/develop/Article/18/18627.SHTM Subsidist in the web program will be frequently used, but the implementation details of the paging are programming processes What is more troublesome in trouble. Most pags displayed query operations need to handle complex multiple query conditions, SQL statements require dynamic splicing composed, plus paging required record positioning, total records of records, traversal, package, and display, program meeting Becomes complicated and difficult to understand. Therefore, some tool classes simplify the paging code, so that the programmer focuses on the business logic. Below is the two tools I have designed: PageDStatement encapsulates the database connection, the total record number query, the page query, the result data package, and the shutdown database connection, and use PreparedStateMent supports dynamic setting parameters.

ROWSETPAGE Reference Page By Page Iterator Mode for PetStore, Design RowSetPage for Packaging Query Results (one page with OracleCachedRowSet Cache queries, please refer to the JSP page query display common mode for the use of the CachedRowSet package database query) The number of strips, current record number, etc., and can generate a simple HTML paging code. The result of the PageDStatement query is encapsulated into rowsetpage. Here is a simple example:

// DAO data query part of the code: ... public RowSetPage getEmployee (String gender, int pageNo) throws Exception {String sql =; // use paging query Oracle database "select emp_id, emp_code, user_name, real_name from employee where gender =?" Implementation, 5 PageDStatement PST = New PageDStatementOracleImpl (SQL, PAGENO, 5); PST.STSTRING (1, GENDER); Return Pst.executeQuery ();} // servlet Processing Query Request section code: ... int Pageno; Try {// You can get user-selected page number Pageno = Integer.PARSEINT (Request.getParameter ("Pageno"));} Catch (Exception EX) {// The default is the first page Pageno = 1;} String Gender = Request.getParameter ("gender"); request.setttribute ("EMPPAGE", MyBean.geTemPloyee (GENDER, PAGENO)); ... // JSP Display Some Code <% @ Page Import = "Page.RowSetPage"%> ... < Script language = "javascript"> Function doQuery () {form1.actionType.Value = "doquery"; Form1.Submit ();} ...

Gender: > <% RowSetPage empPage = (RowSetPage) request.getAttribute ( "empPage"); if (empPage == null) empPage = RowSetPage.EMPTY_PAGE;%> ... <% // Displays the total number of pages and the current page number (Pageno) and paging code. // This DOQUERY is submitted to the JavaScript function name submitted by the query action, and Pageno is the parameter name%>
ID code

User Name Name <% javax.sql.rowset Emprs = (javax.sql.rowset) EMPPPAGE.GETROWSET (); if (EMPRS! = NULL) While (EMPRS.NEXT ()) {%>
<% = EMPRS.GETSTRING ("EMP_ID")%> <% = EMPRS.GETSTRING ("EMP_CODE")%> <% = EMPRS.GETSTRING ("User_name")%> <% = EMPRS.GETSTRING ("Real_name")%> <% } // end while%>
<% = EMPPAGE .GETHTML ("DOQUERY", "DOQUERY", "DOQUERY", "DOQUERY", "Pageno")%> <% = EMPPAGE .GETHTML / td> effect is shown in Figure:

Because paging display is generally accompanied by query conditions and query action, the page should already have the Query Condition and the JavaScript method submitted in the query (as DOQUERY above), so the paging code generated by RowSetPage.gethtml () When the user selects a new page number Directly call up the JavaScript method for the procedure submitted in front. Note that the last query condition needs to be kept at the time of displaying the query results, such as >. At the same time, due to the parameter name of the page, there is therefore also supports multiple paging areas in the same page.

Another paging code implementation is the URL of each page, and the query parameters and page numbers are attached to the URL behind the querystring. The defect of this method is difficult to process when the query condition is complicated, and the servlet that needs to be specified to process the query action may not be suitable for some custom query operations.

If the default paging code generated by RowSetPage.GethTML () can write your own paging processing code, RowSetPage provides a lot of getter methods to obtain relevant information (such as current page numbers, total number of pages, total record number and current record number, etc.) ).

In practical applications, the paging query and display can be made into JSP Taglib, further simplify the JSP code, and mask Java Code.

Attachment: Source code for paging tool classes, annotations should be easily understood.

1.Page.java

2.RowSetPage.java (RowSetPage inherits Page)

3.PagedStatement.java

4.PageDStatementOracleImpl.java (PageDStateMenterAcleiMPL Inherit PageDState) You can use these source code, but must retain the AUTHOR EVAN_ZHAO@hotmail.com word

// // // a p: evan_zhao@hotmail.com ////wwage page; import java.util.list; import java.util.rraylist; import java.util.collection; import java .util.collections; / ** * Title: Paging object
* Description: Objects used to include data and page information
* Page class implements basic methods for displaying paging information, but not specified The type of data, * Subcounds can be organized according to a specific manner,
* If RowSetPage is encapsulated in RowSet, list Package data
* Copyright: CopyRight (C) 2002
* @ author evan_zhao@hotmail.com
* @version 1.0 * / public class Page implements java.io.Serializable {public static final Page EMPTY_PAGE = new Page (); public static final int DEFAULT_PAGE_SIZE = 20; public static final int MAX_PAGE_SIZE = 9999; private int myPageSize = DEFAULT_PAGE_SIZE; private int start; private int avaCount, totalSize; private Object data; private int currentPageno; private int totalPageCount; / ** * default constructor, only the configuration of an empty page * / protected page () {this .init (0, 0, 0. Default_page _Size, new object ();} / ** * Paging data initial method, by subclass call * @Param Start This page data in the start position of the database * @Param AvaCount This page contains the number of data * @Param TotalSize Database * @Param PageSize This page Capacity * @Param Data This page contains data * / protected void Init (int Start, int avacount, int us) {this.avacount = Avacount This.mypagesize = pagesize; this.start = start; this.totalsize = Totalsize; this.data = data; //system.out.println ("Avacount:" avacount); //system.out.println (" Totalsize: " Totalsize);

IF (Avacount> Totalsize) {// throw new runtimeException ("The number of records is greater than the total number of people ?!");} this.currentpageno = (start -1) / pagesize 1; this.totalPageCount = (Totalsize Pagesize 1) / PageSize; if (Totalsize == 0 && avacount == 0) {this.currentpageno = 1; this.totalPageCount = 1;} //system.out.println ("start index to page no: " Start "-" currentpageno;} public object getdata () {return this.data;} / ** * Take this page data capacity (number of records that can be included in this page) * @return This page can contain records * / Public int getpageSize ()} / ** * Is there a next page * @return has next page * / public boolean HasnextPage () {/ * if (Avacount == 0 && totalsize == 0 ) {RETURN FALSE;} Return (start avacount -1) 1);} / ** * Get the current page 1 data in the database * @return * / public int GetStart () {RETURN START;} / ** * Get the position of the current page last data in the database * @Return * / public int get () {int end = this.getStart () this.getsize () -1; IF (End <0) {end = 0;} return end;} / ** * Get the first page of the first data in the database * @

Return Record Corresponding Rownum * / Public INT getStartofpReviouspage () {Return Math.max (Start-mypagesize, 1);} / ** * Get Next Page 1 Data in the database * @return records the corresponding ROWNUM * / Public int GETSTARTOFNEXTPAGE () {Return START AVAUNT;} / ** * Gets the location of the first data in the database, using the default value * @Param Pageno Page number * @return record Rownum * / public static int GETSTARTOFANYPAGE (INT PAGENO) {Return getStartofanyPage (Pageno, default_page_size);} / ** * Gets the first data in the database * @Param Pageno page number * @Param PageSize The page contains the number of records * @return records the corresponding rownum * / public static int GetStartofanyPage (Int Pageno, INT PageSize) {Int StartIndex = (Pageno-1) * Pagesize 1; IF (StartIndex <1) StartIndex = 1; / /System.out.println (" Pageno " - " StartIndex); Return StartIndex;} / ** * Take the number of records included in this page * @return This page contains the number of records * * / Public int getSize () {Return AVA Count;} / ** * Take the total number of records contained in the database * @RETURN database * / public int gettotalsize () {return this.totalsize;} / ** * Take the current page * @return Currently page * / public int getCurrentPageNo () {return this.currentPageno;} / ** * * @return taken total page total page * / public int getTotalPageCount () {return this.totalPageCount;} / ** * * @param queryJSFunctionName implemented Page JS script name, page number is automatically turned back to call this method * @PARAM PAGENOPARAMNAME page number parameter name * @

return * / public String getHTML (String queryJSFunctionName, String pageNoParamName) {if (getTotalPageCount () <1) {return "";} if (. queryJSFunctionName == null || queryJSFunctionName.trim () length () <1) {queryJSFunctionName = "gotoPage";} if (pageNoParamName == null || pageNoParamName.trim () length () <1.) {pageNoParamName = "pageno";} string gotopage = "_" queryjsfunctionName; stringbuffer html = new stringbuffer ("/ n"); html.append ("