The JSP page realizes the paging function __jsp

Source: Internet
Author: User
Tags class manager int size rowcount oracle database

See a lot of online paging function realization, some feel too messy, some really do not understand, may be their own knowledge is not enough.

According to their knowledge, packaging pagination method, in the interface to achieve, for everyone to refer to, there must be imperfect places, we have a lot of advice.

I believe the comrades who have read the previous articles should know that I usually encapsulate the method into a manager parent class, and then other management classes inherit, and then call the parent class's methods.

Because I put it in a small practice project, so take out for everyone to see the words may not be too complete, everyone forgive me.

Manager management abstract Class: Encapsulation of the subclass query, additions and deletions to the method, to obtain the number of pages (inside the access to connection connection is my previous connection pool, we can go to see, I will not repeat the hair)

The manager Class code is as follows:

Package com.jdbc.service;
Import Java.lang.reflect.Constructor;
Import java.lang.reflect.InvocationTargetException;
Import java.sql.Connection;
Import java.sql.PreparedStatement;
Import Java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;
Import java.util.ArrayList;
Import java.util.LinkedList;

Import java.util.List;
Import Com.jdbc.tool.DBHelper;

 Import Com.sun.corba.se.spi.orbutil.fsm.State;
	Abstract class Manager {public abstract Boolean insertinfo (Object entity);
	Public abstract Boolean deleteinfo (Object ID);
	Public abstract Boolean Updateinfo (Object entity);
	Public abstract Object Getallinfobyid (object ID);
	
	
	Public abstract List getallinfo (); /** * According to the number of rows that are passed in each page * @param tname the table name to be paginated * @param rowcount the number of rows per page * @return pages/int getpagesize (String tname
		, int rowcount) {Connection con=dbhelper.getconnection ();
		if (con==null) {return-1;
		} Statement St=null;
		ResultSet Rs=null;
			try {st=con.createstatement (); Rs=st.ExecuteQuery ("SELECT count (*) from" +tname);
			int size=-1;
				if (Rs.next ()) {size=rs.getint (1);
				if (size%rowcount==0) {return (size/rowcount);
			Return (Size/rowcount) +1;
		The catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace ();
		}finally{Dbhelper.closejdbc (rs, St, con);
	} return-1; /** * For the parent class encapsulates a subclass of a query based on object properties * @param tname table name * @param clname the column name to query * @param clvalue The value of the passed-in column name * @param cl In the specified entity class class file * @return Query result set encapsulated data (Entity class object collection) */List Getinfobyproperty (String tname,string[] clname,string[] Clval
		Ue,class cl) {String sql= "select * from" +tname+ "where 0=0";
		
		for (int i = 0; i < clname.length i++) {sql+= "and" +clname[i]+ "=?";}
		
		
	return this.getallinfo (SQL, Clvalue, CL);
	 /** * is used in the parent class encapsulation and deletion of the method, for subclass invocation. * @param sql additions and Deletions change statement * @param args condition value * @param cl is used to specify the entity class class file that is encapsulated in the collection * @return successfully return TRUE failure returns false */bool Ean UpdateDB (String sql,string[] args {//Get connection and Judge Connection Con=dbhelper.getconnection ();
		if (Con==null) {return false;
		//Get an operation instruction device and execute SQL (assignable) PreparedStatement ps=null;
			try {ps=con.preparestatement (SQL);
				if (args!=null&&args.length>0) {for (int i = 0; i < args.length i++) {ps.setstring (i+1, args[i]); } return Ps.executeupdate () >0?
		True:false;
		catch (SQLException e) {//TODO auto-generated catch block E.printstacktrace ();
		}finally{DBHELPER.CLOSEJDBC (NULL, PS, con);
	return false;
	 /** * Method used by the parent class to encapsulate the query for subclass invocation. * @param SQL query statement (SELECT ...).  * @param args Query criteria value (can be null--basic query) * @param cl is used to specify the entity class class file that is encapsulated in the collection @return query result set encapsulated data (Entity class object Set)/List
		Getallinfo (String sql,string[] Args,class cl) {//Get connection and Judge Connection Con=dbhelper.getconnection ();
		Connection con=db_helper.getinstance (). getconnection ();
		if (con==null) {return null;
		//Get an operation instruction device and execute SQL (assignable) PreparedStatement ps=null; ResultSet RS=null;
			try {ps=con.preparestatement (SQL);
				if (Args!=null) {for (int i = 0; i < args.length i++) {ps.setstring (i+1, args[i]);
			} rs=ps.executequery ();
			Gets the source data of RS, from which the number of columns of the action table int Colcount=rs.getmetadata () is obtained. getColumnCount ();
			
			An array of parameters used to prepare the constructor method, the length of which is the number of table columns object[] canshu=new object[colcount];
			Encapsulates the return value container List list=new ArrayList ();
			
			Iterates through the constructor of all the specified entity classes, using a parameter array to get the entity class object (such as success, the column value is encapsulated as an object property value) object Ob=null; Encapsulates the return value container while (Rs.next ()) {//encapsulates the data for a row of tables into a parameter array for (int i = 0; i < canshu.length; i++) {canshu[i]=r
					S.getobject (i+1);
				Can be used to view the Java data type//system.out.println (Canshu[i].getclass ()) corresponding to the Oracle database;
				}//Ob=getobject (cl, Canshu);
				If successful, the object with the attribute value will be encapsulated into the list set if (ob==null) {return null;
			//If successful, the object with the attribute value will be encapsulated into the list collection list.add (OB);
		Return to new ArrayList (list);
			catch (Exception e) {}finally{dbhelper.closejdbc (RS, ps, con); DBHELPER.CLOSEJDBC (RS, PS, NULL);
	return null;
	} List getallinfobyproprety (String sql,string[] Args,class cl) {return null; /** * Used to automatically encapsulate row data as a method of specifying class objects * @param cl is passed in the returned entity type * @param canshu array with parameter matching * @return entity type * * * Private O
		Bject GetObject (Class cl,object[] canshu) {constructor[] cons=cl.getconstructors ();
		Object Ob=null;
				for (int i = 0; i < cons.length i++) {try {ob=cons[i].newinstance (Canshu);
			return OB;
			catch (Exception e) {continue;
	} return null;
 }
	
}


Here I take the teacher management class to give an example to illustrate, we mainly look at my annotated pagination method on the line.

Second, the teacher management class inherits the manager management class, overrides the abstract method of the parent class, defines its own paging method, obtains the total number of page methods, and the code reads as follows:

Package com.jdbc.service;

Import java.util.List;
Import com.jdbc.entity.ClassInfoEntity;

Import com.jdbc.entity.TeacherEntity; public class Teacherservice extends manager{////per page number of incoming rows public int getpagesize (int rowcount) {return THIS.GETPA
	Gesize ("Sa.teacher", rowcount); ///Per Page view teacher Information public list<teacherentity> getallinfobypagesize (int pagesize,int rowcount) {String sql= ' select * From (SELECT * to Sa.teacher where Tid not in (select Tid from Sa.teacher where rownum<= (? -1) *? order B
		Y tid)) tid where rownum<=? ";
		String[] args=new string[]{pagesize+ "", rowcount+ "", rowcount+ ""};
	return this.getallinfo (SQL, args, teacherentity.class);
		@Override public boolean deleteinfo (Object id) {String sql= ' delete from Sa.teacher where tid=? ';
		String[] args=new string[]{id+ ""};
	return this.updatedb (SQL, args);
		@Override public List Getallinfo () {String sql= ' select * from Sa.teacher '; return this.getallinfo (SQL, NULL, TeacherEntity.class);
		@Override public teacherentity Getallinfobyid (Object id) {String sql= ' select * from Sa.teacher where tid=? ';
		String[] args=new string[]{id+ ""};
		List<teacherentity> list=this.getallinfo (sql, args, teacherentity.class); Return (List!=null&&list.size () >0)?
	List.get (0): null;
		@Override public boolean insertinfo (Object entity) {teacherentity t= (teacherentity) entity;
		String sql= "INSERT into sa.teacher values (?,?,?)";
		String[] Args=new String[]{t.gettid () + "", T.gettname (), t.gettage () + ""};
	return this.updatedb (SQL, args);
		@Override public boolean updateinfo (Object entity) {teacherentity t= (teacherentity) entity; String sql= "Update sa.teacher set tname=?,tage=?"
		where tid=? ";
		String[] Args=new string[]{t.gettname (), t.gettage () + "", T.gettid () + ""};
	return this.updatedb (SQL, args);
 }

}


Here's the key to the SQL statement:

SELECT * FROM (SELECT * from Sa.teacher where TID does not be in (select Tid from Sa.teacher where rownum<= (? -1) * ? Order by Tid)) Tid where rownum<=?

Maybe there's a little too clear. This statement is responsible for the implementation of the number of pages, the subquery more, we look carefully to understand.

Third, I finally through the written Schoolmanager to realize the operation of the business, specifically the call teacher Management class, student management class, class management methods. Here are only a list of the teacher's business practices:

People mainly look at my annotated pagination method on the line.

Package Com.jdbc.manager;
Import Java.math.BigDecimal;

Import java.util.List;
Import com.jdbc.entity.TeacherEntity;


Import Com.jdbc.service.TeacherService;
	
	
	public class Schoolmanager {private static Teacherservice teachermanager=new teacherservice (); /** * Add new Teacher information * @param entity add a teacher's entity * @return successfully returns TRUE, Failure returns false */public static Boolean Addnewteacherinfo (OBJ
	ECT entity) {return Teachermanager.insertinfo (entity);
	public static Boolean Delteacherinfobyid (Object ID) {return teachermanager.deleteinfo (ID);
	public static Boolean updteacherinfo (Object entity) {return Teachermanager.updateinfo (entity);
	public static teacherentity Getteacherinfobyid (Object ID) {return Teachermanager.getallinfobyid (ID);
	public static list<teacherentity> Getallteacherinfo () {return teachermanager.getallinfo (); //The display of the information by the number of pages that are passed in and each line displayed public static list<teacherentity> getallteacherinfobypagesize (int pagesize,int ROWCOUNT) {return Teachermanager. Getallinfobypagesize (pagesize, rowcount);
	The number of pages public static int getteacherpagesize (int rowcount) {return teachermanager.getpagesize (ROWCOUNT) is obtained according to the quantity displayed per line;
 }
}


Four, in the interface call Schoolmanager Business Management class to operate, the interface code is as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "Utf-8"%> <% @page import= " Com.jdbc.entity.StudentEntity "%> <% @page import=" Com.jdbc.manager.SchoolManager "%> <% @page import="
Com.jdbc.entity.UserInfoEntity "%> <% String Path = Request.getcontextpath ();
String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/"; %> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" > 
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.