java-web分页操作实现(javaBean+Servlet+jsp)

 

Java-web分页操作(jsp+servlet+javaBean)

一   分页操作分析

分页在web项目中是非常重要的技术,打开每一个网页都可以看到分页

1.疑问的出现

在写分页前要了解什么是分页,分页一共有多少个方法、多少个参数,应该如何编写方法的实现和定义参数的变量

2.疑问的解决

     分页一般分为首页、上一页、下一页、末页,还要得到总记录数,总页数,下面来详细介绍一下它们的概念

    如果设当前页为newPage

(1)当前页  ---------    打开网页时看到的页面

(2)首页  -----------   第一页          newPage=1

(3)上一页  ---------   当前页-1       newPage-1

(4)下一页  ---------   当前页+1      newPage+1

(5)末页    ---------   当前页==总页数  countPage=newPage

(6)总记录数 -------- select count(*) from 表名

(7)总页数  --------- 总记录数%每页显示的记录数=0 ? 总记录数/每页显示的记录数: 总记录数/每页显示的记录数+1

(8)显示当前页的分析    每页显示10条记录

       第1页:newpage=1         起始记录为0      10

       第2页:newpage=2         起始记录  10     10

       第3页:newpage=3         起始记录  20     10

       第4页:newpage=4         起始记录为30     10

       第5页:newpage=5         起始记录  40     10

       第6页:newpage=6         起始记录  50

       第n页 newpage=n         (newpage-1)*pageSize

    (9)查询指定的页面

       第一页:Select id,name,address from test limit 0,10       注:从0开始查询,每页显示10条记录

   第二页:Select id,name,address from test limit 20,10 

       第三页:Select id,name,address from test limit 30,10 

   第n页:Select id,name,address from test limit (newpage-1)*pageSize,pagesize 

二  功能的实现

1.创建数据库(mysql)

use echo;  
DROP TABLE IF EXISTS `test`;  
 
CREATE TABLE `test` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(50) NOT NULL,  
  `address` varchar(50) NOT NULL, 
  PRIMARY KEY (`id`)  
) ENGINE=InnoDB AUTO_INCREMENT=98 DEFAULT CHARSET=gbk;  

INSERT INTO `test` VALUES 
(1,'白雪公主','宫殿'),
(2,'小矮人','森林'),
(3,'萝卜','菜地'),
(4,'白菜','菜地'),
(5,'小猪','菜园'),
(6,'土豆','菜地'),
(7,'牛仔宝','牛栏'),
(8,'玉米','菜地'),
(9,'兔子','菜地'),
(10,'刀豆','菜地'),
(11,'青菜','菜地');

2.创建功能模块

 Paging.jsp

package com.csdn.paging.domain;
public class Paging {
 
    private Integer id;
    private String name;
    private String address;
 
    public Paging() {
       super();
 
    }
 
    public Paging(Integer id, String name, String address) {
       super();
       this.id = id;
       this.name = name;
       this.address = address;
    }
 
    public Integer getId() {
       return id;
    }
 
    public void setId(Integer id) {
       this.id = id;
    }
 
    public String getName() {
       return name;
    }
 
    public void setName(String name) {
       this.name = name;
    }
 
    public String getAddress() {
       return address;
    }
 
    public void setAddress(String address) {
       this.address = address;
    }
 
    @Override
    public String toString() {
       return "Paging [id=" + id + ", name=" + name + ", address=" + address
              + "]";
    }
 
}

PagingDao.java

package com.csdn.paging.dao;
import java.util.List;
import com.csdn.paging.domain.Paging;
 
public interface PagingDao {
    //显示总的记录条数
    Integer getCountRecord();
    //根据当前页到结束页的查询
    List<Paging> findIimitPage(Integer newPage);
    //总的页数
    Integer getCountPage();
}

PagingDaoImpl.java

package com.csdn.paging.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.csdn.paging.domain.Paging;

public class PagingDaoImpl implements PagingDao {

    private static final Integer pageSize = 10;//每页显示5条数据
    private Integer countRecord;// 共有多少条记录
    private Integer countPage;// 共有多少页

//    private static final String URL = "jdbc:MySQL://localhost:3306/echo?user=root&password=123456&useUnicode=true&characterEncoding=utf-8";
    private static Connection conn;
    private PreparedStatement pstmt;
    private ResultSet rs;

    static {
        try {
            // 加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            // 建立连接
//            conn = DriverManager.getConnection(URL);
            // 定义数据库地址url,并设置编码格式
            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/echo?useUnicode=true&characterEncoding=utf-8&useSSL=false", "root", "123456");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public Integer getCountRecord() {
        // 设置返回值
        Integer count = 0;
        // 获取连接
        // 定义sql语句 查询出记录条数
        String sql = "select count(*) as con from test";

        try {
            // 创建预处理对象
            pstmt = conn.prepareStatement(sql);
            // 为占位符赋值
            // 执行更新语句
            rs = pstmt.executeQuery();
            // 判断
            if (rs.next()) {
                count = rs.getInt("con");
            }
            // 计算出总页数,并从getCountPage方法中获取
            this.countPage = ((count % pageSize) != 0 ? (count / pageSize + 1): (count / pageSize));
            // 释放资源
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return count;
    }

    // 得到总的页数
    public Integer getCountPage() {
        // TODO Auto-generated method stub
        return countPage;
    }

    // 根据传过来的数值条件查询
    public List<Paging> findIimitPage(Integer newPage) {
        // 修改返回值
        List<Paging> entities = new ArrayList<Paging>();
        // 获取连接
        // 定义SQL语句
        String sql = "select id,name,address from test limit ?,?";//参数为(newPage - 1) * pageSize和pageSize
        try {
            // 创建预处理对象
            pstmt = conn.prepareStatement(sql);
            // 为占位符赋值
            int index = 1;
            pstmt.setObject(index++, (newPage - 1) * pageSize);
            pstmt.setObject(index++, pageSize);
            // 执行更新
            rs = pstmt.executeQuery();
            // 判断
            while (rs.next()) {
                Paging entity = new Paging();
                entity.setId(rs.getInt("id"));
                entity.setName(rs.getString("name"));
                entity.setAddress(rs.getString("address"));
                entities.add(entity);
            }
            // 释放资源
            if (rs != null) {
                rs.close();
            }
            if (pstmt != null) {
                pstmt.close();
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return entities;
    }
}

PagingServlet.java

注:dopost doget都是父类HttpServlet里的方法 不要直接copy,先生成方法再copy代码。我就是出现显示不出来数据的错误,原因就是servlet没有接收jsp的请求,方法没有生效。

package com.csdn.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

import com.csdn.paging.dao.PagingDaoImpl;
import com.csdn.paging.domain.Paging;

public class PagingServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("doget");
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        System.out.println("dopost");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String npage = request.getParameter("newPage");
        System.out.println("npage="+npage);
        PagingDaoImpl pageService=new PagingDaoImpl();
        List<Paging> entities = pageService.findIimitPage(new Integer(npage));
        int countRecord = pageService.getCountRecord();
        int countPage = pageService.getCountPage();
        request.setAttribute("entities", entities);
        request.setAttribute("countPage", countPage);
        request.setAttribute("newPage", npage);
        request.setAttribute("countRecord", countRecord);
        request.getRequestDispatcher("/paging.jsp").forward(request, response);
    }
}

paging.jsp  

注:一定要在web-inf的lib下添加jar包jstl.jar、standard.jar.否则<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>该行会报错。

安装JSTL 库步骤如下:

  • 从Apache的标准标签库中下载的二进包(jakarta-taglibs-standard-current.zip)。下载地址:http://archive.apache.org/dist/jakarta/taglibs/standard/binaries/
  • 下载jakarta-taglibs-standard-1.1.2.zip 包并解压,将jakarta-taglibs-standard-1.1.2/lib/下的两个jar文件:standard.jar和jstl.jar文件拷贝到/WEB-INF/lib/下。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>paging.jsp</title>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  <!--通过超链接连接到servlet层上,并为newPage传参数 -->
    <body>
        <a href="/ServletPage/servlet/PagingServlet?newPage=1">查看所有信息</a>
       <table border="1">
           <c:forEach items="${entities}" var="entity">
              <tr>
                  <td>
                     ${entity.id}
                  </td>
                  <td>
                     ${entity.name}
                  </td>
                  <td>
                     ${entity.address}
                  </td>
              </tr>
           </c:forEach>
       </table>
       <a href="${pageContext.request.contextPath}/servlet/PagingServlet?newPage=1">首页</a>
       <a href="/ServletPage/servlet/PagingServlet?newPage=${newPage-1<=1?1:newPage-1}">上一页</a>
       <a href="/ServletPage/servlet/PagingServlet?newPage=${newPage+1>=countPage?countPage:newPage+1}">下一页</a>
       <a href="/ServletPage/servlet/PagingServlet?newPage=${countPage}">末页</a>
    </body>
</html>

 web.xml

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  
  
  <welcome-file-list>  
    <welcome-file>Login.html</welcome-file>  
    <welcome-file>Login.htm</welcome-file>  
    <welcome-file>paging.jsp</welcome-file>  
  
  </welcome-file-list>  
    
    <servlet>     
    <servlet-name>PagingServlet</servlet-name>  <!-- 类名 -->  
    <servlet-class>com.csdn.servlet.PagingServlet</servlet-class> <!-- 所在的包 -->  
  </servlet>  
  <servlet-mapping>  
    <servlet-name>PagingServlet</servlet-name>   
    <url-pattern>/servlet/PagingServlet</url-pattern><!-- 访问的网址 -->  
    <!-- http://localhost:8222/ServletPage/servlet/PagingServlet -->
    </servlet-mapping>  
    
   
</web-app>  

效果图如下:

 

 

参考的原文地址:http://blog.csdn.net/hanxiaoshuang123/article/details/6977667

 

posted on 2016-08-05 16:29  EchoLong333  阅读(1181)  评论(0编辑  收藏  举报

导航