Java MVC 分页实例

共4个文件

requestLogList.jsp

RequestInfoController.java

RequestInfoBean.java

RequestInfoService.java

 

1、requestLogList.jsp

功能点:

1.1、总个数:页面加载时COUNT(1)查询总数

1.2、总页数:总个数 %(取模)每页显示数量,如果正好结果为0时,总数除以每页显示数量为总页数,不能整除就是总数除以每页显示数量的加上1为总页数。

如:rs.getInt("TTL_CNT") % Constant.UNIT_CNT == 0 ? rs.getInt("TTL_CNT") / Constant.UNIT_CNT : rs.getInt("TTL_CNT") / Constant.UNIT_CNT + 1;

1.3、首页:点击 首页 时指向第一页

1.4、上一页:当前页 - 1(当前页保存在session当中)

1.5、上一页:当前页 + 1

1.6、尾页:总页数

1.7、直接访问:直接用js方式调用后台,传递页数

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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=UTF-8">
<title>访问日志查看</title>

<style type="text/css">
body
{
    margin-left: 100px;
}
table, th, td
{
    border: 1px solid black;
}
</style>
</head>
<body>
<%@ include file="top.jsp" %>
<h2>访问日志查询</h2>
<form action="/web01/requestInfoController" method="get">
<input type="submit" value="Search">
<input type="hidden" name="callTp" value="requestInfoList">
<br/>
<table>
    <tr>
        <th>NO</th>
        <th>characterEncoding</th>
        <th>contentType</th>
        <th>contextPath</th>
        <th>localAddr</th>
        <th>localName</th>
        <th>localPort</th>
        <th>method</th>
        <th>remoteAddr</th>
        <th>remoteHost</th>
        <th>remotePort</th>
        <th>remoteUser</th>
        <th>requestURI</th>
        <th>requestedSessionId</th>
        <th>locale</th>
        <th>regiDt</th>
    </tr>
    <c:forEach items="${requestScope.requestInfoList}" var="requestInfo">
    <tr>
        <td><c:out value="${requestInfo.rowSeq }" default=" "/></td>
        <td><c:out value="${requestInfo.characterEncoding }" default=" "/></td>
         <td><c:out value="${requestInfo.contentType }" default=" "/></td>
        <td><c:out value="${requestInfo.contextPath }" default=" "/></td>
        <td><c:out value="${requestInfo.localAddr }" default=" "/></td>
        <td><c:out value="${requestInfo.localName }" default=" "/></td>
        <td><c:out value="${requestInfo.localPort }" default=" "/></td>
        <td><c:out value="${requestInfo.method }" default=" "/></td>
        <td><c:out value="${requestInfo.remoteAddr }" default=" "/></td>
        <td><c:out value="${requestInfo.remoteHost }" default=" "/></td>
        <td><c:out value="${requestInfo.remotePort }" default=" "/></td>
        <td><c:out value="${requestInfo.remoteUser }" default=" "/></td>
        <td><c:out value="${requestInfo.requestURI }" default=" "/></td>
        <td><c:out value="${requestInfo.requestedSessionId }" default=" "/></td>
        <td><c:out value="${requestInfo.locale }" default=" "/></td>
        <td><c:out value="${requestInfo.regiDt }" default=" "/></td>
    </tr>
    </c:forEach>
</table>
</form>
总个数:<b>${sessionScope.ttlCnt}</b><br>
总页数:<b>${sessionScope.ttlPage}</b><br>
<a href="/web01/requestInfoController?callTp=requestInfoPageList&now_page_num=1">首页 | </a>  
<c:choose>
    <c:when test="${sessionScope.now_page_num==1}">
        上一页 
    </c:when>
    <c:otherwise>
        <a href="/web01/requestInfoController?callTp=requestInfoPageList&now_page_num=${sessionScope.now_page_num - 1}">上一页 | </a>  
    </c:otherwise>
</c:choose>
<c:choose>
    <c:when test="${sessionScope.now_page_num==sessionScope.ttlPage}">
        下一页  
    </c:when>
    <c:otherwise>
        <a href="/web01/requestInfoController?callTp=requestInfoPageList&now_page_num=${sessionScope.now_page_num + 1}">下一页  | </a>
    </c:otherwise>
</c:choose>
<a href="/web01/requestInfoController?callTp=requestInfoPageList&now_page_num=${sessionScope.ttlPage}"> 尾页</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<script type="text/javascript">
    function pageNum_Change(){
        var now_page_num = document.getElementById("now_page_num").value;
        window.open("/web01/requestInfoController?callTp=requestInfoPageList&now_page_num="+now_page_num, "_self");
    }
</script> 
直接访问:<input id="now_page_num" value="${sessionScope.now_page_num}"><input type="button" value="go" onclick="pageNum_Change()">
<%@ include file="bottom.jsp" %>
</body>
</html>

2、RequestInfoController.java

package com.test.system.controller;

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

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 javax.servlet.http.HttpSession;

import com.test.system.bean.RequestInfoBean;
import com.test.system.service.RequestInfoService;

/**
 * Servlet implementation class RequestInfoController
 */
@WebServlet("/RequestInfoController")
public class RequestInfoController extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RequestInfoController() {
        super();
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String callTp = request.getParameter("callTp");
        if (callTp.equals("requestInfoList")) {
            int now_page_num = 1;
            
            RequestInfoService ris = new RequestInfoService();
            ArrayList<RequestInfoBean> requestInfoList = ris.getRequestInfoList("", now_page_num);
            
            HttpSession session = request.getSession();

            // 当前页面(第一次查询时设置成第一页)
            session.setAttribute("now_page_num", now_page_num);
            
            // 总页数
            int ttlPage = ris.getTtlPage();
            session.setAttribute("ttlPage", ttlPage);

            // 获取总数 
            int ttlCnt = ris.getTtlCount();
            session.setAttribute("ttlCnt", ttlCnt);
            
            request.setAttribute("requestInfoList", requestInfoList);
            request.getRequestDispatcher("/view/requestLogList.jsp").forward(request, response);            
        } else if (callTp.equals("requestInfoPageList")) {
            RequestInfoService ris = new RequestInfoService();
            ArrayList<RequestInfoBean> requestInfoList = ris.getRequestInfoList("", Integer.parseInt(request.getParameter("now_page_num")));
            
            HttpSession session = request.getSession();

            session.setAttribute("now_page_num", request.getParameter("now_page_num"));
            
            // 总页数
            int ttlPage = ris.getTtlPage();
            session.setAttribute("ttlPage", ttlPage);            

            // 获取总数 
            int ttlCnt = ris.getTtlCount();
            session.setAttribute("ttlCnt", ttlCnt);
            
            request.setAttribute("requestInfoList", requestInfoList);
            request.getRequestDispatcher("/view/requestLogList.jsp").forward(request, response);                
        }

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}

3、RequestInfoBean.java

package com.test.system.bean;

public class RequestInfoBean {
    private String characterEncoding = "";
    private String contentType = "";
    private String contextPath = "";
    private String localAddr = "";
    private String localName = "";
    private int localPort = 0;
    private String method = "";
    private String remoteAddr = "";
    private String remoteHost = "";
    private int remotePort = 0;
    private String remoteUser = "";
    private String requestURI = "";
    private String requestedSessionId = "";
    private String locale = "";
    private String regiDt = "";    
    private int RowSeq = 0;
    
    public String getCharacterEncoding() {
        return characterEncoding;
    }

    public void setCharacterEncoding(String characterEncoding) {
        this.characterEncoding = characterEncoding;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public String getContextPath() {
        return contextPath;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    public String getLocalAddr() {
        return localAddr;
    }

    public void setLocalAddr(String localAddr) {
        this.localAddr = localAddr;
    }

    public String getLocalName() {
        return localName;
    }

    public void setLocalName(String localName) {
        this.localName = localName;
    }

    public int getLocalPort() {
        return localPort;
    }

    public void setLocalPort(int localPort) {
        this.localPort = localPort;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getRemoteAddr() {
        return remoteAddr;
    }

    public void setRemoteAddr(String remoteAddr) {
        this.remoteAddr = remoteAddr;
    }

    public String getRemoteHost() {
        return remoteHost;
    }

    public void setRemoteHost(String remoteHost) {
        this.remoteHost = remoteHost;
    }

    public int getRemotePort() {
        return remotePort;
    }

    public void setRemotePort(int remotePort) {
        this.remotePort = remotePort;
    }
    
    public String getRemoteUser() {
        return remoteUser;
    }

    public void setRemoteUser(String remoteUser) {
        this.remoteUser = remoteUser;
    }

    public String getRegiDt() {
        return regiDt;
    }

    public void setRegiDt(String regiDt) {
        this.regiDt = regiDt;
    }

    public String getRequestURI() {
        return requestURI;
    }

    public void setRequestURI(String requestURI) {
        this.requestURI = requestURI;
    }

    public String getRequestedSessionId() {
        return requestedSessionId;
    }

    public void setRequestedSessionId(String requestedSessionId) {
        this.requestedSessionId = requestedSessionId;
    }
    
    public String getLocale() {
        return locale;
    }

    public void setLocale(String locale) {
        this.locale = locale;
    }

    public int getRowSeq() {
        return RowSeq;
    }

    public void setRowSeq(int rowSeq) {
        RowSeq = rowSeq;
    }

}

4、RequestInfoService.java

UNIT_CNT:每页显示数量(常量提取到Constant.java中)

now_page_num:当天页面

package com.test.system.service;

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

import javax.servlet.http.HttpServletRequest;

import com.test.common.Constant;
import com.test.common.dao.BaseDao;
import com.test.system.bean.RequestInfoBean;

public class RequestInfoService {
    private int idx = 1;
    
    public RequestInfoService() {
    }

    // 保存request信息
    public void saveRequestInfo(HttpServletRequest request){
        Connection conn = null;
        PreparedStatement pstmt = null;    
        
        BaseDao baseDao = new BaseDao();
        try {
            conn = baseDao.dbConnection();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }
        
        StringBuffer sqlBf = new StringBuffer();
        sqlBf.setLength(0);
        
        sqlBf.append("INSERT INTO REQUEST_INFO (REQUEST_INFO_SEQ               \n");
        sqlBf.append("                        , CHARACTER_ENCODING             \n");
        sqlBf.append("                        , CONTENT_TYPE                   \n");
        sqlBf.append("                        , CONTEXT_PATH                   \n");
        sqlBf.append("                        , LOCAL_ADDR                     \n");
        sqlBf.append("                        , LOCAL_NAME                     \n");
        sqlBf.append("                        , LOCAL_PORT                     \n");
        sqlBf.append("                        , METHOD                         \n");
        sqlBf.append("                        , REMOTE_ADDR                    \n");
        sqlBf.append("                        , REMOTE_HOST                    \n");
        sqlBf.append("                        , REMOTE_PORT                    \n");
        sqlBf.append("                        , REMOTE_USER                    \n");
        sqlBf.append("                        , REQUEST_URI                    \n");
        sqlBf.append("                        , REQUESTED_SESSION_ID           \n");
        sqlBf.append("                        , LOCALE                         \n");
        sqlBf.append("                        , REGI_DT)                       \n");
        sqlBf.append("VALUES(SEQ_REQUEST_INFO.NEXTVAL                          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");
        sqlBf.append("     , ?          \n");        
        sqlBf.append("     , SYSDATE)   \n");

        System.out.println(sqlBf.toString());
        
        try {
            pstmt = conn.prepareStatement(sqlBf.toString());
            idx = 1;
            pstmt.setString(idx++, request.getCharacterEncoding());
            pstmt.setString(idx++, request.getContentType());
            pstmt.setString(idx++, request.getContextPath());
            pstmt.setString(idx++, request.getLocalAddr());
            pstmt.setString(idx++, request.getLocalName());
            pstmt.setInt(idx++, request.getLocalPort());
            pstmt.setString(idx++, request.getMethod());
            pstmt.setString(idx++, request.getRemoteAddr());
            pstmt.setString(idx++, request.getRemoteHost());
            pstmt.setInt(idx++, request.getRemotePort());
            pstmt.setString(idx++, request.getRemoteUser());
            pstmt.setString(idx++, request.getRequestURI());
            pstmt.setString(idx++, request.getRequestedSessionId());
            pstmt.setString(idx++, request.getLocale().toString());
            
            int i = pstmt.executeUpdate();
            if (i == 1) {
                System.out.println("##### save request success \n");
            } else {
                System.out.println("##### save request fail \n");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        try {
            baseDao.dbDisconnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }        
    }
    
    // 查询List
    public ArrayList<RequestInfoBean> getRequestInfoList(String str, int now_page_num){
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        ArrayList<RequestInfoBean> requestInfoList = new ArrayList<RequestInfoBean>();

        BaseDao baseDao = new BaseDao();
        try {
            conn = baseDao.dbConnection();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        StringBuffer sqlBf = new StringBuffer();
        sqlBf.setLength(0);

        sqlBf.append("SELECT  A.*                                                                     \n");
        sqlBf.append("FROM    (SELECT T1.*                                                            \n");
        sqlBf.append("              , ROWNUM AS ROW_SEQ                                               \n");
        sqlBf.append("         FROM   (SELECT  CHARACTER_ENCODING                                     \n");
        sqlBf.append("                       , CONTENT_TYPE                                           \n");
        sqlBf.append("                       , CONTEXT_PATH                                           \n");
        sqlBf.append("                       , LOCAL_ADDR                                             \n");
        sqlBf.append("                       , LOCAL_NAME                                             \n");
        sqlBf.append("                       , LOCAL_PORT                                             \n");
        sqlBf.append("                       , METHOD                                                 \n");
        sqlBf.append("                       , REMOTE_ADDR                                            \n");
        sqlBf.append("                       , REMOTE_HOST                                            \n");
        sqlBf.append("                       , REMOTE_PORT                                            \n");
        sqlBf.append("                       , REMOTE_USER                                            \n");
        sqlBf.append("                       , REQUEST_URI                                            \n");
        sqlBf.append("                       , REQUESTED_SESSION_ID                                   \n");
        sqlBf.append("                       , LOCALE                                                 \n");
        sqlBf.append("                       , TO_CHAR(REGI_DT, 'YYYY/MM/DD HH24:MI:SS')   REGI_DT    \n");
        sqlBf.append("                 FROM    REQUEST_INFO                                           \n");
        sqlBf.append("                 ORDER BY REQUEST_INFO_SEQ DESC                                 \n");
        sqlBf.append("                ) T1                                                            \n");
        sqlBf.append("         WHERE ROWNUM < (? * ?) + 1                                             \n");
        sqlBf.append("        ) A                                                                     \n");
        sqlBf.append("WHERE A.ROW_SEQ > (? * (? - 1))                                                  \n");
        sqlBf.append("ORDER BY A.ROW_SEQ                                                              \n");
        
        try {
            pstmt = conn.prepareStatement(sqlBf.toString());
            pstmt.setInt(1, Constant.UNIT_CNT);
            pstmt.setInt(2, now_page_num);
            pstmt.setInt(3, Constant.UNIT_CNT);
            pstmt.setInt(4, now_page_num);            

            rs = pstmt.executeQuery();
            while (rs.next()) {
                RequestInfoBean rib = new RequestInfoBean();
                
                rib.setCharacterEncoding(rs.getString("CHARACTER_ENCODING"));
                rib.setContentType(rs.getString("CONTENT_TYPE"));
                rib.setContextPath(rs.getString("CONTEXT_PATH"));
                rib.setLocalAddr(rs.getString("LOCAL_ADDR"));
                rib.setLocalName(rs.getString("LOCAL_NAME"));
                rib.setLocalPort(rs.getInt("LOCAL_PORT"));
                rib.setMethod(rs.getString("METHOD"));
                rib.setRemoteAddr(rs.getString("REMOTE_ADDR"));
                rib.setRemoteHost(rs.getString("REMOTE_HOST"));
                rib.setRemotePort(rs.getInt("REMOTE_PORT"));
                rib.setRemoteUser(rs.getString("REMOTE_USER"));
                rib.setRequestURI(rs.getString("REQUEST_URI"));
                rib.setRequestedSessionId(rs.getString("REQUESTED_SESSION_ID"));
                rib.setLocale(rs.getString("LOCALE"));
                rib.setRegiDt(rs.getString("REGI_DT"));
                rib.setRowSeq(rs.getInt("ROW_SEQ"));
                
                requestInfoList.add(rib);
            }            
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        try {
            baseDao.dbDisconnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        return requestInfoList;
    }    
    
    // 获取记录总数
    public int getTtlCount(){
        int ttlCnt = 0;   // Total Count
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        BaseDao baseDao = new BaseDao();
        try {
            conn = baseDao.dbConnection();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        StringBuffer sqlBf = new StringBuffer();
        sqlBf.setLength(0);
        
        sqlBf.append("SELECT  COUNT(1)    TTL_CNT          \n");
        sqlBf.append("FROM    REQUEST_INFO                 \n");

        try {
            pstmt = conn.prepareStatement(sqlBf.toString());

            rs = pstmt.executeQuery();
            if (rs.next()) {
                ttlCnt = rs.getInt("TTL_CNT");
            }            
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        try {
            baseDao.dbDisconnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }        
        
        return ttlCnt;
    }
    
    // 获取页数
    public int getTtlPage(){
        int ttlPage = 0;   // Total Count
        
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        BaseDao baseDao = new BaseDao();
        try {
            conn = baseDao.dbConnection();
        } catch (SQLException e1) {
            e1.printStackTrace();
        }

        StringBuffer sqlBf = new StringBuffer();
        sqlBf.setLength(0);
        
        sqlBf.append("SELECT  COUNT(1)    TTL_CNT          \n");
        sqlBf.append("FROM    REQUEST_INFO                 \n");

        try {
            pstmt = conn.prepareStatement(sqlBf.toString());

            rs = pstmt.executeQuery();
            if (rs.next()) {
                ttlPage = rs.getInt("TTL_CNT") % Constant.UNIT_CNT == 0 ? rs.getInt("TTL_CNT") / Constant.UNIT_CNT : rs.getInt("TTL_CNT") / Constant.UNIT_CNT + 1;
            }            
        } catch (SQLException e) {
            e.printStackTrace();
        }
        
        try {
            baseDao.dbDisconnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }        
        
        return ttlPage;
    }    
}

 

测试结果:

posted @ 2015-09-22 15:06  bada130  阅读(401)  评论(0编辑  收藏  举报