The implementation of Java learning paging query

Source: Internet
Author: User

Paging is a common function in the system , as long as the query involves the search must be accompanied by pagination , before also learned about the content of pagination, such as the Beef brisket press release system, Most of the previous studies used false paging, this time learning java, using Oracle Database to achieve true paging.

First, let's take a look at the process of implementing this paged query:


first, the packaging paging information:

What we need to do first is to encapsulate a paging entity for pagination, which is convenient to return the query information, encapsulated as follows:

/** * Package Paging information * @author Youngjong * */public class Pagemodel<e> {//result set private list<e> list;//query record number private int to talrecords;//how many records per page private int pagesize;//first few pages private int pageno;public list<e> getList () {return List;} public void setlist (list<e> list) {this.list = list;} public int gettotalrecords () {return totalrecords;} public void settotalrecords (int totalrecords) {this.totalrecords = totalrecords;} public int getpagesize () {return pageSize;} public void setpagesize (int pageSize) {this.pagesize = pageSize;} public int Getpageno () {return pageno;} public void Setpageno (int pageno) {This.pageno = PageNo;} /** * Total pages * @return */public int gettotalpages () {return (totalrecords+pagesize-1)/pagesize;} /** * Get home * @return */public int Gettoppageno () {return 1;} /** * prev * @return */public int Getpreviouspageno () {if (pageno<=1) {return 1;} return pageNo-1;} /** * Next page * @return */public int Getnextpageno () {if (PageNo >= Getbottompageno ()) {return Getbottompageno ();} Return PageNo + 1;} /** * Get last * @return */public int Getbottompageno () {return gettotalpages ();}}


The point here is that this entity uses generics, and the data that is displayed with pagination is not all the same entity data, and for a better reuse of paged queries, the result set is defined as generics, which makes it easy to query for many information:

Second, page load display query data and paging display (Servlet):

A Servlet is called when the page loads , and the paged query is invoked through Servelt and the query results are returned to the page: let's see . The code implementation of the Servlet:

public class Searchitemservlet extends Abstractitemservlet {/** * overwrite servlet doget method */protected void Doget ( HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {//define the variable int pageno=0;//int that shows the first page pagesize=2;//reads the number of displayed data per page set from the configuration file int Pagesize=integer.parseint (This.getservletcontext (). Getinitparameter (" Page-size "));//Gets the JSP to pass over the display of the page string Pagenostring=req.getparameter (" PageNo ");//If blank, the first page if (pagenostring==null) {pageno=1;} Else{pageno=integer.parseint (pagenostring);} Obtain the query condition condition, the condition is empty then query all string Condation=req.getparameter ("Clientidorname");//Call paged Query method, return query data Pagemodel pagemodel= Itemmanager.finditemlist (PageNo, PageSize, condation);///Get paged entity Req.setattribute ("Pagemodel", Pagemodel) passed over the query page ;//The query data is displayed on the page req.getrequestdispatcher ("/basedata/item_maint.jsp"). Forward (req, resp);} @Overrideprotected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException { TODO auto-generated Method Stub//super.dopost (req, resp);d Oget (REQ,RESP);}} 


It is noteworthy that the number of data on each page of the problem, this part can be written in the code, or the number of display can be written in the configuration file, only need to read the configuration file, easy to configure:

where the configuration file can be written like this: Web-inf under the Web. XML Medium:

<context-param><param-name>page-size</param-name><param-value>3</param-value> </context-param>


this notation can be applied to all of the system's Servlet , every page that wants to read the number of pages displayed can be read.

Third,theDao Layer Realization Paging query:

Servlet the Query method is invoked through a Manager interface, similar to the three-layer B The function of the layer, because there is no complex logic, so the code here is very simple:

         /**
* Query item information, parameters are: page number, each page display data, query conditions */public pagemodel finditemlist (int pageno, int pageSize, String condation) {Connection con N=null;try{conn=dbutil.getconnection ();//Call the DAO layer for a paged query return itemdao.finditemlist (conn, PageNo, PageSize, condation) ;} Finally{dbutil.close (conn);}}


the focus of true paged queries is DAO layer implementation, let's look at the code:

        /**
 * Paging Query */public Pagemodel finditemlist (Connection conn,int pageno, int pageSize, String condation) {StringBuffer Sbsql=ne W StringBuffer (); Sbsql.append ("SELECT *"). Append ("From ("). Append ("Select I.*, RowNum rn from ("). Append ("Select A.item _no, A.item_name, A.spec, A.pattern, a.item_category_id, "). Append (" B.name as Item_category_name, a.item_unit_id, C.name as Item_unit_name, A.file_name "). Append (" From T_items A, t_data_dict B, t_data_dict C "). Append (" Where a.item_cate Gory_id=b.id and A.item_unit_id=c.id "); if (condation! = null &&!"). Equals (condation)) {Sbsql.append ("and (A.item_no like" + condation + "% ' or a.item_name like '" + condation + "% ')");} Sbsql.append ("ORDER by A.item_no"). Append (") I where rownum<=?"). Append (")"). Append ("where RN;?"); System.out.println ("sql=" + sbsql.tostring ());//usually take log component records, such as log4j, Level: Info,debug,error ... PreparedStatement pstmt = null; ResultSet rs = null; Pagemodel Pagemodel = null;try {//Assign a value to the query condition parameter pstmt = conn.preparestatement (Sbsql.tostring ());//Query the database for data that is listed in the Pstmt.setint (1, PageNo * pageSize);p Stmt.setint (2, (pageNo-1) * pageSize); int i= Pageno*pagesize;int j= (pageNo-1) * Pagesize;rs = Pstmt.executequery ();//Get Eligible information marriage list itemList = new ArrayList (); whil E (Rs.next ()) {Item item = new Item (); Item.setitemno (rs.getstring ("Item_no")); Item.setitemname (rs.getstring ("Item_ Name ") Item.setspec (rs.getstring (" spec ")); Item.setpattern (rs.getstring (" pattern "));// Construct Itemcategoryitemcategory IC = new Itemcategory (); Ic.setid (rs.getstring ("item_category_id")); Ic.setname ( Rs.getstring ("Item_category_name")); item.setitemcategory (IC);//construction Itemunititemunit IU = new Itemunit (); Iu.setid ( Rs.getstring ("item_unit_id")); Iu.setname (rs.getstring ("Item_unit_name")); Item.setitemunit (IU); item.setFileName (Rs.getstring ("file_name")); Itemlist.add (item);} Assigns a value to the paging entity Pagemodel = new Pagemodel ();p Agemodel.setpageno (PageNo);p agemodel.setpagesize (pageSize); Pagemodel.setlist (itemList);//acquisition of records by condition int totalrecords = gettotalrecords (conn, condation);p agemodel.settotalrecords (totalrecords);} catch (SQLException e) {e.printstacktrace ();//record to log file Errorthrow new ApplicationException ("Paged query Failed");} Finally {Dbutil.close (RS);D butil.close (pstmt);} return Pagemodel;}


In fact, it looks complicated, it's not complicated, it's easy to implement.

iv.jsp page display

backstage obtained the data, passed to the page, the page can be displayed on the page after receiving, in fact, the code to get the data can be done in a word: more Servlet the code is corresponding, because the Servlet we have used the SetAttribute , so JSP the code in is as follows:

Pagemodel pagemodel= (Pagemodel) request.getattribute ("Pagemodel");

Click to jump to the first page of the method as follows (other jumps similar not listed):

Jump to Home function Toppage () {window.self.location= "<%=basepath%>servlet/item/searchitemservlet?pageno=<%= Pagemodel.gettoppageno ()%>&clientidorname=<%=clientidorname%> ";}

This is a complete paged query process, many are packaged can be reused, just inDAOlayer of query statements need to write their own, but recently learned somenhiernate, aboutHibernateThe knowledge is also in the study, oneself must writeSQLthe problem of the statement can also be solved!


The implementation of Java learning paging query

Related Article

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.