1.Dao层操作数据库的方法(MessageDao.java)
设置每页显示的最大留言条数:
private final int MAX_SIZE = 2; // 每页显示的最大留言数
从数据库读取留言的总条数,计算出总页数:
public int getCountPage() throws SQLException { Connection conn = JdbcUtils.GetConnection(); PreparedStatement ps = null; ResultSet rs = null; int countPage = 0; int total = 0; String sql = "SELECT COUNT(*) AS num FROM message"; //查询记录条数,然后把查询结果另外起一个别名,叫做num try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); if (rs.next()) { total = rs.getInt("num"); //total为留言的总条数 } // 总页数=总条数/每页显示最大留言数,能除尽时直接取结果,不能除尽时,结果加1,多加一页来显示 countPage = (total % MAX_SIZE == 0 ? total / MAX_SIZE : total / MAX_SIZE + 1); if (countPage != 0) return countPage; return countPage + 1; //没有第0页,所以加1 } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } finally { JdbcUtils.Free(rs, ps, conn); } }
读取留言,存入List:
public List<Message> getMessage(int currentPage) throws SQLException { //currentPage为当前页数 Connection conn = JdbcUtils.GetConnection(); List<Message> messageList = new ArrayList<Message>(); PreparedStatement ps = null; ResultSet rs = null; String sql = "SELECT * FROM user,message WHERE user.userId=message.userId order by messageId desc LIMIT ?,?"; /* * order by id desc --按id列大小降序排列,不加desc就是升序排列 * LIMIT 100,15--从查询的结果中第100条开始取出15条数据 */ try { ps = conn.prepareStatement(sql); ps.setInt(1, (currentPage - 1) * MAX_SIZE); ps.setInt(2, MAX_SIZE); rs = ps.executeQuery(); while (rs.next()) { Message message = new Message(); message.setMessageId(rs.getInt("messageId")); message.setUserName(rs.getString("userName")); message.setTitle(rs.getString("title")); message.setContent(rs.getString("content")); message.setTime(rs.getString("time")); messageList.add(message); //将找出的数据存入messageList } } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } finally { JdbcUtils.Free(rs, ps, conn); } return messageList; }
private void getMessage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException { MessageService messageService = new MessageService(); //从jsp页面获取当前页数 int currentPage = Integer.parseInt(request.getParameter("currentPage")); //查询数据库获得数据计算出总页数 int countPage = messageService.getCountPage(); //将当前页数,总页数,以及找出的数据返回给jsp页面 request.setAttribute("countPage", countPage); request.setAttribute("currentPage", currentPage); request.setAttribute("messages", messageService.getMessage(currentPage)); request.getRequestDispatcher("getMessage.jsp").forward(request, response); }
<a href="MessageServlet?status=getMessage¤tPage=1">查看留言</a>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!--引入JSTL核心标记库的taglib指令--> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <% 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>显示留言</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <a href="success.jsp">返回</a> <table border="1"> <tr> <th width="150">留言数</th> <th width="150">主题</th> <th width="150">内容</th> <th width="150">留言时间</th> <th width="150">留言人</th> <th width="150">删除选项</th> </tr> <c:forEach items="${requestScope.messages}" var="message"> <tr> <td width="100">${message.messageId}</td> <td width="100">${message.title}</td> <td width="500">${message.content}</td> <td width="200">${message.time}</td> <td width="100">${message.userName}</td> <td width="100"> <form action="MessageServlet?status=deleteMessage" method="post"> <input type="hidden" value="${message.messageId}" name="messageId"> <input type="submit" value="删除" onclick="return confirm('确定删除吗?')"> </form></td> </tr> </c:forEach> </table> <center> <div> 第${requestScope.currentPage}页/共${requestScope.countPage}页 <a href="${pageContext.request.contextPath}/MessageServlet?status=getMessage¤ttPage=1">首页</a><span> </span> <c:choose> <c:when test="${requestScope.currentPage==1}"> 上一页 </c:when> <c:otherwise> <a href="${pageContext.request.contextPath}/MessageServlet?status=getMessage<span style="font-family: Arial, Helvetica, sans-serif;">¤ttPage</span>=${requestScope.currentPage-1}">上一页</a> </c:otherwise> </c:choose> <%--计算begin和end --%> <c:choose> <%--如果总页数不足10,那么就把所有的页都显示出来 --%> <c:when test="${requestScope.countPage<=10}"> <c:set var="begin" value="1" /> <c:set var="end" value="${requestScope.countPage}" /> </c:when> <c:otherwise> <%--如果总页数大于10,通过公式计算出begin和end --%> <c:set var="begin" value="${requestScope.currentPage-5}" /> <c:set var="end" value="${requestScope.currentPage+4}" /> <%--头溢出 --%> <c:if test="${begin<1}"> <c:set var="begin" value="1"></c:set> <c:set var="end" value="10"></c:set> </c:if> <%--尾溢出 --%> <c:if test="${end>requestScope.countPage}"> <c:set var="begin" value="${requestScope.countPage - 9}"></c:set> <c:set var="end" value="${requestScope.countPage}"></c:set> </c:if> </c:otherwise> </c:choose> <%--循环显示页码列表 --%> <c:forEach var="i" begin="${begin}" end="${end}"> <c:choose> <c:when test="${i == requestScope.currentPage}"> [${i}] </c:when> <c:otherwise> <a href="<c:url value ='/MessageServlet?status=getMessage ¤tPage=${i}'/>">[${i}]</a> </c:otherwise> </c:choose> </c:forEach> <c:choose> <c:when test="${requestScope.currentPage==requestScope.countPage}"> 下一页 </c:when> <c:otherwise> <a href="${pageContext.request.contextPath}/MessageServlet?status=getMessage¤tPage=${requestScope.currentPage+1}"> 下一页</a> </c:otherwise> </c:choose> <span> </span><a href="${pageContext.request.contextPath}/MessageServlet?status=getMessage¤tPage=${requestScope.countPage}">尾页</a> </div> </center> </body> </html>
1.向servlet请求查看留言的功能时,需要传递参数currentPage,告诉servlet当前页数是多少。
2.需要引入JSP标准标签库,在getMessage.jsp页面加上这句话:
<!--引入JSTL核心标记库的taglib指令--> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:forEach items="${requestScope.messages}" var="message"></c:forEach>
<c:choose>相当于Java的switch,<c:when>相当于Java的case。<c:otherwise>相当于Java的default。当test中的表达式结果为true时,则会执行本体内容;如果为false,则跳到下一个<c:when>。
语法规则:
<c:when>和<c:otherwise>不能单独使用,它们必须位于<c:choose>父标签中。
在<c:choose>标签中可以包含一个或多个<c:when>标签。
在<c:choose>标签中可以不包含<c:otherwise>标签。
在<c:choose>标签中如果同时包含<c:when>和<c:otherwise>标签,那么<c:otherwise>必须位于<c:when>标签之后。
<c:choose> <c:when test="${requestScope.currentPage==1}"> 上一页 </c:when> <c:otherwise> <a href="${pageContext.request.contextPath}/MessageServlet?status=getMessage¤tPage=${requestScope.currentPage-1}">上一页</a> </c:otherwise> </c:choose>
<c:set var="begin" value="1" /> <c:set var="end" value="${requestScope.countPage}" />这里将变量begin的值设为1,变量end的值设为读取的currentPage的值
<c:if> 作判断用,标签必须要有test属性,当test中的表达式结果为true时,则会执行本体内容;如果为false,则不会执行
<c:if test="${begin<1}"> <c:set var="begin" value="1"></c:set> <c:set var="end" value="10"></c:set> </c:if>
这里判断begin的值是否小于1
${requestScope.currentPage}等价于
< %=request.getAttribute(“currentPage”)% >
从request范围中取出currentPage变量的值
${pageContext.request.contextPath}pageContext:JSP 页的上下文。它可以用于访问 JSP 隐式对象,如请求、响应、会话、输出、servletContext 等。例如,${pageContext.response} 为页面的响应对象赋值。
${pageContext.request.contextPath}样是通过 get方法去取的,先pageContext.getRequest()得到HttpServletRequest对象,再调用 HttpServletRequest的getContextPath方法
作用是取出部署的应用程序名,这样不管如何部署,所用路径都是正确的。
El表达式的写法:${pageContext.request.contextPath}
jsp的写法:<%=request.getContextPath()%>
相关知识参考链接:
http://elf8848.iteye.com/blog/245559