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

  数据库分页  +  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

实现效果

项目目录


项目描述及需求


项目图解



代码记录

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>




自己收集的jsp分页代码。对于北大青鸟Y2的学员可能有用吧。自己也在做这个项目。这里有增、删、该、查加分页。有上一页、下一页、首页、尾页、第几页、还有带数字和点的分页。可以说是非常好的分页代码。想要的朋友自己处下载 <%@ page contentType="text/html; charset=GB2312" language="java" import="java.sql.*" errorPage="" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <% java.sql.Connection sqlCon; //数据库连接对象 java.sql.Statement sqlStmt; //SQL语句对象 ResultSet sqlRst=null; //java.sql.ResultSet sqlRst; //结果集对象 java.lang.String strCon; //数据库连接字符串 java.lang.String strSQL; //SQL语句 int intPageSize; //一页显示的记录数 int intRowCount; //记录总数 int intPageCount; //总页数 int intPage; //待显示页码 java.lang.String strPage; int i; //设置一页显示的记录数 intPageSize = 2; //取得待显示页码 strPage = request.getParameter("page"); if(strPage==null){ //表明在QueryString中没有page这一个参数,此时显示第一页数据 intPage = 1; } else{ //将字符串转换成整型 intPage = java.lang.Integer.parseInt(strPage); if(intPage<1) intPage = 1; } %><% String DBUser="sa"; String DBPassword="88029712"; //String DBServer="127.0.0.1"zjprice; String DBUrl="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs"; //创建语句对象 //Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); sqlCon=java.sql.DriverManager.getConnection(DBUrl,DBUser,DBPassword); sqlStmt=sqlCon.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY); //执行SQL语句并获取结果集 String sql=null; String search=""; String ToPage=request.getParameter("ToPage"); if(request.getParameter("search")!=null &&!request.getParameter("search").equals("")) {search=new String(request.getParameter("search").trim().getBytes("8859_1")); } sql="select top 50 au_id,au_lname from authors "; /*sql="select*from ta,tb where id like'%"+search+"%'"; sql=sql+"or title like'%"+search+"%'"; sql=sql+"or time like'%"+search+"%'"; sql=sql+"or con like'%"+search+"%'"; sql=sql+"order by id";*/ sqlRst=sqlStmt.executeQuery(sql); //获取记录总数 sqlRst.last(); intRowCount = sqlRst.getRow(); //记算总页数 intPageCount = (intRowCount+intPageSize-1) / intPageSize; //调整待显示的页码 if(intPage>intPageCount) intPage = intPageCount; %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>test</title> </head> <body> <table border="1" cellspacing="0" cellpadding="0"> <tr> <th>标题id</th> <th>内容表</th> </tr> <% if(intPageCount>0) { //将记录指针定位到待显示页的第一条记录上 sqlRst.absolute((intPage-1) * intPageSize + 1); //显示数据 i = 0; while(i<intPageSize && !sqlRst.isAfterLast()){ %> <tr> <td> <%=sqlRst.getString(1)%> </td> <td> <%=sqlRst.getString(2)%> </td> </tr> <% sqlRst.next(); i++; } } %> <tr><td colspan="8">共有<font color=red><%= intRowCount %></font>条记录 当前<font color=red><%=intPage%>/<%=intPageCount%></font>页  <% if(intPageCount > 1){ %> <% if(intPage !=0){%> <a href="mysqlpage.jsp">首页</a> <%}if(intPage != 1){%><a href="mysqlpage.jsp?page=<%= intPage - 1 %>">上一页</a> <%}if(intPage<intPageCount){%><a href="mysqlpage.jsp?page=<%=intPage+1%>">下一页</a><%}%> <a href="mysqlpage.jsp?page=<%= intPageCount %>">尾页</a> <% } %>跳转到 <select name="page" onChange="javascript:this.form.submit();"> <% for(i=1;i<=intPageCount;i++){%> <option value="<%= i %>" <% if(intPage == i){%>selected<% } %>><%= i %></option> <% } %> </select>页 <%int m,n,p; %> <%if (intPage>1){ if(intPage-2>0){ m=intPage-2;} else { m=1;} if(intPage+2<intPageCount){ n=intPage+2;} else{ n=intPageCount; }%> 转到页码: [ <% for(p=m;p<=n;p++) { if (intPage==p){ %> <font color="black"><%=p %></font> <% } else{%> <a href=?page=<%=p %>><font color=red>[<%=p %>]</font></a> <% } }%>]<%} %> </td></tr> </table> </body> </html> <% //关闭结果集 sqlRst.close(); //关闭SQL语句对象 sqlStmt.close(); //关闭数据库 sqlCon.close(); %>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晓 5

有啥不懂的可以单聊解答....

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值