Common JSP paging framework and jsp paging framework

Source: Internet
Author: User

Common JSP paging framework and jsp paging framework

Write a general paging framework, so that if you want to implement the paging function in the project, you only need to slightly modify the parameters to implement paging. This saves a lot of time.

I. Paging

Since paging is required, we need to consider creating a general paging class. The required parameters include:

Total number of pages totalPage

Total number of records totalRecord

PageSize per page

Current page pageIndex

List datas

Complete code: Page. java

Import java. util. list; public class Pager <E> {/*** total number of pages */private int totalPages;/*** total number of records */private int totalRecords; /*** Number of pages displayed per page */private int pageSize;/***** current page */private int pageIndex; /*** current page Data Set */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 ;}}

Ii. User

Here we take querying users for paging as an example, so we need a user class

UserId

Username

Password

Registration Time: regdate

Complete code

Import java. SQL. timestamp; public class User {private int userId; // User idprivate String username; // User name 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 ;}}

3. threadLocal extraction of public Parameters

First, if we do not extract public parameters, such as pagesize and pageindex, our query method should be like this:

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

If you add more parameters later, the parameters here will change much, 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 <> (); // 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, so we can add parameters when sending a request to the server, and remove parameters when the server returns data, filters can naturally be used.

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; @ Overridepublic void init (FilterConfig filterConfig) throws ServletException {try {pageSize = Integer. parseInt (filterConfig. getInitParameter ("pagesize");} catch (NumberFormatException e) {pageSize = 15 ;}@ Overridepublic void doFilter (ServletRequest servletRequest, incluservletresponse, FilterChain filterChain) throws IOException, servletException {try {pageIndex = Integer. parseInt (servletRequest. getParameter ("pageindex");} catch (NumberFormatException e) {// do nothing, pageindex = 1} try {// configure the parameter SystemContext when starting the request. setPageSize (pageSize); SystemContext. setPageIndex (pageIndex); filterChain. doFilter (servletRequest, servletResponse);} finally {// remove the SystemContext parameter when the request returns. removePageIndex (); SystemContext. removePageSize () ;}@overridepublic void destroy (){}}

If a filter is used, you must 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-name> SystemFilter </filter-name> <filter-class> com. filter. systemFilter </filter-class> <! -- Configure 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> <! -- Configure the page to be paged here --> <url-pattern>/index. jsp </url-pattern> </filter-mapping> </web-app>

This advantage is self-evident, with a clear structure and convenient modification. The next step is the paging code.

4. Paging code

The paging code should write an interface and implementation class. Here, 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. dr Iver "; 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 ("failed to get connection"); e. printStackTrace () ;}}/*** specific paging implementation code * @ param name query condition * @ return */publ Ic Pager GetUsers (String name) {// obtain the paging parameter int pagesize = SystemContext. getPageSize (); int pageIndex = SystemContext. getPageIndex (); // a paging 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 LIKE %" + name + "% ";} SQL + = "LIMIT ?,? "; // List of sets for storing the current page <User> datas = new ArrayList <> (); // Pager <User> pages = new Pager <> (); User userTemp = null; try {ps = conn. prepareStatement (SQL); if (pageIndex <= 0) pageIndex = 1; // set the parameter ps. setInt (1, (pageIndex-1) * pagesize); ps. setInt (2, pagesize); rs = ps.exe cuteQuery (); // cyclically retrieve and add it to datas while (rs. next () {userTemp = new User (); userTemp. setUserId (rs. getString ("id"); userTemp. setUsername (rs. getString ("use Rname "); userTemp. setPassword (rs. getString ("password"); userTemp. setRegdate (rs. getTimestamp ("regdate"); datas. add (userTemp);} // finally set pagespages. setPageIndex (pageIndex); pages. setPageSize (pagesize); ps = conn. prepareStatement (sqlCount); rs = ps.exe cuteQuery (); 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) conn. close (); conn = null;} catch (SQLException e) {System. out. println ("failed to close"); e. printStackTrace ();}}}

V. jsp test page

The common page displays data. 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 "%> <% 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 (); %> 

Now there are some results.

 

6. Add control options on the JSP page

The pager-taglib framework is used to add control options.

First, after querying the index. jsp page, a new page is introduced statically as the bottom control page.

The usage is to download the corresponding jar and introduce it to the lib of the project.

<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="10"/><jsp:param name="params" value="condition"/></jsp:include></td></tr>

Start writing fenye. jsp

<%@ Page contentType = "text/html; charset = UTF-8" language = "java" pageEncoding = "UTF-8" %> <% int items = Integer. parseInt (request. getParameter ("items"); int maxPageItems = Integer. parseInt (request. getParameter ("maxPageItems"); int maxIndexPages = Integer. parseInt (request. getParameter ("maxIndexPages"); String params = request. getParameter ("params"); %> <% -- Introduce paging framework -- %> <% @ taglib prefix = "pg" uri =" http://jsptags.com/tags/navigation/pager "%> <% -- The parameters are in sequence the total number of projects displayed per page. The number of menus displayed below the current page curPage -- %> <pg: pager items = "<% = items %>" maxPageItems = "<% = maxPageItems %>" maxIndexPages = "<% = maxIndexPages %>" export = "curPage = pageNumber"> <pg: param name = "<% = params %>"/> <pg: first> <a href = "<% = pageUrl %>"> homepage </a> </pg: first> <pg: prev> <a href = "<% = pageUrl %>"> previous page </a> </pg: prev> <pg: pages> <% if (curPage = pageNumber) {%> [<% = pageNumber %>] <%} else {%> <a href = "<% = pageUrl %>"> <% = pageNumber %> </ ><%}%> </pg: pages> <pg: next> <a href = "<% = pageUrl %>"> next page </a> </pg: next> <pg: last> <a href = "<% = pageUrl %>"> last page </a> </pg: last> </pg: pager>

The paging design is basically the above framework, with the focus on parameter transfer. Here, when the parameter transfer uses static introduction, configure jsp: param and then retrieve it in fenye and jsp.
One of the tags in pager-taglib is "/>. This is the parameter passed for my query conditions. If it is not passed, an error will occur when you click the next page for the query, another problem is the encoding. The default encoding of pager-taglib is GB2312. You can repackage the file and compile it on the tomcat server. configure urlEncording = "UTF-8" in the xml file.

VII. Summary

Such a framework can be directly applied if you need to implement paging, create an object class, write paging code, and directly apply Systemcontex. java and SystemFilter. java. xml to configure the corresponding filter file), and then use fenye directly in jsp. jsp, which saves a lot of trouble

Articles you may be interested in:
  • Pagination of JSP database operation data
  • Efficient jsp paging Query
  • A Practical JSP paging code
  • Paging code of jsp hibernate
  • A common jsp PageBean
  • Analysis on paging technology for jsp database reading
  • Sample Code displayed by JSP page
  • Implementation Code of jsp paging display
  • JSP custom pagination TAG

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.