MVC-结合Servlet和JSP实现分页功能

随着数据中记录的增多,网页上显示的数据会越来越多。 
当多到一定程度的时候,就会影响用户的体验。 
解决办法是通过分页技术,一次只显示数据库中的部分数据,如果要看其他数据,可以通过"下一页" "最后一页" 等翻页操作实现

  • 首先准备 DAO

    在DAO中提供方法 
    public List<Hero> list(int start, int count) 
    start表示开始的个数,count表示取多少条
    比如 list(0, 5) , 即表示第一页,每页有5条数据
    比如 list(5, 5) , 即表示第二页,每页有5条数据
    package dao;
     
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.ArrayList;
    import java.util.List;
     
    import bean.Hero;
     
    public class HeroDAO {
     
        public int getTotal() {
            int total = 0;
            try {
                Class.forName("com.mysql.jdbc.Driver");
     
                Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8",
                        "root", "admin");
     
                Statement s = c.createStatement();
     
                String sql = "select count(*) from hero";
     
                ResultSet rs = s.executeQuery(sql);
                while (rs.next()) {
                    total = rs.getInt(1);
                }
     
                System.out.println("total:" + total);
     
                s.close();
     
                c.close();
     
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return total;
        }
     
        public void add(Hero hero) {
     
            try {
                Class.forName("com.mysql.jdbc.Driver");
     
                Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8",
                        "root", "admin");
     
                String sql = "insert into hero values(null,?,?,?)";
                PreparedStatement ps = c.prepareStatement(sql);
                ps.setString(1, hero.name);
                ps.setFloat(2, hero.hp);
                ps.setInt(3, hero.damage);
     
                ps.execute();
     
                ResultSet rs = ps.getGeneratedKeys();
                if (rs.next()) {
                    int id = rs.getInt(1);
                    hero.id = id;
                }
     
                ps.close();
     
                c.close();
     
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
     
        public void update(Hero hero) {
            try {
                Class.forName("com.mysql.jdbc.Driver");
     
                Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8",
                        "root", "admin");
     
                String sql = "update hero set name= ?, hp = ? , damage = ? where id = ?";
                PreparedStatement ps = c.prepareStatement(sql);
                ps.setString(1, hero.name);
                ps.setFloat(2, hero.hp);
                ps.setInt(3, hero.damage);
                ps.setInt(4, hero.id);
     
                ps.execute();
     
                ps.close();
     
                c.close();
     
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
     
        }
     
        public void delete(int id) {
            try {
                Class.forName("com.mysql.jdbc.Driver");
     
                Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8",
                        "root", "admin");
     
                Statement s = c.createStatement();
     
                String sql = "delete from hero where id = " + id;
     
                s.execute(sql);
     
                s.close();
     
                c.close();
     
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
     
        public Hero get(int id) {
            Hero hero = null;
            try {
                Class.forName("com.mysql.jdbc.Driver");
     
                Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8",
                        "root", "admin");
     
                Statement s = c.createStatement();
     
                String sql = "select * from hero where id = " + id;
     
                ResultSet rs = s.executeQuery(sql);
     
                if (rs.next()) {
                    hero = new Hero();
                    String name = rs.getString(2);
                    float hp = rs.getFloat("hp");
                    int damage = rs.getInt(4);
                    hero.name = name;
                    hero.hp = hp;
                    hero.damage = damage;
                    hero.id = id;
                }
     
                s.close();
     
                c.close();
     
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return hero;
        }
     
        public List<Hero> list() {
            return list(0, Short.MAX_VALUE);
        }
     
        public List<Hero> list(int start, int count) {
            List<Hero> heros = new ArrayList<Hero>();
     
            try {
                Class.forName("com.mysql.jdbc.Driver");
     
                Connection c = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8",
                        "root", "admin");
     
                String sql = "select * from hero order by id desc limit ?,? ";
     
                PreparedStatement ps = c.prepareStatement(sql);
                ps.setInt(1, start);
                ps.setInt(2, count);
     
                ResultSet rs = ps.executeQuery();
     
                while (rs.next()) {
                    Hero hero = new Hero();
                    int id = rs.getInt(1);
                    String name = rs.getString(2);
                    float hp = rs.getFloat("hp");
                    int damage = rs.getInt(4);
                    hero.id = id;
                    hero.name = name;
                    hero.hp = hp;
                    hero.damage = damage;
                    heros.add(hero);
                }
     
                ps.close();
     
                c.close();
     
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return heros;
        }
     
    }
  • 只显示5条数据

    修改HeroListServlet
    int start = 0;
    int count = 5;
    List<Hero> heros = new HeroDAO().list(start, count);
    即表示只获取5条数据

    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 bean.Hero;
    import dao.HeroDAO;
     
    public class HeroListServlet extends HttpServlet {
     
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html; charset=UTF-8");
     
            int start = 0;
            int count = 5;
            List<Hero> heros = new HeroDAO().list(start, count);
     
            request.setAttribute("heros", heros);
     
            request.getRequestDispatcher("listHero.jsp").forward(request, response);
     
        }
    }
  • 下一页

    HeroListServlet : 
    通过参数获取start,如果浏览器没有传递参数,就设置为0。 
    根据start,计算next. next的值就是start+count.
    然后把next传递给listHero.jsp


    listHero.jsp
    在最后面增加一个超链
    <a href="?start=${next}">[下一页]</a>
    start=${next} 从服务器传递过来的next值

    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 bean.Hero;
    import dao.HeroDAO;
     
    public class HeroListServlet extends HttpServlet {
     
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html; charset=UTF-8");
     
            int start = 0;
            int count = 5;
     
            try {
                start = Integer.parseInt(request.getParameter("start"));
            } catch (NumberFormatException e) {
                // 当浏览器没有传参数start时
            }
     
            int next = start + count;
     
            List<Hero> heros = new HeroDAO().list(start, count);
     
            request.setAttribute("next", next);
     
            request.setAttribute("heros", heros);
     
            request.getRequestDispatcher("listHero.jsp").forward(request, response);
     
        }
    }
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8" import="java.util.*"%>
     
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
     
    <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>hp</td>
            <td>damage</td>
            <td>edit</td>
            <td>delete</td>
        </tr>
        <c:forEach items="${heros}" var="hero" varStatus="st">
            <tr>
                <td>${hero.id}</td>
                <td>${hero.name}</td>
                <td>${hero.hp}</td>
                <td>${hero.damage}</td>
                <td><a href="editHero?id=${hero.id}">edit</a></td>
                <td><a href="deleteHero?id=${hero.id}">delete</a></td>
            </tr>
        </c:forEach>
        <tr>
            <td colspan="6" align="center">
                <a href="?start=${next}">[下一页]</a>
            </td>
        </tr>
    </table>
  • 上一页

    HeroListServlet:
    根据start,计算pre. pre的值就是start-count.
    然后把pre传递给listHero.jsp

    listHero.jsp
    在下一页前增加一个超链
    <a href="?start=${pre}">[上一页]</a>

    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 bean.Hero;
    import dao.HeroDAO;
     
    public class HeroListServlet extends HttpServlet {
     
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html; charset=UTF-8");
     
            int start = 0;
            int count = 5;
     
            try {
                start = Integer.parseInt(request.getParameter("start"));
            } catch (NumberFormatException e) {
                // 当浏览器没有传参数start时
            }
     
            int next = start + count;
            int pre = start - count;
     
            request.setAttribute("next", next);
            request.setAttribute("pre", pre);
     
            List<Hero> heros = new HeroDAO().list(start, count);
            request.setAttribute("heros", heros);
     
            request.getRequestDispatcher("listHero.jsp").forward(request, response);
     
        }
    }
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8" import="java.util.*"%>
     
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
     
    <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>hp</td>
            <td>damage</td>
            <td>edit</td>
            <td>delete</td>
        </tr>
        <c:forEach items="${heros}" var="hero" varStatus="st">
            <tr>
                <td>${hero.id}</td>
                <td>${hero.name}</td>
                <td>${hero.hp}</td>
                <td>${hero.damage}</td>
                <td><a href="editHero?id=${hero.id}">edit</a></td>
                <td><a href="deleteHero?id=${hero.id}">delete</a></td>
            </tr>
        </c:forEach>
        <tr>
            <td colspan="6" align="center">
                <a href="?start=${pre}">[上一页]</a>
                <a href="?start=${next}">[下一页]</a>
            </td>
        </tr>
    </table>
  • 第一页

    只需要修改listHero.jsp即可
    增加 
    <a href="?start=0">[首  页]</a>
    因为首页的start永远都是0

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8" import="java.util.*"%>
     
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
     
    <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>hp</td>
            <td>damage</td>
            <td>edit</td>
            <td>delete</td>
        </tr>
        <c:forEach items="${heros}" var="hero" varStatus="st">
            <tr>
                <td>${hero.id}</td>
                <td>${hero.name}</td>
                <td>${hero.hp}</td>
                <td>${hero.damage}</td>
                <td><a href="editHero?id=${hero.id}">edit</a></td>
                <td><a href="deleteHero?id=${hero.id}">delete</a></td>
            </tr>
        </c:forEach>
        <tr>
            <td colspan="6" align="center">
                <a href="?start=0">[首  页]</a>
                <a href="?start=${pre}">[上一页]</a>
                <a href="?start=${next}">[下一页]</a>
            </td>
        </tr>
    </table>
  • 最后一页

    HeroListServlet:
    在HeroListServlet中计算last
    last需要根据总数total和每页有多少条数据count来计算得出。

    同时,还要看total是否能够整除count
    假设总数是50,是能够被5整除的,那么最后一页的开始就是45
    if (0 == total % count)
      last = total - count;

    假设总数是51,不能够被5整除的,那么最后一页的开始就是50
    last = total - total % count;

    listHero.jsp
    在下一页后增加一个超链
    <a href="?start=${last}">[末 页]</a>
    start=${last} 从服务器传递过来的last值

    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 bean.Hero;
    import dao.HeroDAO;
     
    public class HeroListServlet extends HttpServlet {
     
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html; charset=UTF-8");
     
            int start = 0;
            int count = 5;
     
            try {
                start = Integer.parseInt(request.getParameter("start"));
            } catch (NumberFormatException e) {
                // 当浏览器没有传参数start时
            }
     
            int next = start + count;
            int pre = start - count;
     
            int total = new HeroDAO().getTotal();
     
            int last;
            // 假设总数是50,是能够被5整除的,那么最后一页的开始就是45
            if (0 == total % count)
                last = total - count;
            // 假设总数是51,不能够被5整除的,那么最后一页的开始就是50
            else
                last = total - total % count;
     
            request.setAttribute("next", next);
            request.setAttribute("pre", pre);
            request.setAttribute("last", last);
     
            List<Hero> heros = new HeroDAO().list(start, count);
            request.setAttribute("heros", heros);
     
            request.getRequestDispatcher("listHero.jsp").forward(request, response);
     
        }
    }
    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8" import="java.util.*"%>
     
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
     
    <table align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>hp</td>
            <td>damage</td>
            <td>edit</td>
            <td>delete</td>
        </tr>
        <c:forEach items="${heros}" var="hero" varStatus="st">
            <tr>
                <td>${hero.id}</td>
                <td>${hero.name}</td>
                <td>${hero.hp}</td>
                <td>${hero.damage}</td>
                <td><a href="editHero?id=${hero.id}">edit</a></td>
                <td><a href="deleteHero?id=${hero.id}">delete</a></td>
            </tr>
        </c:forEach>
        <tr>
            <td colspan="6" align="center">
                <a href="?start=0">[首  页]</a>
                <a href="?start=${pre}">[上一页]</a>
                <a href="?start=${next}">[下一页]</a>
                <a href="?start=${last}">[末  页]</a>
            </td>
        </tr>
    </table>
  • 边界处理

    上一页,下一页有一个问题,
    如果在第一页点击上一页,就会看不到数据了,因为在第一页的时候,pre=-5,也就导致传递到serlvet的start=-5;
    同样的在最后一页的时候,点击下一页,也有类似的问题。

    解决办法是进行边界处理:
    pre = pre < 0 ? 0 : pre;
    如果pre是负数了,就使用0 

    next = next > last ? last : next;
    如果next大于last,就使用last
    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 bean.Hero;
    import dao.HeroDAO;
     
    public class HeroListServlet extends HttpServlet {
     
        protected void service(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html; charset=UTF-8");
     
            int start = 0;
            int count = 5;
     
            try {
                start = Integer.parseInt(request.getParameter("start"));
            } catch (NumberFormatException e) {
                // 当浏览器没有传参数start时
            }
     
            int next = start + count;
            int pre = start - count;
     
            int total = new HeroDAO().getTotal();
     
            int last;
            if (0 == total % count)
                last = total - count;
            else
                last = total - total % count;
     
            pre = pre < 0 ? 0 : pre;
            next = next > last ? last : next;
     
            request.setAttribute("next", next);
            request.setAttribute("pre", pre);
            request.setAttribute("last", last);
     
            List<Hero> heros = new HeroDAO().list(start, count);
            request.setAttribute("heros", heros);
     
            request.getRequestDispatcher("listHero.jsp").forward(request, response);
     
        }
    }
  • 套上Bootstrap

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8" import="java.util.*"%>
    <!DOCTYPE html>
    <script src="http://how2j.cn/study/js/jquery/2.0.0/jquery.min.js"></script>
    <link href="http://how2j.cn/study/css/bootstrap/3.3.6/bootstrap.min.css" rel="stylesheet">
    <script src="http://how2j.cn/study/js/bootstrap/3.3.6/bootstrap.min.js"></script>
         
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
     
    <script>
    $(function(){
        $("a").addClass("btn btn-default btn-xs");
         
    });
     
    </script>
    <table style="width:500px; margin:44px auto" class="table table-striped table-bordered table-hover  table-condensed" align='center' border='1' cellspacing='0'>
        <tr>
            <td>id</td>
            <td>name</td>
            <td>hp</td>
            <td>damage</td>
            <td>edit</td>
            <td>delete</td>
        </tr>
        <c:forEach items="${heros}" var="hero" varStatus="st">
            <tr>
                <td>${hero.id}</td>
                <td>${hero.name}</td>
                <td>${hero.hp}</td>
                <td>${hero.damage}</td>
                <td><a href="editHero?id=${hero.id}">编辑</a></td>
                <td><a href="deleteHero?id=${hero.id}">删除</a></td>
            </tr>
        </c:forEach>
     
    </table>
            <nav>
              <ul class="pager">
     
                <li><a href="?start=0">首  页</a></li>
                <li><a href="?start=${pre}">上一页</a></li>
                <li><a href="?start=${next}">下一页</a></li>
                <li><a href="?start=${last}">末  页</a></li>
              </ul>           
            </nav>


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值