MVC模式下用Servlet和jsp分页的HelloWord

MVC模式下分页:
马克-to-win:像淘宝百度这样的类似网页,我们用了很多很多。基本上就是输入查询条件以后,符合查询条件的结果可能会成千上万。我们不能一下子把所有这些结果都列出来,只能一次显示一页。当用户按下一页的时候,才会把下一页的内容列出来。这样不至于内存崩溃。要达到这样的效果,要用到分页技术。分页技术的核心思想就是把所有的结果放在一个ArrayList的当中(在我们的例子当中就是ArrayList ret)。马克-to-win:这个ArrayList连同相关参数比如一共有多少行(totalNumberOfRowsInDB),每页有多少行(pageSize),当前显示是第几页(currentPageNumber),一共有多少页(totalNumberOfPages),都放在Session当中。马克-to -win:返回到jsp后,再从Session当中取出所有这些数据,把它显示出来。注意这里数据库的每行数据都对应一个RegisterRow实例。把所有这些实例都放在ArrayList当中。如果你觉得全部把结果放在Session当中浪费空间的话,你甚至一次只放5页,当用户访问第5页的时候,你就再一次访问数据库,把数据放在Session当中。算法由你自己定义,据情况而定。当然,为简单起见,我们的例子是把所有符合条件的数据都给取出来。



例1.3.1:


home.jsp:

<%@ page contentType="text/html; charset=GBK" %>
<html>
<form method="post" action="MarkToWinServlet">
每页    <input type="text" name="pagesize" value="2">条
第    <input type="text" name="pageno" value="3">页
查id小于    <input type="text" name="id" value="8">
    <input type="submit" name="Submit" value="Submit">
</form>
<hr>
既然这是首页,像淘宝首页一样,这底下是首页的一些泛泛信息。
</html>





package com;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletHello1 extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("GBK");
        String pageno = request.getParameter("pageno");
        String pagesize = request.getParameter("pagesize");
        String id = request.getParameter("id");
        MyBean mb = new MyBean();
        try {
            mb.getData(pageno, pagesize, id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        request.getSession().setAttribute("myBean", mb);
        response.sendRedirect("show.jsp");
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
}



MyBean.java:

package com;
import java.sql.*;
import java.util.ArrayList;
public class MyBean {
    /* 下面一大堆变量,jsp中都需要取到,所以是类变量, 非局部 */
    private int totalNumberOfRowsInDB; // 数据表中总共存储了多少行
    private int pageSize;
    private int currentPageNumber;
    private int totalNumberOfPages;
    private int id;
    private ArrayList ret;

    public void getData(String curpage, String pagesizeS, String idS)
            throws Exception {
        Connection con;
        /*
         * MysqlConnectionPoolDataSource ds is always in the memory once it is
         * created becasue it is static..
         */
        con = DatabaseConn.getConnection();
        if (curpage == null) {
            currentPageNumber = 1; // 如果“PAGE”为NULL时将当前页面设置为1
        } else {
            currentPageNumber = Integer.parseInt(curpage);
            if (currentPageNumber < 1) { // 如果当前页小于1,将当前页设置为1
                currentPageNumber = 1;
            }
        }
        id = Integer.parseInt(idS);
        pageSize = Integer.parseInt(pagesizeS);

        int i = 0;
        ret = new ArrayList();
        Statement stm = null;
        ResultSet rs = null;

        stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_UPDATABLE);
        String sql = "select * from register where id<" + id;
        rs = stm.executeQuery(sql);
        rs.last();
        totalNumberOfRowsInDB = rs.getRow();
        totalNumberOfPages = (totalNumberOfRowsInDB + pageSize - 1) / pageSize;
        if (currentPageNumber > totalNumberOfPages)
            currentPageNumber = totalNumberOfPages;
        rs.absolute((currentPageNumber - 1) * pageSize + 1);
        while (i < pageSize && !rs.isAfterLast()) {
            RegisterRow rr = new RegisterRow();
            rr.setId(rs.getInt(1));
            rr.setName(rs.getString(2));
            rr.setAge(rs.getInt(3));
            ret.add(rr);
            rs.next();
            i++;
        }
        stm.close();
        con.close();
    }   
    public int getCurrentPageNumber() {
        return currentPageNumber;
    }
    public void setCurrentPageNumber(int currentPageNumber) {
        this.currentPageNumber = currentPageNumber;
    }
    public int getTotalNumberOfRowsInDB() {
        return totalNumberOfRowsInDB;
    }
    public int getPageSize() {
        return pageSize;
    }
    public int getTotalNumberOfPages() {
        return totalNumberOfPages;
    }
    public int getId() {
        return id;
    }
    public ArrayList getRet() {
        return ret;
    }
}





show.jsp:

<%@ page contentType="text/html; charset=GBK" import="java.sql.*"%>
<%@ page import="com.*,java.util.*"%>
<html>
<head>
<title>分页</title>
</head>
<body>
    <center>
        <%
            int totalNumberOfRowsInDB = 0;//数据库总共多少条记录the total number of the rows in the DB.
            int totalnumberOfPages = 0;//总共多少页the total number of the pages
            int currentpagenumber = 0;//当前是第几页currentpagenumber means current page.
            int i = 0;
            int id = 0;
            int pageSize = 0;
            MyBean myBean = ((MyBean) session.getAttribute("myBean"));
            if (myBean != null) {
                currentpagenumber = myBean.getCurrentPageNumber();
                id = myBean.getId();
                totalnumberOfPages = myBean.getTotalNumberOfPages();//计算出总的页数
                pageSize = myBean.getPageSize();
            }
        %>



        <form method="post" action="MarkToWinServlet">
            <br> 第<%=currentpagenumber%>页 共<%=totalnumberOfPages%>页
            <%
                if (currentpagenumber < totalnumberOfPages) {//如果当前页小于总页数
            %>
            <a
                href="MarkToWinServlet?pageno=<%=currentpagenumber + 1%>&pagesize=<%=pageSize%>&id=<%=id%>">下一页< /a>
            <%
                }
            %>
            <%
                if (currentpagenumber > 1)//如果当前页大于1
                {
            %>
            <a
                href="MarkToWinServlet?pageno=<%=currentpagenumber - 1%>&pagesize=<%=pageSize%>&id=<%=id%>">上一页< /a>
            <%
                }
            %>
            第<input type="text" name="pageno" value="<%=currentpagenumber%>">页,
            id小于<input name="id" value="<%=id%>">,每页共<input name="pagesize"
                value="<%=pageSize%>">条 <br> <input type="submit"
                name="Submit" value="Submit">
        </form>
像淘宝的搜寻一样,结果就显示在下面:
<hr>
        <table border="1">
            <tr>
                <td>ID</td>
                <td>名字</td>
                <td>年龄</td>
            </tr>
            <%
                if (totalnumberOfPages > 0) {
                    ArrayList ret = (ArrayList) myBean.getRet();
                    Iterator it = ret.iterator();
                    while (it.hasNext()) {
                        RegisterRow temp = (RegisterRow) it.next();
                        out.println("<TR>");
                        out.println("<td>" + temp.getId() + "</td>");
                        out.println("<td>" + temp.getName() + "</td>");
                        out.println("<td>" + temp.getAge() + "</td>");
                        out.println("</tr>");
                    }
                }
            %>
        </table>
        <br>
    </center>
</body>
</html>




RegisterRow.java:

package com;
public class RegisterRow {
    int id;
    String name;
    int age;
    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;
    }
}