servlet Pagination code example

Source: Internet
Author: User
Tags xmlns create database tomcat server oracle database

  This article describes the servlet paging code implementation, using an Oracle database to get data from the Scott User's EMP table, and pagination implementation steps to see the following code

1. First create an object UserData to hold the data obtained from the database.     Code as follows: Package com.tool;   Import Java.math.BigDecimal; Import Java.util.Date;  /**  * Created by Lx_sunwei on 14-1-6.  */public class UserData {     /**      * EMP table data Properties      */  & nbsp Private String ename;     Private String job;     Private BigDecimal empno;     Private BigDecimal Mgr;     Private Date hiredate;     Private BigDecimal Sal;     Private BigDecimal comm;     Private BigDecimal deptno;       Public BigDecimal getempno () {        [return empno;    }   &NBSP ;   public void Setempno (BigDecimal empno) {        this.empno = empno;    }   &NB Sp   Public BigDecimal Getmgr () {        return MGR    :       Public VO ID setmgr (BigDecimal Mgr) {         this.mgr = Mgr;    }       public Date gethiredate () {        return hiredate   &NBSP ; }       public void sethiredate (Date hiredate) {        this.hiredate = hiredate; &nbs P  }       public BigDecimal getsal () {       -return sal;    }       public void setsal (BigDecimal sal) {        this.sal = sal;    }   &nbs P   Public BigDecimal Getcomm () {        return comm    :       Public void Setcomm (BigDecimal comm) {        This.comm = comm;    }       public BigDecimal Getdeptno () {        return deptno;    }       public void setde Ptno (BigDecimal deptno) {        This.deptno = Deptno;    } &nbsp     Public String Getename () {       -return ename;    }       PU Blic void Setename (String ename) {        this.ename = ename;    }       PU Blic String Getjob () {        return job;    :       public void Setjob (STR ing job {        this.job = job;    }}       2. Create a DBHelper object to interact with the database   Code as follows: Package Com.dao;   Import Com.tool.UserData;   Import Java.math.BigDecimal; Import java.sql.*; Import java.util.*; Import Java.util.Date;  /**  * Created by Lx_sunwei on 14-1-6.  */public class DBHelper {      Connection conn;  //database Connection object     PreparedStatement pt;  //sql statement preprocessing object     ResultSet RS;  //result set object       public  dbhelper () {        try {        &nbsp   Class.forName ("Oracle.jdbc.driver.OracleDriver");  //Load driver        } catch (ClassNotFoundException e) {            E. Printstacktrace ();        }     {     /**      * get current page data       * @param curpage      * @param rowsperpage      * @return      */  &NBS P Public list<userdata> getData (int curpage, int rowsperpage) {          LIST<USERDATA&GT ; DataList = new arraylist<> ();         String url = "Jdbc:oracle:thin: @localhost: 1521:ORCL";         try {            conn = drivermanager.getconnection (URL, "Scott" , "Tiger");             String sql = "SELECT * from emp where rownum <= (? -1) * "+rowsperpage+" + "+rowsperpage+") minus "+       &NBSP             "SELECT * from emp where rownum <= (? -1) * "+rowsperpage+";             PT = conn.preparestatement (SQL);             Pt.setint (1,curpage);             Pt.setint (2,curpage);             RS = Pt.executequery ();             while (Rs.next ()) {               /** & nbsp                * data from result set                  */                UserData UserData = new UserData ();                 BigDecimal empno = Rs.getbigdecimal ("Empno");                 String ename = rs.getstring ("ename");                 String job = rS.getstring ("job");                 BigDecimal mgr = Rs.getbigdecimal ("Mgr");                 Date hiredate = rs.getdate ("HireDate");                 BigDecimal sal = Rs.getbigdecimal ("Sal");                 BigDecimal comm = rs.getbigdecimal ("comm");                 BigDecimal deptno = Rs.getbigdecimal ("Deptno");                /**                   * Set object properties                  */                Userdata.setempno (empno);                 userdata.setename (ename);                 userdata.setjob (Job);             &NBSP   Userdata.setmgr (MGR);                 userdata.sethiredate (hiredate);                 userdata.setsal (SAL);                 USERDATA.SETCOMM (comm);                 Userdata.setdeptno (DEPTNO);                 Datalist.add (userData);  //add objects to the set                         rs.close ();             pt.close ();             conn.close ();        } catch (SQLException e) {            e.printstacktrace (); &nbs P      }         return dataList;    }      /**      * back to total pages      * @return      */     PublIC int getmaxpage (int rowsperpage) {        int maxpage;         int Maxrowcount = 0;         String url = "Jdbc:oracle:thin: @localhost: 1521:ORCL";         try {            conn = drivermanager.getconnection (URL, "Scott" , "Tiger");  //CREATE database connection             String sql = "SELECT COUNT (*) from EMP";             PT = conn.preparestatement (SQL);             RS = Pt.executequery ();             if (Rs.next ()) {                MAXROWCO UNT = Rs.getint (1);  //Total            }        } catch (SQLException e) {  &NBS P         e.printstacktrace ();        }         Maxpage = (Maxrowcount + rowsPerPage-1)Rowsperpage;  //Total pages         return maxpage;    }}       3. Create a Servlet to control the display page The     code is as follows: Package com.servlet;   Import Com.dao.DBHelper; Import Com.tool.UserData;   Import Javax.servlet.RequestDispatcher; Import javax.servlet.ServletException; Import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.HttpServletResponse; Import java.io.IOException; Import java.util.*;  /**  * Created by Lx_sunwei on 14-1-6.  */public class Servlet extends HttpServlet {      public int rowsperpage;  //the number of rows to display per page   &N Bsp public int curpage;  //Current Page page number     public int maxpage;  //Total pages     DBHelper db = new DBHelper ();     Public Servlet () {        rowsperpage = 5;    }       PROTECTE d void DoPost (HttpServletRequest request, httpservletresponse response) throws SErvletexception, IOException {        String curPage1 = request.getparameter ("page");  //get current Page page Code         if (CurPage1 = null) {            curpage = 1;             Request.setattribute ("Curpage", curpage);  //set Curpage object        }else {            Curpage = Integer.parsei NT (CURPAGE1);             if (Curpage < 1) {                cur Page = 1;                         Request.setattribute ("Curpage", Curpa GE);        }           list<userdata> dataList;         dataList = Db.getdata (curpage,rowsperpage);  //get current page data         maxpage = Db.getmaxpage (rowsperpage);  //Get total pages        Request.setattribute ("DataList", dataList);         Request.setattribute ("Maxpage", maxpage);           RequestDispatcher rd = Request.getrequestdispatcher ("pagemain.jsp");  //forward the request to the pagemain.jsp page         Rd.forward (request,response);    }       protected void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {        doPost (request,response);    }}     &NB Sp 4. Create JSP page, display data.   Code as follows: <%@ page import= "java.util.List"%> <%@ page import= "com.tool.UserData"%> <%@ page Contenttyp E= "Text/html;charset=utf-8" language= "java"%> <html> <head>     <title>servlet data paging </title>     <link rel= "stylesheet" type= "Text/css" href= "Css.css" > </head> <body> <div style= "margin-top:15%; margin-left:25% ">     <table>         <caption>scott user, EMP table data </caption>         <%! int curpage,maxpage; %>         <% curpage =integer.parseint (Request.getattribute ("Curpage"). toString ()); %> <!--get current page-->         <% maxpage =integer.parseint ((String) Request.getattribute (" Maxpage "). toString ()); %> <!--total pages-->         <%if (Request.getattribute ("dataList") = null) {    &NB Sp  %>         <tr>             <TD colspan= "8" > No data &l t;/td>         </tr>         <%        }else {&N Bsp      %>         <tr>             <!--table Head ;             <th>EMPNO</th>             <th>ename</th>             <th>JOB</th>         &NBS P   <th>MGR</th>             <th>HIREDATE</th>     &NB Sp       <th>SAL</th>             <th>COMM</th>   & nbsp         <th>DEPTNO</th>         </tr>       &NBSP ; <%             List List = (List) request.getattribute ("DataList");             for (Object alist:list) {              &NB Sp UserData UserData = (UserData) alist;        %>         <tr>             <!-- Get table Data-->             <td><%= userdata.getempno ()%></td> &NBsp           <td><%= userdata.getename ()%></td>         &NBSP ;   <td><%= userdata.getjob ()%></td>             <td><%= use Rdata.getmgr ()%></td>             <td><%= userdata.gethiredate ()%>& lt;/td>             <td><%= userdata.getsal ()%></td>     &NB Sp       <td><%= Userdata.getcomm ()%></td>             <TD ><%= Userdata.getdeptno ()%></td>         </tr>         <%                             &NBSP     ;  %>     </table> </div> <div style= "margin-top:8%; margin-left:29% ">     <%= curpage%> page, total <%= maxpage%> page       <%if (Curpage > 1) {   %>     <a HRE f= "servlet?page=1" > Home </a>     <a href= "servlet?page=<%=curpage-1%>" > previous page </a>     <%    }else {   %>     First prev     <%     &NBSP ;  }%>     <%if (Curpage < Maxpage) {   %>       <a href= "servlet?p Age=<%=curpage + 1%> "> next page </a>     <a href=" Servlet?page=<%=maxpage%> "> Last </a >     <%    }else {   %>     Next last     <%        }%>       goto <form name= "Form1" action= "Servlet" method= "get" >     <LA bel>         <select name= "page" onchange= "Document.form1.submit ()" >       &N Bsp     <%for (int i= 1; I <= maxpage; i++) {                if (i = = curpage) {            %>             <!--current page number default check-->             <OPTI On selected value= "<%= i%>" ><%= i%></option>             <%            }else {           %>         &NB Sp   <option value= "<%= i%>" ><%= i%></option>             <%                                   & nbsp }%>         </select>     </label> </form> page </div> </body> </html>     Web.xml in the configuration file is:   code as follows: <?xml version= "1.0" encoding= "UTF-8"?> <web-apP xmlns= "Http://java.sun.com/xml/ns/javaee"            xmlns:xsi= "http://www.w3.org/ 2001/xmlschema-instance "           xsi:schemalocation=" http://java.sun.com/xml/ns/ Java EE           http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd "           version= "3.0" >       <servlet>         <servlet-name> servlet</servlet-name>         <servlet-class>com.servlet.servlet</servlet-class >     </servlet>     <servlet-mapping>         <SERVLET-NAME&GT ; servlet</servlet-name>         <url-pattern>/Servlet</url-pattern>     </servlet-mapping>   </web-app>       Deploy the project to a TOMCAT server, enter address: http://localhost : 8080/servlet   So you can see the effect  

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.