Java web分页技术(jsp+servlet+Dao+javabean)

一世执手 提交于 2020-03-14 04:25:41

经过两天的折腾,终于自己搞定一个完整的分页项目。。。。。。眼都要瞎了。。。。。。有用信息全部展开了,整体截图如下:

1:DBC.java(数据库连接封装类)

package com.common.db;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Connection;  
import java.sql.PreparedStatement;  
import java.sql.Statement;  
public class DBC {
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://localhost:3306/StaffRec";
    private static String username = "root";
    private static String password = "root";
    static {
        try {
            /**
             * 加载驱动
             */
            Class.forName(driver);
        }catch(Exception ex) {
            ex.printStackTrace();
        }
    }
    public static Connection getConnection() {
        /**
         * 创建连接对象
         */
        Connection conn=null;
        try {
            conn=(Connection) DriverManager.getConnection(url,username,password);
        }catch(Exception ex) {
            ex.printStackTrace();
        }
        return conn;
    }
    /**
     * 关闭相关流
     */
    public static void close(ResultSet rs,Statement st,Connection conn) {
        try {
            if(rs!=null) {
                rs.close();
            }
            if(st!=null) {
                st.close();
            }
            if(conn!=null) {
                conn.close();
            }
        }catch(SQLException e) {
            e.printStackTrace();
        }
    }
    public static void closePst(ResultSet rs,PreparedStatement pst,Connection conn) {
        try {
            if(rs!=null) {
                rs.close();
            }
            if(pst!=null) {
                pst.close();
            }
            if(conn!=null) {
                conn.close();
            }
        }catch(SQLException e) {
            e.printStackTrace();
        }
    }


}
View Code

2:Rec.java(和数据库表对应的实体类,需要显示的内容)

package javabean;

public class Rec {
    private int id;  
    private String rec;  
    private String reced;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getRec() {
        return rec;
    }
    public void setRec(String rec) {
        this.rec = rec;
    }
    public String getReced() {
        return reced;
    }
    public void setReced(String reced) {
        this.reced = reced;
    }  

}
View Code

3:PageModel.java(完整的分页模型!!!)

package javabean;

import java.util.List;  

/** 
 * 封装分页信息 
 * @author Administrator 
 * 
 */  
public class PageModel<E> {  
    //结果集  
    private List<E> list;  
    //查询记录数  
    private int totalRecords;   
    //每页多少条数据  
    private int pageSize;  
    //第几页  
    private int pageNo;  
      
    /** 
     * 总页数 
     * @return 
     */  
    public int getTotalPages() {  
        return (totalRecords + pageSize - 1) / pageSize;  
    }  
      
    /** 
     * 取得首页 
     * @return 
     */  
    public int getTopPageNo() {  
        return 1;  
    }  
      
    /** 
     * 上一页 
     * @return 
     */  
    public int getPreviousPageNo() {  
        if (pageNo <= 1) {  
            return 1;  
        }  
        return pageNo - 1;  
    }  
      
    /** 
     * 下一页 
     * @return 
     */  
    public int getNextPageNo() {  
        if (pageNo >= getBottomPageNo()) {  
            return getBottomPageNo();  
        }  
        return pageNo + 1;    
    }  
      
    /** 
     * 取得尾页 
     * @return 
     */  
    public int getBottomPageNo() {  
        return getTotalPages();  
    }  
    /**
     * get set函数  
     * @return
     */
    public List<E> getList() {  
        return list;  
    }  
  
    public void setList(List<E> list) {  
        this.list = list;  
    }  
  
    public int getTotalRecords() {  
        return totalRecords;  
    }  
  
    public void setTotalRecords(int totalRecords) {  
        this.totalRecords = totalRecords;  
    }  
  
    public int getPageSize() {  
        return pageSize;  
    }  
  
    public void setPageSize(int pageSize) {  
        this.pageSize = pageSize;  
    }  
  
    public int getPageNo() {  
        return pageNo;  
    }  
  
    public void setPageNo(int pageNo) {  
        this.pageNo = pageNo;  
    }  
}  
View Code

4:RecommentDao.java(业务逻辑层,操作数据库等操作,返回值为PageModel对象)

package com.common.page;

import java.sql.Connection;  
import java.sql.PreparedStatement;  
import java.sql.ResultSet;  
import java.sql.SQLException;  
import java.util.ArrayList;  
import java.util.List;  
  
import com.common.db.DBC;  
import javabean.*;
  
public class RecommentDao {  
    public PageModel<Rec> findData(String pageNo,String pageSize){  //去掉了static
        PageModel<Rec> pageModel=null; //移到这儿
        Connection conn=DBC.getConnection();
        String sql="select * from recommend limit ?,?";  
        //PageModel pageModel=null; 
        PreparedStatement pst=null;  
        ResultSet rs=null;  
        Rec rec=null;  
        List<Rec> list=new ArrayList<Rec>();  
        try {  
              pst=conn.prepareStatement(sql); 
              //pstm.setInt(1, (pageNo-1)*pageSize); 
              //pstm.setInt(2, pageNo*pageSize);
              pst.setInt(1, (Integer.parseInt(pageNo)-1)*Integer.parseInt(pageSize));  
              pst.setInt(2, Integer.parseInt(pageSize));  
              rs=pst.executeQuery();
              while(rs.next()){  
                  rec=new Rec();  
                  rec.setId(rs.getInt("id"));  
                  rec.setRec(rs.getString("rec"));  
                  rec.setReced(rs.getString("reced"));  
                  list.add(rec);  
               }  
               ResultSet rs2=pst.executeQuery("select count(*) from recommend");  
               int total=0;  
               if(rs2.next()){  
                   total=rs2.getInt(1);//总的数据条数 
               }  
                pageModel=new PageModel<Rec>();  
                pageModel.setPageNo(Integer.parseInt(pageNo));  
                pageModel.setPageSize(Integer.parseInt(pageSize));  
                pageModel.setTotalRecords(total);  
                pageModel.setList(list); 
            } catch (SQLException e) {  
                e.printStackTrace();  
            }finally{  
               DBC.closePst(rs, pst, conn); 
            } 
        return pageModel;  
    }  
      
    /*public static void main(String[] args) { 
        RecommentDao client=new RecommentDao();
        PageModel<Rec> pageModel=client.findData("2","4");  
        List<Rec> list=pageModel.getList();  
        for(Rec a:list){  
            System.out.print("ID:"+a.getId()+",推荐人:"+a.getRec()+",被推荐人:"+a.getReced());  
            System.out.println();  
        }  
        System.out.print("当前页:"+pageModel.getPageNo()+" ");  
        System.out.print("共"+pageModel.getTotalPages()+"页  ");  
        System.out.print("首页:"+pageModel.getTopPageNo()+" ");  
        System.out.print("上一页:"+pageModel.getPreviousPageNo()+" ");  
        System.out.print("下一页:"+pageModel.getNextPageNo()+" ");  
        System.out.print("尾页:"+pageModel.getBottomPageNo()+" ");  
        System.out.print("共"+pageModel.getTotalRecords()+"条记录");  
        System.out.println();  
    }*/
  
}  
View Code

5:recomment.java(控制层servlet,连接前端和业务层,获得PageModel对象后跳转到新页面展示分页数据信息)

package servlet;

import java.io.IOException;

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

import com.common.page.RecommentDao;
import javabean.PageModel;
import javabean.Rec;

/**
 * Servlet implementation class recomment
 */
@WebServlet("/recomment")
public class recomment extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public recomment() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());
        this.doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //System.out.println("+1");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String pageSize = request.getParameter("pageSize");// 每页显示行数
        String pageNo = request.getParameter("pageNo");// 当前显示页次
        if (pageSize == null) {// 为空时设置默认页大小为10
            pageSize = "10";
        }
        if (pageNo == null) {// 为空时设置默认为第1页
            pageNo = "1";
        }
        //System.out.println("pageNo="+pageNo+"pageSize="+pageSize);
        // 保存分页参数,传递给下一个页面
        request.setAttribute("pageSize", pageSize);
        request.setAttribute("pageNo", pageNo);
        //新建Dao对象,获取pageModel
        RecommentDao client=new RecommentDao();
        PageModel<Rec> pageModel=client.findData(pageNo,pageSize); 
        request.setAttribute("pageModel", pageModel);//前端获取这个值
        request.getRequestDispatcher("../Result.jsp").forward(request, response);
    }

}
View Code

6:index.jsp(程序入口,调到servlet层)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<a href="/haha/servlet/recomment">查看所有推荐信息</a>
</body>
</html>
View Code

7:result.jsp(展示分页结果的页面)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.util.*" %>
<%@ page import="com.common.page.*" %>
<%@ page import="javabean.*" %>

<%
String pageSize = (String) request.getAttribute("pageSize");
String pageNo = (String) request.getAttribute("pageNo");
PageModel<Rec> pageModel=(PageModel<Rec>) request.getAttribute("pageModel");
List<Rec> list=pageModel.getList();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- <script src="/haha/js/jquery.min.js" type="text/javascript"></script> -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table align="center" >
        <tr>
            <td align="center" colspan="3">
                <h2>所有信息</h2>
            </td>
        </tr>
        <tr align="center">
            <td><b>ID</b></td>
            <td><b>推荐人</b></td>
            <td><b>推荐号码</b></td>
        </tr> 
         
  <%
    if(list==null||list.size()<1){
        %><p align="center">还没有任何数据!</p>
    <%}else{
        for(Rec rec:list){
  %>   
  <tr>
     <td><%=rec.getId() %></td>
     <td><%=rec.getRec().substring(0, 3)+"****"+rec.getRec().substring(7, 11) %></td>
     <td><%=rec.getReced() %></td>     
  </tr>
  <%
        }
    }    
  %>
 
</table>
    <form name="form1" action="/haha/servlet/recomment" method="post">
        <TABLE border="0" width="100%" >
            <TR>
                <TD align="left"><a>每页条数</a>
                <select name="pageSize"
                    onchange="document.all.pageNo.value='1';document.all.form1.submit();">
                    <option value="10" <%if(pageSize.equals("10")){%>
                        selected="selected" <%}%>>10</option>
                    <option value="20" <%if(pageSize.equals("20")){%>
                        selected="selected" <%}%>>20</option>
                    <option value="30" <%if(pageSize.equals("30")){%>
                        selected="selected" <%}%>>30</option>
                </select></TD>
                <TD align="right">
                <a
                    href="javascript:document.all.pageNo.value='<%= pageModel.getTopPageNo() %>';document.all.form1.submit();">首页</a>
                <a
                    href="javascript:document.all.pageNo.value='<%= pageModel.getPreviousPageNo() %>';document.all.form1.submit();">上一页</a>
                <a
                    href="javascript:document.all.pageNo.value='<%= pageModel.getNextPageNo()%>';document.all.form1.submit();">下一页</a>
                <a
                    href="javascript:document.all.pageNo.value='<%= pageModel.getBottomPageNo()%>';document.all.form1.submit();">尾页</a>
                <a>第</a>
                <select name="pageNo" onchange="document.all.form1.submit();">
                    <%
                        int pageCount = pageModel.getTotalPages();
                    %>
                    <%
                        for (int i = 1; i <= pageCount; i++) {
                    %>
                    <option value="<%=i%>" <%if(pageNo.equals(i+"")){%>
                        selected="selected" <%}%>><%=i%></option>
                    <%
                        }
                    %>
                </select><a>页</a></TD>
            </TR>
        </TABLE>

        </form>
</body>
</html>
View Code

8:配置web.xml(主要是针对servlet进行配置)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>haha</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>recomment</servlet-name>
    <servlet-class>servlet.recomment</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>recomment</servlet-name>
    <url-pattern>/servlet/recomment</url-pattern>
  </servlet-mapping>
  
  <session-config>
    <session-timeout>720</session-timeout>
  </session-config>
</web-app>
View Code

9:结果展示

运行index.jsp

单击:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!