数据库分页  +  jsp页面   完整代码案例

使用技术:

1)mysql数据库基础

2)C3P0连接池(开源框架)

3)dbUtils(第三方框架)

4)jsp基础

用到的第三方jar包:

C3P0连接池核心jar包:C3P0-0.9.1.0.jar      

        注意:C3P0使用配置文件方式实现,需在src目录下存放配置未见(c3p0-config.xml)

项目src包下  C3P0  配置问价格式如下(文件名:c3p0-config.xml):

---------------------------------------------------------------------------------------------

<c3p0-config>

    <!-- 以下是默认项  连接mysql的驱动 -->

    <default-config>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/student</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">123456</property>
        <property name="initialPoolSize">3</property>
        <property name="maxPoolSize">6</property>
        <property name="maxIdleTime">1000</property>
    </default-config>

  <!-- 以下可以配置其他数据库的驱动 -->
<!--     <named-config name="oracle_config">
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/student</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="initialPoolSize">3</property>
        <property name="maxPoolSize">6</property>
        <property name="maxIdleTime">1000</property>
    </named-config> -->


</c3p0-config>
-------------------------------------------------------------------------------------------
连接mysql数据的驱动jar包:mysql-connector-java-5.1.12-bin.jar

dbutils第三方jar包:commons-dbutils-1.6.jar

Jstl标签库的jar包:jstl-1.2.jar(若新建项目中没有带,则自行导入)

   注意:使用javaee5.0的项目自动导入jstl支持jar

实现效果

JAVA_WEB 数据库分页 + jsp页面 完整代码案例

项目目录

JAVA_WEB 数据库分页 + jsp页面 完整代码案例


项目描述及需求

JAVA_WEB 数据库分页 + jsp页面 完整代码案例


项目图解

JAVA_WEB 数据库分页 + jsp页面 完整代码案例


代码记录

untils包下工具类

-----------------------------JdbcUntils类代码如下(操作数据库的类)--------------------------------

package com.wxw.people.untils;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.junit.Test;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JdbcUntils {

    /*
     * 1:初始化  C3P0   连接池
     * */
    private static DataSource dataSource;
    
    static {
        dataSource = new ComboPooledDataSource();
    }
    
    /*
     * 2:创建DbUntils核心工具类对象
     * */
    public static QueryRunner getQueryRunner(){
        
        // 创建QueryRunner对象,传入连接池对象
        // 在创建QueryRunner对象的时候,如果传入了数据源对象;
        // 那么在使用QueryRunner对象方法的时候,就不需要传入连接对象;
        // 会自动从数据源中获取连接(不用关闭连接)
        
        QueryRunner queryRunner = new QueryRunner(dataSource);
        
        return queryRunner;
    }
    
    @Test
    public void test(){
        String sql = "insert into student(id,name,age,gender) values(?,?,?,?)";
        
        for(int i = 8 ; i <= 100; i++){
            if(i%2==0){
                try {
                    getQueryRunner().update(sql, i,"Lucy" + i,i,"女" );
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }else{
                try {
                    getQueryRunner().update(sql, i,"Lucy" + i,i,"男" );
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            
        }
    }  
}


-----------------------------PageBean类代码如下(存储返回页数,查询到的分页数据等)--------------------------------

package com.wxw.people.untils;

import java.util.List;

public class PageBean<T> {

    private int currentPage = 1;                //当前页,默认显示第一页
    private int pageCount = 8;                //每页显示的行数(查询返回的行数),默认每页显示3行
    private int totalCount ;                        //数据库表中的总记录数
    private int totalPage;                        //总页数  =  总记录数  /    每页显示的行数(+1)
    private List<T> list;                           //分页查询到的数据
    
    
    //返回总页数
    public int getTotalPage() {
        
        //若总页数是奇数是页数增加的逻辑判断
        
        if(totalCount % pageCount == 0){
            totalPage = totalCount / pageCount;
        }else{
            totalPage = totalCount / pageCount +1;
        }
        
        return totalPage;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageCount() {
        return pageCount;
    }

    public void setPageCount(int pageCount) {
        this.pageCount = pageCount;
    }

    public int getTotalCount() {
        
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }



    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> list) {
        this.list = list;
    }
}

entity包下JavaBean类

-----------------------------Students类代码如下(JavaBean)--------------------------------

package com.wxw.people.entity;

public class Students {
    
    private int id;
    private String name;
    private int age;
    private String gender;
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    @Override
    public String toString() {
        return "Students [id=" + id + ", name=" + name + ", age=" + age
                + ", gender=" + gender + "]";
    }
}

dao包下操作数据库的一个接口及实现类

-----------------------------操作数据库  IEmployeeDao  接口代码如下--------------------------------

package com.wxw.people.dao;

import com.wxw.people.entity.Students;
import com.wxw.people.untils.PageBean;
/*
 *
 * 数据访问层,接口设计
 * */

public interface IEmployeeDao {

    /*
     * 分页查询数据
     * */
    public  void  getAll(PageBean<Students> pageBean);
    
    /*
     * 查询总记录数
     * */
    public int getTotalCount();
    
}

-----------------------------操作数据库  EmployeeDao  实现类代码如下--------------------------------

package com.wxw.people.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.wxw.people.dao.IEmployeeDao;
import com.wxw.people.entity.Students;
import com.wxw.people.untils.JdbcUntils;
import com.wxw.people.untils.PageBean;

public class EmployeeDao implements IEmployeeDao {

    @Override
    public void getAll(PageBean<Students> pageBean) {
        
        //查询总记录数;  并设置保存到pageBean对象中
        int totalCount = getTotalCount();
        pageBean.setTotalCount(totalCount);
        
        /*
         * 问题: jsp页面,如果当前页为首页,再点击上一页报错!
         *              如果当前页为末页,再点下一页显示有问题!
         * 解决:
         *        1. 如果当前页 <= 0;       当前页设置当前页为1;
         *        2. 如果当前页 > 最大页数;  当前页设置为最大页数
         */
        
        if(pageBean.getCurrentPage() <= 0){
            pageBean.setCurrentPage(1);
        }else if(pageBean.getCurrentPage() > pageBean.getTotalPage()){
            pageBean.setCurrentPage(pageBean.getTotalPage());
        }

        //获取当前页:计算查询的起始行、返回行数
        int currentPage = pageBean.getCurrentPage();
        int index = (currentPage - 1)*pageBean.getPageCount();
        int count = pageBean.getPageCount();
        
        String sql = "select * from student limit ?,?";
        
        QueryRunner queryRunner = JdbcUntils.getQueryRunner();
        
        try {
            List<Students> list = queryRunner.query(sql, new BeanListHandler<Students>(Students.class),index,count);
            pageBean.setList(list);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
    }

    
    
    
    
    public int getTotalCount() {
        
        String sql = "select count(*) from student";
        
        try {
            Long count = JdbcUntils.getQueryRunner().query(sql, new ScalarHandler<Long>());
            
            return count.intValue();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}

service包下操作业务逻辑的一个接口及实现类

-----------------------------操作业务逻辑  IEmployeeService 接口代码如下--------------------------------

package com.wxw.people.service;

import com.wxw.people.entity.Students;
import com.wxw.people.untils.PageBean;

public interface IEmployeeService {

    public void getAll(PageBean<Students> pb);
    
}

-----------------------------操作业务逻辑  EmployeeService 实现类代码如下--------------------------------

package cn.itcast.service.impl;

import cn.itcast.dao.IEmployeeDao;
import cn.itcast.dao.impl.EmployeeDao;
import cn.itcast.entity.Employee;
import cn.itcast.service.IEmployeeService;
import cn.itcast.utils.PageBean;

/**
 * 3. 业务逻辑层,实现
 * @author Jie.Yuan
 *
 */
public class EmployeeService implements IEmployeeService {
    
    // 创建Dao实例
    private IEmployeeDao employeeDao = new EmployeeDao();

    @Override
    public void getAll(PageBean<Employee> pb) {
        try {
            employeeDao.getAll(pb);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

servlet包下接收请求数据的servlet类

-----------------------------接收请求 参数  IndexServlet  类代码如下--------------------------------

package com.wxw.people.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wxw.people.entity.Students;
import com.wxw.people.service.IEmployeeService;
import com.wxw.people.service.impl.EmployeeService;
import com.wxw.people.untils.PageBean;

public class IndexServlet extends HttpServlet {
    
    
    private IEmployeeService service = new EmployeeService();
    private String uri;
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        
        try {
            //获取“当前页”参数(第一次访问时当前页为null)
            String currPage = req.getParameter("currentPage");
            
            //判断   第一次是设置默认值
            if(currPage == null || "".equals(currPage)){
                currPage = "1";
            }
            
            //转换   从jsp获取的都是字符串型的    需转换为整形才能保存到javaBean中
            int currentPage = Integer.parseInt(currPage);
            
            PageBean<Students> pb = new PageBean<Students>();
            pb.setCurrentPage(currentPage);
            
            //调用service层
            service.getAll(pb);
            
            //保存域对象
            req.setAttribute("pageBean", pb);
            
            uri = "/WEB-INF/index.jsp";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            uri = "/error/error.jsp";
        }
        
        //跳转
        req.getRequestDispatcher(uri).forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }   
}

网页端向用户展现的JSP页面

-----------------------------JSP页面代码如下--------------------------------

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>分页</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">
</head>
<body>

    <table border="1" width="80%" align="center" cellpadding="5" cellspacing="0">
    
        <tr>
            <td>编号</td>
            <td>姓名</td>
            <td>年龄</td>
            <td>性别</td>
        </tr>
        
        <c:choose>
            <c:when test="${not empty requestScope.pageBean.list }">
                <c:forEach var="stu" items="${requestScope.pageBean.list }" varStatus="vs">
                    <tr>
                        <td>${stu.id }</td>
                        <td>${stu.name }</td>
                        <td>${stu.age }</td>
                        <td>${stu.gender }</td>
                    </tr>
                </c:forEach>
            </c:when>
            <c:otherwise>
                <tr>
                    <td colspan="8">对不起,没有你要找的数据</td>
                </tr>
            </c:otherwise>
        </c:choose>
        
        <tr>
            <td colspan="8" align="center">
            <a href="${pageContext.request.contextPath }/index?currentPage=1">首页</a>
            <a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.currentPage - 1}">上一页</a>
            <a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.currentPage + 1}">下一页</a>
            <a href="${pageContext.request.contextPath }/index?currentPage=${requestScope.pageBean.totalPage}">末页</a>
            </td>
        </tr>
    
    </table>


</body>
</html>




相关文章: