The principle and realization of paging technology Java+oracle code implementation Paging (II) _java

Source: Internet
Author: User
Tags rollback stringbuffer

Immediately after the article-pagination technology principle and implementation of the meaning and method of pagination (i), this article continues to analyze paging technology. The last chapter is about the simple principle and introduction of paging technology, this article in-depth analysis of the paging Technology Code implementation.
The last chapter describes the best implementation of pagination is paging in the database layer, and different databases have different paging implementation, such as Oracle is using three-tier SQL nesting implementation of paging, MySQL is implemented with the Limit keyword (mentioned above).
This article is based on Java+oracle, explaining the implementation of the code layer .
as we usually see in pagination, when pagination is returned not only includes the query result set (List), but also includes the total number of pages (Pagenum), the current page (PageNo) and so on information, so we encapsulate a query results Pagemodel class, the code is as follows:

Package Kane;
Import java.util.List;
 public class Pagemodel<e> {private list<e> List;
 private int pageno;
 private int pageSize;
 private int totalnum;

 private int totalpage;
 Public list<e> GetList () {return List;
 public void setlist (list<e> list) {this.list = list;
 public int Getpageno () {return pageno;
 The public void Setpageno (int pageno) {This.pageno = PageNo;
 public int getpagesize () {return pageSize;
 The public void setpagesize (int pageSize) {this.pagesize = pageSize;
 public int Gettotalnum () {return totalnum;
 The public void settotalnum (int totalnum) {this.totalnum = Totalnum; Settotalpage (Gettotalnum ()% pageSize) = = 0?
 (Gettotalnum ()/pageSize): (Gettotalnum ()/pageSize + 1));
 public int gettotalpage () {return totalpage;
 The public void settotalpage (int totalpage) {this.totalpage = Totalpage;
 //Get first page public int getfirstpage () {return 1; //Get last page public int getlastpage () {RETUrn Totalpage;
 //Get front page public int getprepage () {if (PageNo > 1) return pageNo-1;
 return 1;
 //Get the back page public int getbackpage () {if (PageNo < totalpage) return PageNo + 1;
 return totalpage;
 //Determine if the ' home ' and ' front page ' is available as public String ispreable () {if (PageNo = 1) return "disabled";
 Return "";
 //Determine whether the ' end ' and ' next page ' are available with public String isbackable () {if (PageNo = = totalpage) return "disabled";
 Return "";

 }
}

The generics are used in order to enable the paging class to be reused, such as encapsulating the user object when querying users, and encapsulating the flow of a single Flowcard class when querying the flow order in finance.
We query the user for example, the user selects the query condition, first invokes the servlet to obtain the query parameter, then requests the business logic layer to obtain the paging encapsulation result class. The business logic calls the DAO layer to get the result set, to obtain the number of records encapsulated in the Component page class. The final servlet sets the results to the JSP page display. The
first explains the servlet, and the code is as follows:

Package Kane;
Import java.io.*;

Import java.util.*;
Import Javax.servlet.ServletConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse; Import Kane.
UserInfo; Import Kane.
Userinfomanage; Import Kane.

Pagemodel;
 public class Userbasicsearchservlet extends HttpServlet {private static final long serialversionuid = 1L;

 private int pageSize = 0; @Override public void init (ServletConfig config) throws servletexception {pageSize = Integer.parseint (config.getinitpar
 Ameter ("PageSize")); @Override protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, Ioexceptio
 n {doPost (req, resp); @Override protected void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, Ioexcepti
 on {//1. Gets the page parameter and constructs the parameter object int pageno = Integer.parseint (Req.getparameter ("PageNo")); String sex = Req.getparameteR ("Gender");
 String home = Req.getparameter ("NewLocation");
 String colleage = Req.getparameter ("colleage");

 String comingyear = Req.getparameter ("Comingyear");
 UserInfo u = new UserInfo ();
 U.setsex (Sex);
 U.sethome (home);
 U.setcolleage (colleage);

 U.setcy (comingyear);
 2. Invoke the business logic to obtain the result set userinfomanage Userinfomanage = new Userinfomanage ();
 pagemodel<userinfo> pagination = Userinfomanage.userbasicsearch (U, PageNo, pageSize);

 List<userinfo> userlist = Pagination.getlist ();
 3. Package return result StringBuffer Resultxml = new StringBuffer ();
 try {resultxml.append ("<?xml version= ' 1.0 ' encoding= ' gb18030 '? >/n ')";
 Resultxml.append ("<root>/n"); for (iterator<userinfo> iterator = Userlist.iterator (); iterator. Hasnext ();)
 {UserInfo UserInfo = Iterator.next ();
 Resultxml.append ("<data>/n");
 Resultxml.append ("/t<id>" + userinfo.getid () + "</id>/n"); Resultxml.append ("/t<truename>" + userinfo.gettruename () + "</truename >/n");
 Resultxml.append ("/t<sex>" + userinfo.getsex () + "</sex>/n");
 Resultxml.append ("/t 

Where the user object code is as follows:

Package Kane;
Import Java.util.Date;
 public class UserInfo {private int id;
 Private String username;
 private String password;
 Private String Truename;
 Private String sex;
 Private Date birthday;
 Private String home;
 Private String colleage;

 Private String comingyear;
 public int getId () {return id;
 The public void setId (int id) {this.id = ID;
 Public String GetUserName () {return username;
 } public void Setusername (String username) {this.username = username;
 Public String GetPassword () {return password;
 } public void SetPassword (String password) {this.password = password;
 Public String Gettruename () {return truename;
 } public void Settruename (String truename) {this.truename = Truename;
 Public String Getsex () {return sex;
 } public void Setsex (String sex) {this.sex = sex;
 Public Date Getbirthday () {return birthday;
 The public void Setbirthday (Date birthday) {this.birthday = birthday; Public String Gethome () {REturn home;
 public void Sethome (String home) {this.home = home;
 Public String Getcolleage () {return colleage;
 } public void Setcolleage (String colleage) {this.colleage = colleage;
 Public String getcy () {return comingyear;
 public void Setcy (String cy) {this. comingyear= cy;
 }
}

The

is followed by the business Logic layer code as follows:

 package Kane; import java.sql.Connection; Import Kane.
dbutility; Import Kane.

Pagemodel;

 public class Userinfomanage {private Userinfodao Userinfodao = null;
 Public Userinfomanage () {Userinfodao = new Userinfodao ();  Public pagemodel<userinfo> Userbasicsearch (UserInfo u, int pageno, int pageSize) throws Exception {Connection
 connection = null;
 pagemodel<userinfo> pagination = new pagemodel<userinfo> ();
 try {connection = dbutility.getconnection ();
 Dbutility.setautocommit (connection, false);
 Pagination.setlist (Userinfodao.getuserlist (U, PageNo, pageSize));
 Pagination.setpageno (PageNo);
 Pagination.setpagesize (pageSize);
 Pagination.settotalnum (Userinfodao.gettotalnum (U));
 Dbutility.commit (connection);
 catch (Exception e) {dbutility.rollback (connection);
 E.printstacktrace ();
 throw new Exception ();
 finally {dbutility.closeconnection ();
 return pagination; }
}

Where dbutility is the connection encapsulation class for the database. The
is finally the DAO Layer code implementation with the following code:

Package Kane;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.util.ArrayList;

Import java.util.List; Import Kane.
UserInfo; Import Kane.

dbutility; public class Userinfodao {public list<userinfo> getuserlist (UserInfo UserInfo, int pageno, int pageSize) throws
 Exception {PreparedStatement pstmt = null;
 ResultSet rs = null;
 List<userinfo> userlist = null; try {String sql = ' select * from ' (select RowNum num,u.* from user_info where sex =? and home like ' "+ userinfo.gethome () +"% "+" ' and colleage like ' "+ userinfo.getcolleage () +"% "+" ' and coming Year like ' "+ userinfo.getcy () +"% "+" ' ORDER by id "u where rownum<=?)
 where num>=? ";
 userlist = new arraylist<userinfo> ();
 Connection conn = Dbutility.getconnection ();
 pstmt = conn.preparestatement (sql);
 Pstmt.setstring (1, Userinfo.getsex ());
 Pstmt.setint (2, PageNo * pageSize); Pstmt.setiNT (3, (pageNo-1) * pageSize + 1);
 rs = Pstmt.executequery ();
 while (Rs.next ()) {UserInfo user = new UserInfo ();
 User.setid (Rs.getint ("id"));
 User.settruename (rs.getstring ("Truename"));
 User.setsex (rs.getstring ("Sex"));
 User.sethome (rs.getstring ("Home"));
 Userlist.add (user);
 } catch (SQLException e) {e.printstacktrace ();
 throw new Exception (e);
 Finally {Dbutility.closeresultset (RS);
 Dbutility.closepreparedstatement (PSTMT);
 return userlist;
 public int Gettotalnum (UserInfo UserInfo) throws Exception {preparedstatement = null;
 ResultSet rs = null;
 int count = 0; try {String sql = "SELECT COUNT (*) from User_info where sex=?" and home like ' "+ userinfo.gethome () +"% "+" ' and colleage like ' "+ userinfo.getcolleage () +"% "+" ' and coming
 Year like ' "+ userinfo.getcy () +"% "+" "";
 Connection conn = Dbutility.getconnection ();
 pstmt = conn.preparestatement (sql);
 Pstmt.setstring (1, Userinfo.getsex ());
 rs = Pstmt.executequery (); if (RS.NExt ()) {count = Rs.getint (1);
 } catch (SQLException e) {e.printstacktrace ();
 throw new Exception (e);
 Finally {Dbutility.closeresultset (RS);
 Dbutility.closepreparedstatement (PSTMT);
 return count;
 }
}

The final thing is that the servlet returns the resulting results to the JSP page.
Note: where the dbutility code is the code that encapsulates the database connection operation, as follows:

Package Kane;
Import java.sql.Connection;
Import Java.sql.DriverManager;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;

Import java.sql.SQLException; 

 public class Dbutility {private static threadlocal<connection> ThreadLocal = new threadlocal<connection> ();
 public static Connection getconnection () {Connection conn = null;
 conn = Threadlocal.get ();
 if (conn = = null) {try {class.forname ("oracle.jdbc.driver.OracleDriver");
 conn = Drivermanager.getconnection ("Jdbc:oracle:thin: @localhost: 1521:oracle", "admin", "admin");
 Threadlocal.set (conn);
 catch (ClassNotFoundException e) {e.printstacktrace ();
 catch (SQLException e) {e.printstacktrace ();
 } return conn; }//Encapsulation settings Connection autocommit public static void Setautocommit (Connection conn, Boolean flag) {try {conn.setautocommit (fl
 AG);
 catch (SQLException e) {e.printstacktrace ();
 }//SET transaction commit public static void commit (Connection conn) {try {conn.commit (); catch (SqleXception e) {e.printstacktrace ();
 }//Package set Connection rollback public static void RollBack (Connection conn) {try {conn.rollback ();
 catch (SQLException e) {e.printstacktrace (); }//Encapsulation closes Connection, PreparedStatement, resultset functions public static void CloseConnection () {Connection conn = Threadl
 Ocal.get ();
 try {if (conn!= null) {conn.close ();
 conn = null;
 Threadlocal.remove ();
 } catch (SQLException e) {e.printstacktrace ();
 } public static void Closepreparedstatement (PreparedStatement pstmt) {try {if (pstmt!= null) {pstmt.close ();
 pstmt = null;
 } catch (SQLException e) {e.printstacktrace ();
 } public static void Closeresultset (ResultSet rs) {try {if (rs!= null) {rs.close ();
 rs = null;
 } catch (SQLException e) {e.printstacktrace ();

 }
 }
}

Threadlocal is used to ensure that transactions are consistent so that all database operations of the same thread use the same connection.
A simple code implementation is done.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.