Jsp+servlet+javabean implementation of data paging method complete instance _jsp programming

Source: Internet
Author: User
Tags getmessage postgresql xml attribute

This article describes the Jsp+servlet+javabean implementation of data paging method. Share to everyone for your reference, specific as follows:

Here faith and line and remember the mentality, record the learning process, learn quickly forget quickly, for fear of forgetting, for future use.
Part of the code used is to find your own online, and modify it yourself, plus your own understanding. Do not know whether it is original, only to do their own study records.

Use Related: PostgreSQL database, dom4j, JSP, Servlet

First, the engineering pattern, to a global view to facilitate readers and their own view and use

Ideas for:

The configuration information is recorded in Config.xml file to facilitate the database change and facilitate the porting and reuse.
Dom4jutil.java is used to parse an XML property file for required data
Postgresql_util.java data connection and database operation
Pageproperties.java for table Paging properties JavaBean
Pageproperties.java encapsulates paging operations
Page.java for paging main operation
Tablepage.jsp for effect Display interface

Third-party jar packages used:

Dom4j-1.6.1.jar FOR XML file parsing
Postgresql-9.3-1101.jdbc4.jar for JDBC Connection PostgreSQL database

The paging effect is as follows: You can click on the next page to achieve page, enter the specified pages jump (out of range jump to the 1th or last page). Specific implementation see detailed code, I have posted it. Small rookie one, is in the learning stage, there is a great God can guide under of course better, I hope the generous enlighten!

Second, the specific code implementation

1. Config.xml database connection Information Property 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.DocumentException;
Import org.dom4j.Element;
Import Org.dom4j.io.SAXReader;
 /** * is used to parse XML attribute file * @author Johsonmuler * * */public class Dom4jutil {private static Element root=null;
  static{//Static code block//Create resolution Object Saxreader sr=new Saxreader ();
  Gets the current engineering path//String Url=system.getproperty ("User.dir");
String Url=dom4jutil.class.getresource (""). GetPath ();
  System.out.println (URL);
   try {//Get profile information through the file path document Doc=sr.read (url+ "Config.xml");
  Gets the root node root=doc.getrootelement ();
  catch (Documentexception e) {e.printstacktrace ();
  The public static string Getpostgresdata (String str) {//is based on the root node to get the configuration file Data Element e=root.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 Postgresql_util {private static dom4jutil dom=new dom4jutil ();
 private static Connection C=null;
 private static ResultSet Rs=null;
 private static String Driver=dom.getpostgresdata ("Driver");
 private static String url=dom.getpostgresdata ("url");
 private static String Username=dom.getpostgresdata ("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 ("Get Connection Exception:" +e.getmessage ()); /** * Data Query Method (Statement) * @param SQL * @return * @throws SQLException/public ResultSet executequery (St Ring SQL)Throws sqlexception{Statement s=c.createstatement ();
  Rs=s.executequery (SQL);
 Return RS; /** * Overloaded Method (preparedstatement) * @param SQL * @param list * @return * @throws SQLException/Public result Set 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));
  } rs=ps.executequery ();
  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.executeupdate (SQL);
  C.close ();
 return i; /** * Overloaded 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 i=ps.executeupdate ();
  C.close ();
 return i; /** * Separate Get connection * @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;//current page number private int totalpages;//total pages private int totalrecords;//Total
 According to the number of 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;
 The public void setcurrentpage (int currentpage) {this.currentpage = CurrentPage;
 public int gettotalpages () {return totalpages;
 The public void settotalpages (int totalpages) {this.totalpages = TotalPages;
 public int gettotalrecords () {return totalrecords;
 The 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;//current page number private int totalpages;//total pages private int totalrecords;//Total
 According to the number of 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;
 The public void setcurrentpage (int currentpage) {this.currentpage = CurrentPage;
 public int gettotalpages () {return totalpages;
 The public void settotalpages (int totalpages) {this.totalpages = TotalPages;
 public int gettotalrecords () {return totalrecords;
 The 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 primary 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 paging properties through Tablepage * * * * * * * * tablepage tb=new tablepage ();
  Gets the page number int currentpage=tb.currentpage (tb.getstrpage (Request, "page") displayed by the current table);
  System.out.println (currentpage); Set the number of data bars per page Tb.setpagerecord (10);/Set 10 data per page/** * Set JDBC connection via xxsql_util and data processing * * Postgresql_util Postgres=ne W POSTGResql_util ();
   try {ResultSet rs_count=postgres.executequery ("SELECT count (*) as C from student");
   Rs_count.next ();
   Gets the total number of data bars int totalrecords=rs_count.getint ("C");
   Gets the total number of pages of the page display table int totalpages=tb.gettotalpages (totalrecords) based on the total data bar count of the datasheet; if (currentpage>totalpages) {currentpage=totalpages;//guarantees that the last page is not out of range}//Get dynamic result set ResultSet based on database table information and current page information rs=t
   B.getpageresultset (Postgres.executequery ("SELECT * from Student"), currentpage);
   /** * Add data to JavaBean * * pageproperties pp=new pageproperties (currentpage, TotalPages, totalrecords, RS);
   /** * Forward the JavaBean to the front-end * * * Request.setattribute ("result", pp);
  Request.getrequestdispatcher ("tablepage.jsp"). Forward (request, response);
catch (SQLException e) {System.out.println ("Class Page:" +e.getmessage ());
  E.printstacktrace ();

 }
 }
}

7, tablepage.jsp foreground display effect

<%@ 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, feel the background code is really cumbersome, but this is taking into account the program robustness and portability, convenient code reuse. Later to use, according to their own needs in the property file (Config.xml) to configure the relevant JDBC driver, in the JSP page through the request to obtain the background servlet (page.jsp) of the forwarding results ("result"), combined with page properties ( Pageproperties.java Class) to achieve the effect.

Of course, this is also because of personal learning, tend to use something more.

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.