JSP based on bootstrap pagination display instance parsing _javascript skills

Source: Internet
Author: User
Tags getdate prev stmt

First of all introduce a simple and neat page of the Bootstrap-paginator: bootstrap, you can refer to: Paginator pagination plug-in use method to explain this article to learn.
Screenshot of Effect:

GitHub official Download Address: Https://github.com/lyonlai/bootstrap-paginator
Here is a detailed introduction to the page based on this tool JSP pagination display implementation process (note: Compared to the original page I have a lot of unnecessary content, this example only focus on the implementation of pagination display)

Why do I need a paging display?
This blog post is very thorough: the meaning and method of pagination technology principle and realization (I.)

second, JSP page part , here directly in the JSP page with JDBC Connection SqlServer2005 database query data (the actual implementation does not recommend the complex business logic encapsulated in the JSP page, JSP page should only be responsible for display; response to the client, Business logic calls, result forwarding should be done by the servlet.
The code is as follows:

<%@ page import= "paginationexample.*"%> <%@ page import= "java.util.*"%> <%@ page import= "java.sql.*"%&

Gt <%@ page language= "java" contenttype= "text/html;
 Charset=utf-8 "pageencoding=" UTF-8 "%> <%! private static final int pageSize = 20; Set the number of record bars per page (currently displaying 20 records per page)%> <% request.setcharacterencoding ("UTF-8"); Set the content that the client submits to the servlet by UTF-8 encoding response.setcharacterencoding ("UTF-8"); Set the content that the servlet passes back to the client by UTF-8 encoding Response.setcontenttype ("Text/html;charset=utf-8"); Tells the browser to parse the content in UTF-8 format String pagenostr = Request.getparameter ("Pagenostr"); To display the number of pages int pageno = 1 to be delivered by the receiving client; The number of pages to display int totalpages = 1; Total pages//check, set PageNo if (pagenostr!= null &&!pagenostr.equals ("")) {try {pageno = Integer.parseint (pagen
 
 OSTR);
 if (PageNo < 1) {//pageno is less than 1 o'clock the default display first page PageNo = 1;
 {numberformatexception e) {//Get PageNo (current number of pages) is illegal, the first page is displayed by default pageno = 1;
 } else {//other failed to get PageNo The first page is displayed by default pageno = 1; }
 
/* ======================================== Connection Database (Gets the total number of pages and the observation record to be displayed in the current page) ====================================== * *
 Gets the total number of pages in the database that will be recorded by the specified bar (pageSize)/Connection totalconn = null;
 Statement totalstmt = null;
 
 ResultSet Totalrs = null;
 
 try {totalconn = Dbutil.getconnection ();

 Generate SQL statement String sqlgettotalpages = "SELECT count (*) from alldata";
 Get the total record bar number totalstmt = Totalconn.createstatement ();
 Totalrs = Totalstmt.executequery (sqlgettotalpages);
 Totalrs.next ();
 
 int countresult = Totalrs.getint (1); Get total pages totalpages = countresult% PageSize = = 0? 
 
 Countresult/pagesize: (int) (countresult/pagesize) + 1;
 catch (SQLException e) {System.out.println ("History query error, operation not completed!");
 E.printstacktrace ();
 finally {dbutil.close (TOTALRS);
 Dbutil.close (TOTALSTMT);
 Dbutil.close (Totalconn);
 /* If the number of pages is greater than the total number of pages, the last page is displayed by default */if (PageNo > TotalPages) {pageno = TotalPages; 
 
 /* * Get the observation record to be displayed in the current page of the database, use a List to dress the record/list<record> records = new Arraylist<record> (); Connection Conn = null;
 PreparedStatement pstmt = null;
 
 ResultSet rs = null;
 int startIndex = (pageNo-1) * pageSize + 1;
 
 int endindex = PageNo * pageSize;
 
 try {conn = dbutil.getconnection (); String sql = "SELECT * from" (select Row_number () data_taizhan_num, data_date ASC) as ' num ', * from AllData)
 As temp where num between "+ StartIndex +" and "+ endindex;
 pstmt = conn.preparestatement (sql);
 rs = Pstmt.executequery ();
 while (Rs.next ()) {//Remove the data from each record and encapsulate it as a recordset R = new ();
 R.settaizhan_num (rs.getstring (2));
 R.setdate (Rs.gettimestamp (3));
 R.settem (Rs.getstring (4));
 R.sethum (Rs.getstring (5));
 R.SETPA (rs.getstring (6));
 R.setrain (rs.getstring (7));
 R.setwin_dir (rs.getstring (8));
 
 R.SETWIN_SP (rs.getstring (9)); Records.add (R);
 Put the encapsulated record object into the list container} catch (SQLException e) {System.out.println ("Query error, Operation incomplete!");
 E.printstacktrace ();
 Finally {Dbutil.close (RS);
 Dbutil.close (PSTMT);
 Dbutil.close (conn); } System.out.println (TotalpagES);
System.out.println (PageNo);

 /* ======================================== Database connection End ====================================== * *%>
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" > 
Package paginationexample;

Import java.sql.*; /** * Package Meteorological data Information * @author Zhong * */public class Record {private string taizhan_num;//station name private string tem;// temperature private String hum; Humidity Private String pa; Pressure private String rain; Rainfall private String win_dir; Wind direction private String win_sp; Wind speed private Timestamp date;
 Observation Date (original format)/** * Obtain the name of the station that produces the observation record; * @return Station name/public String Gettaizhan_num () {return taizhan_num; /** * Sets the name of the station that produces the observation record; * @param taizhan_num to set station name */public void Settaizhan_num (String taizhan_num) {This.taizh
 An_num = Taizhan_num;
 /** * get the temperature; * @return Temperature value/public String Gettem () {return TEM;
 /** * setting temperature; * @param tem to set temperature value/public void Settem (String tem) {this.tem = tem;
 /** * obtain humidity; * @return Humidity value/public String Gethum () {return hum;
 /** * Set humidity; * @param hum to be set humidity value * * public void Sethum (String hum) {this.hum = hum; /** * get pressure; * @return pressure value/public String getpa () {REturn PA;
 /** * Set pressure; * @param PA to set the pressure value * * public void SETPA (String pa) {THIS.PA = PA;
 /** * obtain rainfall; * @return Rain value/Public String Getrain () {return rain;
 /** * Set rainfall; * @param rain to set the rainfall value * * * public void Setrain (String rain) {this.rain = Rain;
 /** * Obtain wind direction, * @return Wind Direction value/public String Getwin_dir () {return win_dir;
 /** * Set wind direction; * @param win_dir to set wind direction value/public void Setwin_dir (String win_dir) {this.win_dir = Win_dir;
 /** * obtain wind speed; * @return wind speed value/public String getwin_sp () {return win_sp;
 /** * Set wind direction; * @param win_sp to set wind direction value/public void setwin_sp (String win_sp) {this.win_sp = win_sp;
 /** * Obtain observation date, * @return Observation Date/public Timestamp getDate () {return date;
 /** * Set observation date; * @param date value/public void setdate (Timestamp date) {this.date = date;

 }

 
}

Corresponding ALLDATA table part of the data screenshot:

Dbutil class is a database tool class, unified external provide database-related connection, statement, etc., the code is as follows:

Package paginationexample;

Import java.sql.*;
Import Org.apache.tomcat.jdbc.pool.DataSource;

Import org.apache.tomcat.jdbc.pool.PoolProperties;
 
 /** * Database Tools class (with tomcat JDBC Pool) * @author Zhong * * */public class Dbutil {private static DataSource ds;
 static {//configure Tomcat JDBC Pool (connection pool) Poolproperties p = new Poolproperties (); P.seturl ("jdbc:sqlserver://localhost:1433; Databasename=weather "); Sets the URL of the connection p.setdriverclassname ("Com.microsoft.sqlserver.jdbc.SQLServerDriver"); Load Database driver P.setusername ("sa"); User name P.setpassword ("2003NianDeDiYiChangXue") for remote connections;
 Password p.setjmxenabled (true);
 P.settestwhileidle (FALSE);
 P.settestonborrow (TRUE);
 P.setvalidationquery ("SELECT 1");
 P.settestonreturn (FALSE);
 P.setvalidationinterval (30000);
 P.settimebetweenevictionrunsmillis (30000);
 P.setmaxactive (100);
 P.setinitialsize (10);
 P.setmaxwait (10000);
 P.setremoveabandonedtimeout (60);
 P.setminevictableidletimemillis (30000);
 P.setminidle (10);
 P.setlogabandoned (TRUE); P.setremOveabandoned (TRUE); P.setjdbcinterceptors ("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;")
 + "Org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
 ds = new DataSource ();
 Ds.setpoolproperties (P); Private Dbutil () {}/** * gets a database connection (Connection); * @return Database Connection/public static Connection get
 
 Connection () {Connection conn = null;
 try {conn = ds.getconnection ();
 catch (SQLException e) {e.printstacktrace ();
 Return conn; /** * Closes the incoming Connection; * @param conn to be closed Connection/public static void Close (Connection conn) {try {if (CO)
 nn!= null) {conn.close ();
 conn = null;
 } catch (SQLException e) {e.printstacktrace (); /** * Closes incoming Statement * @param stmt Statement/public static void Close (Statement stmt) {try {if (STM) to be closed
 T!= null) {stmt.close ();
 stmt = null;
 } catch (SQLException e) {e.printstacktrace (); }/** * closes incoming resultset; * @param rs to be closed resultset/public STAtic void Close (ResultSet rs) {try {if (rs!= null) {rs.close ();
 rs = null;
 } catch (SQLException e) {e.printstacktrace ();

 }
 }
 
}

Iv. Additional notes:
①:sqlserver implementation of paging requires the use of the Row_number () function to generate a single record of the row number of columns, to facilitate the subsequent paging out the corresponding line number interval section of the record. Cases:

See, there's one more. Column with the field name num that stores the row number;
(If the primary key ID in the table is an automatically incremented number, you can also use the ID to segment the record directly, but only if the ID must be sequential and automatically incremented)
For more row_number () function implementation paging information please refer to: SQL Server implementation using Row_number paging

②:mysql paging to achieve a much simpler, direct use of limit keyword can be. Cases:
SELECT * FROM table1 the ORDER by ID ASC limit 3, 2 means to sort the data in table table1 by ID value (ascending), starting with the third row, followed by two rows (that is, line fourth to fifth)
③: The specific use of bootstrap-paginator can refer to the official documents (located in the extracted document folder), the official document is very good, easy to understand.
When used, be aware that for the bootstrap V3 version, use the <ul> tag to display the Bootstrap-paginator and indicate the bootstrap version in the configuration item (refer to my JSP sample page).
(Bootstrap V2 version directly uses the <div> tag in the sample document)
④: Pagination Common formula: set to display the number of pages n, each page to display m data, then (in the database) the starting position of data (that is, startindex in the JSP example) is: (n-1) *m+1, termination location (Endindex) is: n*m

If you want to further study, you can click here to learn, and then attach 3 wonderful topics:

Bootstrap Learning Course

Bootstrap Practical Course

Bootstrap Plugin Usage Tutorial

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.