Jsp + servlet + javabean complete example of implementing the data paging method, servletjavabean

Source: Internet
Author: User
Tags xml attribute

Jsp + servlet + javabean complete example of implementing the data paging method, servletjavabean

This example describes how to implement data paging Using jsp + servlet + javabean. We will share this with you for your reference. The details are as follows:

Here, we keep a line of mind to record the learning process and learn quickly and forget it for future use.
Some of the code used is to search and modify it on the Internet, and add your own understanding. I do not know if it is not original. I only keep my learning records.

Usage: PostgreSQL database, dom4j, JSP, Servlet

I. The first is the engineering pattern. A global view is provided to help readers view and use it on their own.

The idea is:

The configuration information is recorded in the config. xml file to facilitate database changes and facilitate migration and reuse.
DOM4JUtil. java is used to parse xml Attribute files to obtain required data
PostgreSQL_Util.java data integration and Database Operations
PageProperties. java is the table paging attribute javaBean
PageProperties. java encapsulate paging operations
Page. java is the main Page operation.
TablePage. jsp shows the effect

Third-party jar packages used:

Dom4j-1.6.1.jar for xml File Parsing
Postgresql-9.3-1101.jdbc4.jar for JDBC connection to postgreSQL database

The paging effect is as follows: you can click the previous page to flip the page, and enter the specified page to jump (beyond the range to jump to the 1st or last page ). For more information about the implementation, see the detailed code. I'm a newbie. I'm in the learning stage. It's certainly better to have some tips!

II. Specific Code Implementation

1. config. xml database connection information attribute File

<?xml version="1.0" encoding="utf-8"?><!DOCTYPE postgres[ <!ELEMENT postgres (driver,url,username,pwd)> <!ELEMENT driver (#PCDATA)> <!ELEMENT url (#PCDATA)> <!ELEMENT username (#PCDATA)> <!ELEMENT pwd (#PCDATA)>]><postgres> <driver>org.postgresql.Driver</driver> <url>jdbc:postgresql://localhost:5432/java</url> <username>admin</username> <pwd>k42jc</pwd></postgres>

2. DOM4JUtil. java

Package util; import org. dom4j. document; import org. dom4j. extends entexception; import org. dom4j. element; import org. dom4j. io. SAXReader;/*** used to parse the xml property file * @ author JohsonMuler **/public class DOM4JUtil {private static Element root = null; static {// static code block // create resolution object SAXReader sr = new SAXReader (); // obtain the current project path // String url = System. getProperty ("user. dir "); String url = DOM4JUtil. class. getResource (""). getPath (); // System. out. println (url); try {// obtain the configuration file information Document doc = sr through the file path. read (url + "config. xml "); // get the root node root = doc. getRootElement ();} catch (incluentexception e) {e. printStackTrace () ;}} public static String getPostgresData (String str) {// obtain the configuration file data Element e = root Based on the root node. element (str); String data = e. getText (); return data;} public static void main (String [] args) {// String url = DOM4JUtil. class. getResource (".. "). getPath (); // System. out. println (System. getProperty ("user. dir "); // System. out. println (url); String driver = getPostgresData ("driver"); String url = getPostgresData ("url"); System. out. println (driver); System. out. println (url );}}

3. PostgreSQL_Util.java

Package util; import java. SQL. preparedStatement; import java. SQL. statement; import java. SQL. connection; import java. SQL. driverManager; import java. SQL. resultSet; import java. SQL. SQLException; import java. util. list; public class extends SQL _util {private static DOM4JUtil dom = new DOM4JUtil (); private static Connection c = null; private static ResultSet rs = null; private static String driver = dom. getdomainsdata ("driver"); private static String url = dom. getdomainsdata ("url"); private static String username = dom. getdomainsdata ("username"); private static String pwd = dom. getPostgresData ("pwd"); public PostgreSQL_Util () {try {Class. forName (driver); c = DriverManager. getConnection (url);} catch (ClassNotFoundException e) {System. out. println ("specified class not found:" + e. getMessage ();} catch (SQLException e) {System. out. println ("connection exception:" + e. getMessage () ;}}/*** Data Query Method (Statement) * @ param SQL * @ return * @ throws SQLException */public ResultSet executeQuery (String SQL) throws SQLException {Statement s = c. createStatement (); rs=s.exe cuteQuery (SQL); return rs;}/*** overload method (PreparedStatement) * @ param SQL * @ param list * @ return * @ throws SQLException */public ResultSet executeQuery (String SQL, List <Object> list) throws SQLException {PreparedStatement ps = c. prepareStatement (SQL); for (int I = 0; I <list. size (); I ++) {System. out. println (list. get (I); System. out. println (I + 1); ps. setObject (I + 1, list. get (I);} rsw.ps.exe cuteQuery (); c. close (); return rs;}/*** data update method (add, delete, change) (Statement) * @ param SQL * @ throws SQLException */public int executeUpdate (String SQL) throws SQLException {Statement s = c. createStatement (); int I =s.exe cuteUpdate (SQL); c. close (); return I;}/*** overload method (PreparedStatement) * @ param SQL * @ param list * @ throws SQLException */public int executeUpdate (String SQL, list <Object> list) throws SQLException {PreparedStatement ps = c. prepareStatement (SQL); for (int I = 0; I <list. size (); I ++) {ps. setObject (I + 1, list. get (I);} int iw.ps.exe cuteUpdate (); c. close (); return I;}/*** obtain the Connection separately * @ return * @ throws ClassNotFoundException * @ throws SQLException */public static Connection getConnection () throws ClassNotFoundException, SQLException {Class. forName (driver); c = DriverManager. getConnection (url); return c ;}}

4. PageProperties. java

Package bean; import java. SQL. resultSet; public class PageProperties {private int currentPage; // the current page number private int totalPages; // the total number of pages private int totalRecords; // The total number of data entries private ResultSet rs; // dynamic result set public PageProperties () {super ();} public PageProperties (int currentPage, int totalPages, int totalRecords, ResultSet rs) {super (); this. currentPage = currentPage; this. totalPages = totalPages; this. totalRecords = totalRecords; this. rs = rs;} public int getCurrentPage () {return currentPage;} public void setCurrentPage (int currentPage) {this. currentPage = currentPage;} public int getTotalPages () {return totalPages;} public void setTotalPages (int totalPages) {this. totalPages = totalPages;} public int getTotalRecords () {return totalRecords;} public void setTotalRecords (int totalRecords) {this. totalRecords = totalRecords;} public ResultSet getRs () {return rs;} public void setRs (ResultSet rs) {this. rs = rs ;}}

5. TablePage. java

Package bean; import java. SQL. resultSet; public class PageProperties {private int currentPage; // the current page number private int totalPages; // the total number of pages private int totalRecords; // The total number of data entries private ResultSet rs; // dynamic result set public PageProperties () {super ();} public PageProperties (int currentPage, int totalPages, int totalRecords, ResultSet rs) {super (); this. currentPage = currentPage; this. totalPages = totalPages; this. totalRecords = totalRecords; this. rs = rs;} public int getCurrentPage () {return currentPage;} public void setCurrentPage (int currentPage) {this. currentPage = currentPage;} public int getTotalPages () {return totalPages;} public void setTotalPages (int totalPages) {this. totalPages = totalPages;} public int getTotalRecords () {return totalRecords;} public void setTotalRecords (int totalRecords) {this. totalRecords = totalRecords;} public ResultSet getRs () {return rs;} public void setRs (ResultSet rs) {this. rs = rs ;}}

6. Page. java: This is the main processing class, Servlet

Package servlet; import java. io. IOException; import java. io. printWriter; import java. SQL. resultSet; import java. SQL. SQLException; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; import util. postgreSQL_Util; import bean. pageProperties; import bean. tablePage; public class Page extends HttpServlet {public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html; charset = UTF-8"); PrintWriter out = response. getWriter ();/*** set the paging attribute through TablePage **/TablePage tb = new TablePage (); // obtain the page number of the current table int currentPage = tb. currentPage (tb. getStrPage (request, "page"); System. out. println (currentPage); // sets the number of data entries per page. setPageRecord (10); // set to display 10 pieces of data per page/*** set JDBC connection and data processing through xxSQL_Util */PostgreSQL_Util postgres = new PostgreSQL_Util (); try {ResultSet rs_count=s.exe cuteQuery ("select count (*) as c from student"); rs_count.next (); // get the total number of data entries int totalRecords = rs_count.getInt ("c "); // obtain the total number of pages in the table based on the total number of data entries in the table. int totalPages = tb. getTotalPages (totalRecords); if (currentPage> totalPages) {currentPage = totalPages; // ensure that the last page does not exceed the range} // obtain the dynamic result set ResultSet rs1_tb.getpageresultset(s.exe cuteQuery ("select * from student"), currentPage) based on the database table information and the current page information ); /*** add data to javaBean */PageProperties pp = new PageProperties (currentPage, totalPages, totalRecords, rs);/*** forward the javaBean to the frontend */request. setAttribute ("result", pp); request. getRequestDispatcher ("tablePage. jsp "). forward (request, response);} catch (SQLException e) {System. out. println ("Class Page:" + e. getMessage (); // e. printStackTrace ();}}}

7. Display Results on the front end of tablePage. jsp

<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% @ page import =" java. SQL. resultSet "%> <% @ page import =" bean. pageProperties "%> <% @ taglib prefix =" c "uri =" http://java.sun.com/jsp/jstl/core "%> <% String path = request. getContextPath (); String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/"; %> <! Doctype html public "-// W3C // dtd html 4.01 Transitional // EN"> 

Initially, it seems that the background code is really cumbersome, but this takes into account the robustness and portability of the program to facilitate code reuse. It will be used later. In the property file (config. configure the JDBC driver in xml, and obtain the background Servlet (Page. jsp), combined with page properties (PageProperties. java class.

Of course, this is also because of personal learning and tends to use more things.

I hope this article will help you with jsp program design.

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.