JSP页面分页显示数据

一、源代码(这里以一个Java web的留言板项目为例):

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;
	}

servlet处理:

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>


显示留言的JSP页面:

<%@ 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="删除" οnclick="return confirm('确定删除吗?')">
					</form></td>
			</tr>
		</c:forEach>
	</table>
	
	<center>
	<div>
		第${requestScope.currentPage}页/共${requestScope.countPage}页 <a
			href="${pageContext.request.contextPath}/MessageServlet?status=getMessage&currenttPage=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;">&currenttPage</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
					&currentPage=${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&currentPage=${requestScope.currentPage+1}"> 下一页</a>
			</c:otherwise>
		</c:choose>
		<span> </span><a
			href="${pageContext.request.contextPath}/MessageServlet?status=getMessage&currentPage=${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>来迭代整个结果集,itms为结果集,var为每一条结果
<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&currentPage=${requestScope.currentPage-1}">上一页</a>
	</c:otherwise>
</c:choose>


用<c: set />来设置变量的值

<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


3.EL表达式,简化书写:
${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

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
自己收集的jsp分页代码。对于北大青鸟Y2的学员可能有用吧。自己也在做这个项目。这里有增、删、该、查加分页。有上一页、下一页、首页、尾页、第几页、还有带数字和点的分页。可以说是非常好的分页代码。想要的朋友自己处下载 <%@ page contentType="text/html; charset=GB2312" language="java" import="java.sql.*" errorPage="" %> <%@ page import="java.io.*" %> <%@ page import="java.util.*" %> <% java.sql.Connection sqlCon; //数据库连接对象 java.sql.Statement sqlStmt; //SQL语句对象 ResultSet sqlRst=null; //java.sql.ResultSet sqlRst; //结果集对象 java.lang.String strCon; //数据库连接字符串 java.lang.String strSQL; //SQL语句 int intPageSize; //一页显示的记录数 int intRowCount; //记录总数 int intPageCount; //总页数 int intPage; //待显示页码 java.lang.String strPage; int i; //设置一页显示的记录数 intPageSize = 2; //取得待显示页码 strPage = request.getParameter("page"); if(strPage==null){ //表明在QueryString中没有page这一个参数,此时显示第一页数据 intPage = 1; } else{ //将字符串转换成整型 intPage = java.lang.Integer.parseInt(strPage); if(intPage<1) intPage = 1; } %><% String DBUser="sa"; String DBPassword="88029712"; //String DBServer="127.0.0.1"zjprice; String DBUrl="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs"; //创建语句对象 //Class.forName("org.gjt.mm.mysql.Driver").newInstance(); Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); sqlCon=java.sql.DriverManager.getConnection(DBUrl,DBUser,DBPassword); sqlStmt=sqlCon.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY); //执行SQL语句并获取结果集 String sql=null; String search=""; String ToPage=request.getParameter("ToPage"); if(request.getParameter("search")!=null &&!request.getParameter("search").equals("")) {search=new String(request.getParameter("search").trim().getBytes("8859_1")); } sql="select top 50 au_id,au_lname from authors "; /*sql="select*from ta,tb where id like'%"+search+"%'"; sql=sql+"or title like'%"+search+"%'"; sql=sql+"or time like'%"+search+"%'"; sql=sql+"or con like'%"+search+"%'"; sql=sql+"order by id";*/ sqlRst=sqlStmt.executeQuery(sql); //获取记录总数 sqlRst.last(); intRowCount = sqlRst.getRow(); //记算总页数 intPageCount = (intRowCount+intPageSize-1) / intPageSize; //调整待显示的页码 if(intPage>intPageCount) intPage = intPageCount; %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <title>test</title> </head> <body> <table border="1" cellspacing="0" cellpadding="0"> <tr> <th>标题id</th> <th>内容表</th> </tr> <% if(intPageCount>0) { //将记录指针定位到待显示页的第一条记录上 sqlRst.absolute((intPage-1) * intPageSize + 1); //显示数据 i = 0; while(i<intPageSize && !sqlRst.isAfterLast()){ %> <tr> <td> <%=sqlRst.getString(1)%> </td> <td> <%=sqlRst.getString(2)%> </td> </tr> <% sqlRst.next(); i++; } } %> <tr><td colspan="8">共有<font color=red><%= intRowCount %></font>条记录 当前<font color=red><%=intPage%>/<%=intPageCount%></font>页  <% if(intPageCount > 1){ %> <% if(intPage !=0){%> <a href="mysqlpage.jsp">首页</a> <%}if(intPage != 1){%><a href="mysqlpage.jsp?page=<%= intPage - 1 %>">上一页</a> <%}if(intPage<intPageCount){%><a href="mysqlpage.jsp?page=<%=intPage+1%>">下一页</a><%}%> <a href="mysqlpage.jsp?page=<%= intPageCount %>">尾页</a> <% } %>跳转到 <select name="page" onChange="javascript:this.form.submit();"> <% for(i=1;i<=intPageCount;i++){%> <option value="<%= i %>" <% if(intPage == i){%>selected<% } %>><%= i %></option> <% } %> </select>页 <%int m,n,p; %> <%if (intPage>1){ if(intPage-2>0){ m=intPage-2;} else { m=1;} if(intPage+2<intPageCount){ n=intPage+2;} else{ n=intPageCount; }%> 转到页码: [ <% for(p=m;p<=n;p++) { if (intPage==p){ %> <font color="black"><%=p %></font> <% } else{%> <a href=?page=<%=p %>><font color=red>[<%=p %>]</font></a> <% } }%>]<%} %> </td></tr> </table> </body> </html> <% //关闭结果集 sqlRst.close(); //关闭SQL语句对象 sqlStmt.close(); //关闭数据库 sqlCon.close(); %>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值