JSP Universal Paging Framework _jsp programming

Source: Internet
Author: User
Tags prev xmlns

Write a common paging framework, so that if you want to implement the paging function in the project, only a few changes to the parameters can be achieved paging processing. It will save a lot of time by writing this.

I. Page-type

Now that we're paging, we need to consider building a generic paging class with the parameters that are typically:

Total Pages Totalpage

Total record number Totalrecord

Display number per page pageSize

Current Page pageindex

Collection List datas that hosts the current page data

Complete code: Page.java

Import java.util.List;
public class Pager<e> {
/**
* Total pages
*
/private int totalpages;
/**
* The total number of records * * *
private int totalrecords;
/**
* Display quantity per page * *
private int pageSize;
/**
* Current Page
*
/private int pageIndex;
/**
* Current Page data collection * *
private list<e> datas;
public void settotalpages (int totalpages) {
this.totalpages = totalpages;
}
public void settotalrecords (int totalrecords) {
this.totalrecords = totalrecords;
}
public void setpagesize (int pageSize) {
this.pagesize = pageSize;
}
public void Setpageindex (int pageIndex) {
this.pageindex = PageIndex;
}
public void Setdatas (list<e> datas) {
this.datas = datas;
}
public int gettotalpages () {return
totalpages;
}
public int gettotalrecords () {return
totalrecords;
}
public int getpagesize () {return
pageSize;
}
public int Getpageindex () {return
pageIndex;
}
Public list<e> Getdatas () {return
datas;
}
}

Two. User class

Here to query the user to do pagination as an example, so you need a user class

User number UserId

User name username

User Password Password

Registration Time RegDate

Complete code

Import Java.sql.Timestamp;
public class User {
private int userid;//User ID
private string username;//username
private string password;//password
Private Timestamp regdate;//registration time public
int GetUserID () {return
userId;
}
public void Setuserid (int userId) {
This.userid = userId;
}
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 Timestamp Getregdate () {return
regdate;
}
public void Setregdate (Timestamp regdate) {
this.regdate = regdate;
}
}

Three. Threadlocal extraction of common parameters

First of all, if you do not extract public parameters, such as Pagesize,pageindex, then our query method should look like this:

public void Getusers (String name,int pagesize,int pageIndex)

If we add the parameters later, no doubt the parameters here will change a lot, so we use threadlocal to extract pagesize and pageindex.

Write this class first.

public class Systemcontext {
//page size
private static threadlocal<integer> pageSize = new threadlocal<> ();
Current page
private static threadlocal<integer> PageIndex = new threadlocal<> ();
public static Integer GetPageSize () {return
pagesize.get ();
}
public static void Removepagesize () {
pagesize.remove ();
}
public static void SetPageSize (int _pagesize) {
pagesize.set (_pagesize);
}
Public Integer Getpageindex () {return
pageindex.get ();
}
public void Setpageindex (int _pageindex) {
pageindex.set (_pageindex);
}
public static void Removepageindex () {
pageindex.remove ();
}
}

For threadlocal, this variable will always exist in the thread, then we can send the request to the server to add parameters, the server to return the data when the parameter removal, one time, automatically can use the filter

Then the filter is as follows:

 import com.dao.SystemContext; import javax.servlet.*; import java.io.IOException; public class Systemfilter implements filter{int pageSize; int pageIndex = 1; @Override public void init (Filterconfig filt Erconfig) throws Servletexception {try {pageSize = Integer.parseint (Filterconfig.getinitparameter ("pageSize"));
catch (NumberFormatException e) {pageSize = 15;}} @Override public void Dofilter (ServletRequest servletrequest, Servletresponse servletresponse, Filterchain FilterChain ) throws IOException, Servletexception {try {pageIndex = Integer.parseint (Servletrequest.getparameter ("PageIndex"));
catch (NumberFormatException e) {//Do nothing, pageindex=1} try {//Start the request configuration parameter systemcontext.setpagesize (pageSize);
Systemcontext.setpageindex (PageIndex);
Filterchain.dofilter (Servletrequest,servletresponse);
}finally {///request to remove the parameter Systemcontext.removepageindex ();
Systemcontext.removepagesize (); @Override public void Destroy () {}} 

With a filter, naturally you have to configure the filter in Web.xml

<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns=
"Http://xmlns.jcp.org/xml/ns/javaee"
xmlns : xsi= "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemalocation= "Http://xmlns.jcp.org/xml/ns/javaee Http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd "
version=" 3.1 ">
<filter>
< Filter-name>systemfilter</filter-name>
<filter-class>com.filter.systemfilter</ Filter-class>
<!--configured with no page size-->
<init-param>
<param-name>pagesize</param-name >
<param-value>15</param-value>
</init-param>
</filter>
< filter-mapping>
<filter-name>SystemFilter</filter-name>
<!--here to configure pages that require paging-->
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
</web-app>

This benefit is self-evident, the structure is clear, the modification is convenient. Next is the paging code

Four. Pagination Code

The paging code should write an interface and implement the class, where the demo project is written together

Import Com.util.Pager;
Import Com.util.User;
Import java.sql.*;
Import java.util.ArrayList;
Import java.util.List; public class Userdao {private Connection conn = null; private ResultSet rs = null; private PreparedStatement PS = null; /public static void main (string[] args) {//Userdao DAO = new Userdao ();//DAO.
Getusers ("", 15, 1);
Dao.close ();
Public Userdao () {String drivername = "Com.mysql.jdbc.Driver";
String url = "Jdbc:mysql://localhost:3306/fenyedemo"; String user = "root";
String password = "123456"; try {class.forname (drivername); conn = Drivermanager.getconnection (Url,user,password);} catch (
ClassNotFoundException e) {System.out.println ("no driver Found"); E.printstacktrace ();} catch (SQLException e) {
SYSTEM.OUT.PRINTLN ("Get Connection Failed");
E.printstacktrace (); }/** * Specific paging implementation code * @param name Query condition * @return/Public Pager getusers (String name) {//Get paging parameter int pagesize = Systemconte
Xt.getpagesize ();
int pageIndex = Systemcontext.getpageindex (); Page-specific SQL statement String sql = "Select"* from user ";
String sqlcount = "SELECT count (*) from user"; if (Name!=null &&!name.trim (). Equals ("")) {sql = "where username like%" +name+ "%"; sqlcount = "Where username L
IKE% "+name+"%;
SQL + + "LIMIT?,?";
The collection that holds the current page list<user> datas = new arraylist<> ();
The collection that holds the current paging pager<user> pages = new pager<> ();
User usertemp = null;
try {PS = conn.preparestatement (SQL); if (pageindex<=0) pageindex=1;//Set Parameters Ps.setint (1, (pageIndex-1) *pagesize);
Ps.setint (2,pagesize);
rs = Ps.executequery ();
Loop out, add to Datas while (Rs.next ()) {usertemp = new User (); Usertemp.setuserid (rs.getstring ("id");
Usertemp.setusername (rs.getstring ("username"));
Usertemp.setpassword (rs.getstring ("password"));
Usertemp.setregdate (Rs.gettimestamp ("regdate"));
Datas.add (usertemp);
///finally set up the pages Pages.setpageindex (PageIndex);
Pages.setpagesize (pagesize);
PS = conn.preparestatement (sqlcount);
rs = Ps.executequery (); while (Rs.next ()) {Pages.settotalrecords (Rs.getint (1)); pages.settotalPages ((Rs.getint (1)-1)/pagesize+1);
} pages.setdatas (Datas);
catch (SQLException e) {System.out.println ("get Error"); E.printstacktrace ();} return pages; public void Close () {try {if (rs!=null) Rs.close (); rs = null; if (ps!=null) ps.close (); ps = null; if (conn!=null) con N.close ();
conn = null;
catch (SQLException e) {System.out.println ("Shutdown failed"); E.printstacktrace ();} }

Five. JSP test page

Normal page is to display data, this is very simple, the code is as follows

<%@ page import= "Com.dao.UserDAO"%> <%@ page import= "com.util.Pager"%> <%@ page import= "Com.util.User"% > <%@ page import= "java.util.Iterator"%> <%@ page contenttype= "Text/html;charset=utf-8" language= "java"%&
Gt
<% String condition = request.getparameter ("condition");
Userdao Userdao = new Userdao ();
pager<user> pages = null; if (Condition!=null &&!condition.trim (). Equals ("")) {pages = userdao.getusers (condition);}
else {pages = userdao.getusers (null);} userdao.close (); %>  

There are some effects now.

Six. JSP page Add control option

Add control options Use the paging framework Pager-taglib to better support versatility.

First, after the index.jsp page query static introduction of a new page, as the bottom control page

The use of the method is to download the appropriate jar, and then introduced to the project's Lib can be

<TR><TD colspan= "100%" >
<jsp:include page= "fenye.jsp" >
<jsp:param name= "Items" value= "<%=pages.gettotalrecords ()%>"/> <jsp:param name= "Maxpageitems" value= "
<%=pages.getpagesize" () %> "/>
<jsp:param name= maxindexpages value="/> "<jsp:param name=" params "value="
Condition "/>
</jsp:include>
</td></tr>

Let's start writing fenye.jsp.

<%@ page contenttype= "Text/html;charset=utf-8" language= "java" pageencoding= "Utf-8"%> <% int items = INTEGER.P
Arseint (Request.getparameter ("items"));
int maxpageitems = Integer.parseint (Request.getparameter ("Maxpageitems"));
int maxindexpages = Integer.parseint (Request.getparameter ("maxindexpages"));
String params = Request.getparameter ("params"); %> <%--introduces a paging framework--%> <% @taglib prefix= "PG" uri= "Http://jsptags.com/tags/navigation/pager"%> <%-- parameter is the total number of items per page display quantity below menu display number current page curpage--%> <pg:pager items= "<%=items%>" maxpageitems= "<%=maxpageitems% > "maxindexpages=" <%=maxIndexPages%> "export=" Curpage=pagenumber "> <pg:param name=" <%=params% > "/> <pg:first> <a href=" <%=pageUrl%> "> Home </a> </pg:first> <pg:prev> <a href= "<%=pageUrl%>" > previous page </a> </pg:prev> <pg:pages> <% if (curpage==pagenumber) {%> [ <%=pagenumber%&gt] <%} else {%> <a href= "<%=pageurl%> "><%=pagenumber%></a> <%}%> </pg:pages> <pg:next> <a href=" <%=pageurl%& gt; "
> Next </a> </pg:next> <pg:last> <a href= "<%=pageurl%>" > Last </a> </pg:last> </pg:pager>

Page design is basically the above framework, the emphasis is on parameter transfer, where the parameter transfer using static introduction, configure Jsp:param, and then fenye,jsp to remove.
Pager-taglib in which there is a label is "/>, this is for my query conditions passed over the parameters, if not passed, then the query click on the next page will also be wrong, there is a problem is the coding problem, pager-taglib the default code is GB2312, You can repackage the file, or configure urlencording= "Utf-8" in Tomcat's Server.xml file, which will be fine.

Seven. Summary

Such a framework, if other needs to implement pagination can be applied directly, establish the corresponding entity classes, write pagination code, directly apply Systemcontex.java and Systemfilter.java (remember to configure the corresponding filter file web.xml), You can use fenye.jsp directly in your JSP, which will save you a lot of trouble.

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.