"Web" pagination is simple to implement __ page pagination

Source: Internet
Author: User
Tags prev serialization

Web page Paging

 

Why paging is required.

I. Data-related causes

The data in a large number of queries is more time-consuming.

Second, enhance user experience needs

Users are more convenient to query and display the data he needs.

Common pagination: traditional pagination and drop-through-page mode.

The traditional way of paging, you can clear access to data information, such as how many data, how many pages display.

With a drop-down paging, it is not generally possible to get clear information about the amount of data, but after paging operations, you can still see the data that was previously queried.

Common ways to implement pagination

1. Use Sublist () to implement paging.

list<e> sublist (int fromindex,int toindex)

Returns a partial view of the Fromindex (included) and Toindex (not included) specified in the list.

2. Implementing paging Using SQL statements

Take advantage of the pagination syntax of the database, use the paging statement, get the paging data (for example, use the Limit keyword in the MySQL database, use the ROWNUM keyword in Oracle, etc.)

Mysql

-select * from students limit0,10, starting from No. 0, inquires 10 records altogether.

3. Use the Hibernate framework for paging.

Create a query or criteria object that, when queried, sets the Firstresult (starting from the first few) and Maxresults (querying several records) properties.

String hql = "from Student";

Query q = session.createquery (HQL);

Q.setfirstresult (0);

Q.setmaxresults (10);

List L = q.list ();

Implementation mode

Advantages

Disadvantages

Working with scenes

Sublist

Simple, Easy-to-use

Low efficiency

Unable to bulk get data on demand

SQL statement

Simple, direct, high efficiency

Poor database compatibility

Database compatibility not required

Hibernate framework

Object-oriented, strong compatibility

Low performance for complex queries

Compatible with different databases

1. Use sublist to implement paging.


Create the Model layer

Student object Student Class

public class Student implements serializable{
	
	/**
	 * 
	 *
	/private static final long Serialversionuid =- 2448260736229612919l;//serialization ID
	private int id;//student record ID
	private String stuname;//name
	private int age;//age
	private int gender;//sex
	private String address;//address public
	Student () {
		super ();
	}
	public Student (int ID, string stuname, int age, int gender, string address) {
		super ();
		This.id = ID;
		This.stuname = Stuname;
		This.age = age;
		This.gender = gender;
		this.address = address;
	/
	 * constructor, which constructs the data of the MAP type queried to the student object
	/Public Student (map<string,object> Map) {
		this.id = (int) Map.get ("id");
		This.stuname = (String) map.get ("Stu_name");
		This.age = (int) map.get ("Age");
		This.gender = (int) map.get ("Gender");
		This.address = (String) map.get ("Address");
	}

Paging Object Pager Class

public class Pager<t> implements serializable{/** * Serialization ID/private static final long Serialversionuid = 756
	9566861340703188L; private int pagesize;//How many records per page private int currentpage;//current page Data private int totalrecord;//Altogether how many records private list<t& Gt
	datalist;//to display the data private int totalpage;//total pages Public Pager () {super ();
		Public Pager (int pageSize, int currentpage, int totalrecord, int totalpage,list<t> dataList) {super ();
		This.pagesize = pageSize;
		This.currentpage = CurrentPage;
		This.totalrecord = Totalrecord;
		This.totalpage = Totalpage;
	This.datalist = dataList; Public Pager (int pagenum,int pagesize,list<t> sourceList) {if (Sourcelist.size () ==0 | |
		SourceList = = null) {return;
		///Total record bar number This.totalrecord = Sourcelist.size ();
		How many records are displayed per page this.pagesize = pageSize;
		Get total number of pages this.totalpage = this.totalrecord/this.pagesize;
		if (this.totalrecord% this.pagesize!= 0) {this.totalpage = This.totalpage +1; }//Current articleSeveral pages of data if (This.totalpage < pagenum) {this.currentpage = This.totalpage;
		}else{this.currentpage = pagenum;
		}//Starting index int fromindex = this.pagesize* (this.currentpage-1);
		End index int toindex;
		if (this.pagesize * this.currentpage >this.totalrecord) {toindex = This.totalrecord;
		}else{Toindex = this.pagesize * this.currentpage;
	} this.datalist = Sourcelist.sublist (Fromindex, Toindex);
 }
}
Database Tools Class Jdbcutil.java

public class Jdbcutil {//Represents the user name of the definition database private static String USERNAME;
	Defines the password for the database private static String PASSWORD;
	Define driver information for the database private static String DRIVER;
	Defines the address private static String URL that accesses the database;
	Defines a connection to a database private Connection Connection;
	Define the execution object of the SQL statement private PreparedStatement pstmt;
	Defines the result set returned by a query private ResultSet ResultSet;
	static{Loadconfig (); /** * Loads the database configuration file and assigns values to the associated attributes, which are written in the configuration file to facilitate management/public static void Loadconfig () {//path Web-inf\classes\jdbc.propert
		ies InputStream instream = JdbcUtil.class.getResourceAsStream ("/jdbc.properties");
		Properties prop = new properties ();
			try{prop.load (instream);
			USERNAME = Prop.getproperty ("Jdbc.username");
			PASSWORD = Prop.getproperty ("Jdbc.password");
			Driver= prop.getproperty ("Jdbc.driver");
		URL = Prop.getproperty ("Jdbc.url");
		}catch (Exception e) {throw new RuntimeException ("Error reading user profile", e); /** * Get database connection/public Connection getconnection () {try {class.forname (DRIVER);//Register Driver
			Gets the Connection object connection = Drivermanager.getconnection (Url,username,password);
		catch (ClassNotFoundException e) {e.printstacktrace ();
		catch (SQLException e) {e.printstacktrace ();
	return connection; /** * Perform UPDATE operation * SQL SQL statement * Params execution parameter * Return execution result/public boolean updatebypreparedstatement (String sq
		L,list<?> params) throws sqlexception{Boolean flag = false;
		int result = -1;//Indicates the number of rows of the database affected by the user performing add deletion and modification pstmt = connection.preparestatement (sql);
		int index = 1; Fill in SQL statement with placeholder if (params!= null &&!params.isempty ()) {for (int i=0;i < params.size (); i++) {Pstmt.seto
			Bject (index + +, params.get (i));
		result = Pstmt.executeupdate (); Flag = result >0?
		True:false;
	return flag; /** * Execute query operation * SQL SQL statement * Params execution parameter/public list<map<string, object>> Findresult (String sql,l Ist<?> params) throws sqlexception{list<map<string, object>> List = new arraylist<Map<string,object>> ();
		int index = 1;
		pstmt = connection.preparestatement (sql); * * * Fill Query statement parameters/if (params!= null &&!params.isempty ()) {for (int i = 0;i<params.size (); i++) {p
			Stmt.setobject (index + +, params.get (i));
		} ResultSet = Pstmt.executequery (); * * To obtain the type of a resultSet column and the property information about the column by ResultSetMetaData, such as column name, number of columns, and so on * * ResultSetMetaData metaData = Resultset.getmetadata (
		);
		Gets the number of columns int cols_len = Metadata.getcolumncount (); * * Traverse ResultSet/while (Resultset.next ()) {map<string,object> Map = new hashmap<string, object> ()
			;
				for (int i= 0;i<cols_len;i++) {//Get column name String cols_name = Metadata.getcolumnname (i+1);
				Gets the column value based on the column name Object cols_value = Resultset.getobject (cols_name);
				if (Cols_value = = null) {Cols_value = "";
			} map.put (Cols_name, Cols_value);
		} list.add (map);
	} return list; /** * FREE RESOURCES * */public void Releaseconn () {if (ResultSet!= null) {try {Resultset.close ();
			catch (SQLException e) {e.printstacktrace ();
			} if (pstmt!= null) {try {pstmt.close ();
			catch (SQLException e) {e.printstacktrace ();
			} if (connection!= null) {try {connection.close ();
			catch (SQLException e) {e.printstacktrace ();
 }
		}
	}
}
Database configuration file

Jdbc.username=root
Jdbc.password=limeng
jdbc.driver=com.mysql.jdbc.driver
jdbc.url=jdbc\:mysql\:// 127.0.0.1\:3306/pager

Create DAO layer, data manipulation object Interface Studentdao.java

Public interface Studentdao {
	/**
	 * Based on query criteria, query student paging information
	 * @param searchmodel Package Query conditions
	 * @param pagenum Query the first few data
	 * @param pageSize display how much data
	 *
	 @return
	/Public pager<student> findstudent (Student Searchmodel, int pagenum,int pageSize);
}
DAO layer Interface Implementation class Subliststudentdaoimpl.java

public class Subliststudentdaoimpl implements studentdao{@Override public pager<student> findstudent (Student Sea Rchmodel, int pagenum, int pageSize) {/* * get all data on condition * * list<student> allstudentlist = getallstudent (
		Searchmodel);
		* * Create a paging object based on the parameter * * pager<student> Pager = new pager<student> (pagenum,pagesize,allstudentlist);
	return pager; * * * get all data/private list<student> getallstudent (Student searchmodel) {list<student> result = new
		Arraylist<student> ();
		list<object> paramlist = new arraylist<object> ();
		String stuname = Searchmodel.getstuname ();
		int gender = Searchmodel.getgender ();
		StringBuilder sql = new StringBuilder ("SELECT * from T_student where 1=1");
			if (stuname!= null &&!stuname.equals ("")) {Sql.append ("and stu_name like?");
		Paramlist.add ("%" +stuname+ "%"); } if (gender = Constant.gender_female | | gender== constant.gender_male) {sql.append ("" and gender= ?");
		Paramlist.add (gender);
		} jdbcutil jdbcutil = null;
			try {jdbcutil = new jdbcutil ();
			Jdbcutil.getconnection ();
			list<map<string, object>> maplist = Jdbcutil.findresult (sql.tostring (), paramlist);
					if (maplist!= null) {for (map<string, object> map:maplist) {Student s = new Student (MAP);
				Result.add (s); The catch (SQLException e) {throw new RuntimeException ("Queries all data exceptions.
		", e);
			}finally{if (jdbcutil!= null) {jdbcutil.releaseconn ();
	} return result;
 }
}
Create service layer, call DAO layer

public class Subliststudentserviceimpl implements studentservice{
	
	private Studentdao Studentdao;
	When public Subliststudentserviceimpl () {
		//Create service implementation class, initialize DAO object
		Studentdao = new Subliststudentdaoimpl ();
	}
	@Override public
	pager<student> findstudent (Student searchmodel, int pagenum,
			int pageSize) {
		Pager <Student> result = Studentdao.findstudent (Searchmodel, Pagenum, pageSize);
		return result;
	}
	Public Studentdao Getstudentdao () {return
		Studentdao;
	}
	public void Setstudentdao (Studentdao studentdao) {
		This.studentdao = Studentdao;
	}
}
Create servlet, receive parameters, call service layer

public class Sublistservlet extends HttpServlet {//Create service object private Studentservice Studentservice = new Subliststude
	Ntserviceimpl ();
	Public Sublistservlet () {super ();  public void Destroy () {Super.destroy ()//Just puts ' destroy ' string in Log/' Put your code here} ' public void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doPost (reques
	T, response);
		public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
		* * Set the encoding format to prevent the parsing of Chinese parameters garbled * * * request.setcharacterencoding ("Utf-8");
		/* Receive request parameter * Student name */String Stuname = Request.getparameter ("Stuname");
		* * Sex, the default is 0, means all, regardless of men and women/int gender = Constant.default_gender;
		String genderstr = Request.getparameter ("gender"); if (genderstr!= null &&! "". Equals (Genderstr.trim ())) {gender = Integer.parseint (GENDERSTR);//Get Student Gender} * * * current request page/int PagenUm = Constant.default_pagenum;
		String pagenumstr = Request.getparameter ("Pagenum"); Parameter checksum, is the number if (Pagenumstr!= null &&!)
			Stringutil.isnum (PAGENUMSTR)) {Request.setattribute ("errormsg", "parameter input error");
			Request.getrequestdispatcher ("subliststudent.jsp"). Forward (request, response);
		Return } if (pagenumstr!= null &&! "". Equals (Pagenumstr.trim ())) {pagenum = Integer.parseint (PAGENUMSTR);//Get current request page}/* * How many data per page */int page
		Size = constant.default_page_size;
		String pagesizestr = Request.getparameter ("PageSize"); if (pagesizestr!= null &&! "". Equals (Pagesizestr.trim ())) {pageSize = Integer.parseint (PAGESIZESTR);//How many records are displayed per page}//Assemble query conditions Student searchmode
		L = new Student ();
		Searchmodel.setstuname (Stuname);
		Searchmodel.setgender (gender);
		Invoke Service Query Results pager<student> result = Studentservice.findstudent (Searchmodel, Pagenum, pageSize);
		Returns the results to the page request.setattribute (result); Request.gEtrequestdispatcher ("subliststudent.jsp"). Forward (request, response);
 }
}
JSP page

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > <% @taglib Prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%> <% @taglib prefix= "FN" uri= "Http://java.sun.com/jsp/jstl" /functions "%>  









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.