Oracle数据库JSP分页

创建表

create table t_user(

username varchar(20),

password varchar(20));

insert into t_user values(‘aa‘,‘aa‘);

导入jdbc驱动

e:\oracle\product\10.1.0\Db_3\jdbc\lib\ojdbc14.jar

创建DB类,内容如下:

package util;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class DB {

    private DB() {

    }

    static {

       try {

           Class.forName("oracle.jdbc.OracleDriver");

       } catch (ClassNotFoundException e) {

           e.printStackTrace();

       }

    }

    public static Connection getConnection() {

       Connection con = null;

       try {

           con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","wt", "wt");

       } catch (SQLException e) {

           e.printStackTrace();

       }

       return con;

    }

    public static void closeConnection(Connection con) {

       if (con != null) {

           try {

              con.close();

              con = null;

           } catch (SQLException e) {

              e.printStackTrace();

           }

       }

    }

    public static Statement getStatement(Connection con){

       Statement statement=null;

       try {

           statement=con.createStatement();

       } catch (SQLException e) {

           e.printStackTrace();

       }

       return statement;

    }   

    public static void closeStatement(Statement statement) {

       if (statement != null) {

           try {

              statement.close();

              statement = null;

           } catch (SQLException e) {

              e.printStackTrace();

           }

       }

    }

    public static PreparedStatement getPreparedStatement(Connection con,String sql){

       PreparedStatement preparedStatement=null;

       try {

           preparedStatement=con.prepareStatement(sql);

       } catch (SQLException e) {

           e.printStackTrace();

       }

       return preparedStatement;

    }   

    /*

     * isGeneratedKey:是否获得记录的主键

     * Statement.RETURN_GENERATED_KEYS:是否获得记录的主键

     * */

    public static PreparedStatement getPreparedStatement(Connection con,String sql,boolean isGeneratedKey){ 

       PreparedStatement preparedStatement=null;

       try {

           if(isGeneratedKey==true){

              String generatedColumns[] = {"id"};  //该表的主键

              preparedStatement=con.prepareStatement(sql,generatedColumns);

           }

       } catch (SQLException e) {

           e.printStackTrace();

       }

       return preparedStatement;

    }

    public static void closePreparedStatement(PreparedStatement preparedStatement) {

       if (preparedStatement != null) {

           try {

              preparedStatement.close();

              preparedStatement = null;

           } catch (SQLException e) {

              e.printStackTrace();

           }

       }

    }

    public static ResultSet executeQuery(Statement statement,String sql){

       ResultSet resultSet=null;

       try {

           resultSet=statement.executeQuery(sql);

       } catch (SQLException e) {

           e.printStackTrace();

       }

       return resultSet;

    }

    public static void executeUpdate(String sql){

       Connection con=DB.getConnection();

       PreparedStatement ps=DB.getPreparedStatement(con, sql);

       try {

           ps.executeUpdate(sql);

       } catch (SQLException e) {

           e.printStackTrace();

       }finally{

           DB.closePreparedStatement(ps);

           DB.closeConnection(con);

       }

    }

    public static void closeResultSet(ResultSet resultSet){

       if(resultSet!=null){

           try {

              resultSet.close();

               resultSet=null;

           } catch (SQLException e) {

              e.printStackTrace();

           }

       }

    }

}

创建UserOracleDAO,内容如下:

package dao;

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;

import model.User;

import util.DB;

public class UserOracleDAO {

    public List<User> getPage(int pageNumber, int pageSize) {

       Connection con = DB.getConnection();

       String sql = "";

       if (pageNumber == 0) {  //如果第一页的话

           pageNumber = 1;

           sql += "select * from(select a.*, rownum r from( select  * from t_user) a where rownum <="

                  + pageSize + ") B where r >=" + pageNumber + "";

       } else {

           pageNumber += 1;

           sql += "select * from(select a.*, rownum r from( select  * from t_user) a where rownum <="

                  + pageNumber

                  * pageSize

                  + ") B where r >"

                  + ((pageNumber * pageSize) - pageSize) + "";

       }

       Statement st = null;

       ResultSet rs = null;

       List<User> users = new ArrayList<User>();

       try {

           st = con.createStatement();

           rs = st.executeQuery(sql);

           while (rs.next()) {

              User user = new User();

              user.setUsername(rs.getString("username"));

              user.setPassword(rs.getString("password"));

              users.add(user);

           }

       } catch (SQLException e) {

           e.printStackTrace();

       } finally {

           DB.closeResultSet(rs);

           DB.closeStatement(st);

           DB.closeConnection(con);

       }

       return users;

    }

    public int getCounts() {

       Connection con = DB.getConnection();

       Statement st = DB.getStatement(con);

       String sql = "select count(*) from t_user";

       ResultSet rs = null;

       int count = 0;

       try {

           rs = st.executeQuery(sql);

           if (rs.next()) {

              count = rs.getInt("count(*)");

           }

       } catch (SQLException e) {

           e.printStackTrace();

       }

       return count;

    }

    //获得首页

    public List<User> getFirstPage(int pageSize) {

       Connection con = DB.getConnection();

       int start=1;

       String sql = "select * from(select a.*, rownum r from( select  * from t_user) a where rownum <="

           + pageSize + ") B where r >=" +start+ "";

       Statement st = null;

       ResultSet rs = null;

       List<User> users = new ArrayList<User>();

       try {

           st = con.createStatement();

           rs = st.executeQuery(sql);

           while (rs.next()) {

              User user = new User();

              user.setUsername(rs.getString("username"));

              user.setPassword(rs.getString("password"));

              users.add(user);

           }

       } catch (SQLException e) {

           e.printStackTrace();

       } finally {

           DB.closeResultSet(rs);

           DB.closeStatement(st);

           DB.closeConnection(con);

       }

       return users;

    }

    //获得首页

    public List<User> getLastPage(int pageCount,int pageSize) {

       Connection con = DB.getConnection();

       int start=((pageCount*pageSize)-pageSize)+1;

       int end=(pageCount*pageSize)+1;

       String sql = "select * from(select a.*, rownum r from( select  * from t_user) a where rownum <="

           + end + ") B where r >=" +start+ "";

       Statement st = null;

       ResultSet rs = null;

       List<User> users = new ArrayList<User>();

       try {

           st = con.createStatement();

           rs = st.executeQuery(sql);

           while (rs.next()) {

              User user = new User();

              user.setUsername(rs.getString("username"));

              user.setPassword(rs.getString("password"));

              users.add(user);

           }

       } catch (SQLException e) {

           e.printStackTrace();

       } finally {

           DB.closeResultSet(rs);

           DB.closeStatement(st);

           DB.closeConnection(con);

       }

       return users;

    }

}

创建User内容如下:

package model;

import java.io.Serializable;

public class User implements Serializable{

    private String username;

    private String password;

    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;

    }

}

创建UserServlet,内容如下:

package servlet;

import java.io.IOException;

import java.util.List;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import model.User;

import dao.UserOracleDAO;

public class UserServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public void doGet(HttpServletRequest request, HttpServletResponse response)

           throws ServletException, IOException {

       doPost(request, response);

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)

           throws ServletException, IOException {

       String method=request.getParameter("method");

       UserOracleDAO uod=new UserOracleDAO(); 

       HttpSession session=request.getSession();

       int pageSize=5;

       int userSize=uod.getCounts(); //获得所有记录

        int pageCount=userSize/pageSize==0?userSize/pageSize:userSize/pageSize+1; //判断是否整除,页数是否是整数

       if(method.equals("first")){

           int currentPage=Integer.parseInt(request.getParameter("currentPage"));

           List<User> users=uod.getFirstPage(pageSize);

           session.setAttribute("list",users);

           session.setAttribute("currentPage",String.valueOf(currentPage));

           session.setAttribute("pageCount",String.valueOf(pageCount));

           getServletConfig().getServletContext().getRequestDispatcher("/list.jsp").forward(request,response);

           return;

       }

       if(method.equals("last")){

           int currentPage=pageCount;

           List<User> users=uod.getLastPage(pageCount, pageSize);

           session.setAttribute("list",users);

           session.setAttribute("currentPage",String.valueOf(currentPage));

           session.setAttribute("pageCount",String.valueOf(pageCount));

           getServletConfig().getServletContext().getRequestDispatcher("/list.jsp").forward(request,response);

           return;

       }

       if(method.equals("back")){

           int currentPage=Integer.parseInt(request.getParameter("currentPage"));

           if(currentPage!=0){

              currentPage--;

              List<User> users=uod.getPage(currentPage,pageSize);

              session.setAttribute("list",users);

              session.setAttribute("currentPage",String.valueOf(currentPage));

              session.setAttribute("pageCount",String.valueOf(pageCount));

               getServletConfig().getServletContext().getRequestDispatcher("/list.jsp").forward(request,response);

           }

           return;

       }

       if(method.equals("next")){

           int currentPage=Integer.parseInt(request.getParameter("currentPage"));

           currentPage++;

           List<User> users=uod.getPage(currentPage,pageSize);

           session.setAttribute("list",users);

           session.setAttribute("currentPage",String.valueOf(currentPage));

           session.setAttribute("pageCount",String.valueOf(pageCount));

           getServletConfig().getServletContext().getRequestDispatcher("/list.jsp").forward(request,response);

           return;

       }

    }

}

配置web.xml,内容如下:

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.5" 

    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/javaee 

    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

  <servlet>

    <description>This is the description of my J2EE component</description>

    <display-name>This is the display name of my J2EE component</display-name>

    <servlet-name>UserServlet</servlet-name>

    <servlet-class>servlet.UserServlet</servlet-class>

  </servlet>

  <servlet-mapping>

    <servlet-name>UserServlet</servlet-name>

    <url-pattern>/UserServlet</url-pattern>

  </servlet-mapping>

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

</web-app>

创建list.jsp,内容如下:

<%@ page language="java"

    import="java.util.*,model.User,dao.UserOracleDAO"

    pageEncoding="GB18030"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme() + "://"

           + request.getServerName() + ":" + request.getServerPort()

           + path + "/";

%>

<%

    List<User> users = (List<User>) session.getAttribute("list");

    int currentPage=0;  //当前页

    int PageCount=0; //总页数

    int pageSize=5;  //每页显示数据数 

    if (users != null) {

       currentPage=Integer.parseInt((String)session.getAttribute("currentPage"));

       PageCount=Integer.parseInt((String)session.getAttribute("pageCount"));

    } else {

       currentPage=0;

       UserOracleDAO uod = new UserOracleDAO();

       users = uod.getFirstPage(pageSize);

       int userSize=uod.getCounts();

       PageCount=userSize/pageSize==0?userSize/pageSize:userSize/pageSize+1; //判断是否整除,页数是否是整数

    }

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

       <base href="<%=basePath%>">

       <title>My JSP ‘index.jsp‘ starting page</title>

       <meta http-equiv="pragma" content="no-cache">

       <meta http-equiv="cache-control" content="no-cache">

       <meta http-equiv="expires" content="0">

       <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

       <meta http-equiv="description" content="This is my page">

       <!--

    <link rel="stylesheet" type="text/css" href="styles.css">

    -->

    </head>

    <body>

       <table border=‘1‘>

           <tr>

              <td>

                  用户名

              </td>

              <td>

                  密码

              </td>

           </tr>

           <%

              for (Iterator<User> it = users.iterator(); it.hasNext();) {

                  User user = it.next();

           %>

           <tr>

              <td><%=user.getUsername()%></td>

              <td><%=user.getPassword()%></td>

           </tr>

           <%

              }

           %>

           <tr>

              <td>

                  <a href="UserServlet?method=first&currentPage=0">首页</a>

                  <a href="UserServlet?method=back&currentPage=<%=currentPage%>">上一页</a>

                  <%if(currentPage==0){ %>

                  <a>1/<%=PageCount%></a>

                  <%}else if(currentPage==PageCount){%>

                      <a><%=PageCount%>/<%=PageCount%></a>

                  <%}else{ %>

                      <a><%=currentPage+1%>/<%=PageCount%></a>

                  <%}%>

                  <a href="UserServlet?method=next&currentPage=<%=currentPage%>">下一页</a>

                  <a href="UserServlet?method=last">尾页</a>

              </td>

           </tr>

       </table>

    </body>

</html>

Oracle数据库JSP分页

时间: 2024-10-11 22:36:31

Oracle数据库JSP分页的相关文章

Oracle数据库查询分页SQL语句

Oracle数据库查询分页数据SQL语句: select * from (select a.*,rownum row_num from (select * from mytable t order by t.id desc) a ) b where b.row_num between 1 and 10

【知了堂学习笔记】JSP页面数据分页实现(一)——分页概念以及主流数据库的分页查询

一.分页简介 1.分页,就是一种将数据库里的数据一部分展示给用户的技术.为什么要这样做呢?因为一般来说用户在查询时数据是非常多的,当一个页面不能显示所有数据时,我们就要对查询的数据进行分页,就像我们的书本分成一页一页一样.最简单的例子就是百度,当你百度时,成千上万的数据,并不是呈现在一个页面的. 2.分页的实现方式 1)假分页(不推荐):什么是假分页呢?假分页就是一次性将数据库里的数据全部取出来,存储在页面中,然后再将数据分别展示出来.这种假分页在数据少的还可以玩玩,当数据多起来的时候,这种方式

Oracle+Jsp分页

分页原理: 从jsp页面传到servlet请求中,可以获得当前点击的页数,第一次进入为首页,通过在servlet中获得的当前页数,并且设计一次性显示的内容数,就是几条信息, 并且从dao层查询到数据库中总记录数,就可以得到总的多少页,把这些信息封装到PageBean对象中即可. // 将分页组件保存到session中,到页面上遍历显示 // 将当前页要显示的数据集合保存到session中,到页面上遍历显示 // 将分页类对象保存到session中,到页面使用来做分页显示 // 重定向到显示页面

JSP与oracle数据库交互案例

本案例为咖啡销售情况录入查询系统 一.数据输入系统: 1.  设计输入信息页面 代码如下: <html> <head> </head> <body> <center><H1>咖啡管理系统--录入系统</H1></center> 欢迎来到录入系统<br /> <form action="inputaction.jsp" method="post" name

《Oracle数据库的SQL分页模板》

在系统开发过程中,需要对数据进行查询,大部分情况下从数据库中查询的数据量比较大,在系统页面无法全部显示,而且查询全部的数据会影响系统的反应速度,需要对所查询的数据进行分页的查询操作,以此减轻系统的压力. 在Oracle数据库中,如何完成分页SQL的编写,影响着系统开发的速度,特提供两个SQL的分页模板: (1).采用oracle的内置函数ROWNUM.(ROWNUM是结果的伪列,仅仅当聚集结果时产生,但早于排序或聚合) select <columns I actually want>,rown

oracle,mysql,SqlServer三种数据库的分页查询

MySql: MySQL数据库实现分页比较简单,提供了 LIMIT函数.一般只需要直接写到sql语句后面就行了.LIMIT子 句可以用来限制由SELECT语句返回过来的数据数量,它有一个或两个参数,如果给出两个参数, 第一个参数指定返回的第一行在所有数据中的位置,从0开始(注意不是1),第二个参数指定最多返回行数.例如:select * from table WHERE … LIMIT 10; #返回前10行select * from table WHERE … LIMIT 0,10; #返回前

Java代码操作oracle数据库(JDBC+sevrlet+jsp+html)

1, 注册页面 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Strict//EN" "http://www.w3.org/TR/html4/strict.dtd"> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"

Oracle数据库分页总结

在Oracle数据库中,数据分页功能是必不可少的操作, Oracle数据库分页查询语句有三种写法: --1.根据ROWID 来分select * from nmb where rowid in(select rid from (select rownum rn,rid from (select rowid rid,userid from nmb order by userid desc )where rownum <30)where rn>20)order by userid desc;--效

JSP读取Oracle数据库里的图片Blob字段并显示在页面上&lt;转&gt;

java代码:首先定义一个读取Oracle数据库的Blob字段并把字节写入一个输出流的方法. 1 public static void writeImg(OutputStream os) { 2 Connection con; 3 try { 4 con = ConnectionFactory.getConnection(); 5 Statement stmt = con.createStatement(); 6 ResultSet rs = stmt.executeQuery("select