JSP将后台返回的数据显示并分页

<span style="font-size:18px;"><%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@page import="java.util.Iterator" import="java.util.List" 
	import="com.bbs.pojo.*" import="org.springframework.context.ApplicationContext" import="org.springframework.context.support.ClassPathXmlApplicationContext"
	%>

<%!
	public static final int PAGESIZE = 20;    //每页行数
	int pageCount;
	int curPage = 1;
%>
<%
	//一页放20个
	try{
		List<Topic> topiclist = (List<Topic>)session.getAttribute("topiclist");
		//out.print(((Topic)topiclist.get(1)).getContent());
		
		//记录总行数
		int size = topiclist.size();
		
		//总页数
		pageCount = (size%PAGESIZE==0)?(size/PAGESIZE):(size/PAGESIZE+1);
		
		//获取当前页数
		String tmp = request.getParameter("curPage");
		
		//初始化页数
		if(tmp==null){
			tmp="1";
		}
		//out.print(tmp);
		curPage = Integer.parseInt(tmp);
		//调整页数
		if(curPage>=pageCount){    
			curPage = pageCount;
		} 
	
		int count = 0;
		Iterator<Topic> it = topiclist.iterator();
		
		//out.print("记录总数:"+topiclist.size()+"<br>");
		//将记录指针定位到待显示页的第一条记录上
		ApplicationContext act = new ClassPathXmlApplicationContext("applicationContext.xml");
		UserDAO ud =(UserDAO)act.getBean("UserDAO");
		ModuleDAO md =(ModuleDAO)act.getBean("ModuleDAO");
		while(it.hasNext()){
			//用于定位每页打印开始位置
			for(int i=1;i <= topiclist.size();i++){
				if(i == (curPage-1)*PAGESIZE+1){
					//out.print((curPage-1)*PAGESIZE+1);
					break;
				}
				it.next();
			}
			
			Topic topic=(Topic)it.next();
			User u=ud.findById(topic.getUser().getId());
			Module module=md.findById(topic.getModule().getId());
			count++;
			%>
		<div class="templatemo-content-widget white-bg templatemo-overflow-hidden" >
             <table style=" 900px">
                
               
			<tr>
				<td rowspan="2"><img width="110px" height="110px" src="<%=u.getHeadImg() %>"></td>
				<td colspan="3"><span style=" 500px;height: 60px"><a href="findPostAction?topicId=<%=topic.getId()%>" style="font-size: 40px;color: red"><%=topic.getContent() %></a></span></td>
				<td><p><span>浏览次数:<font color="orange" size="15px"><%=topic.getPostCount() %></font></span></p></td>
			</tr>
			
			<tr>
				<td><a href="findTopicByModuleAction?moduleId=<%=module.getId()%>"><%=module.getName() %></a></td>
				<td><B><span><%=u.getUsername() %></span></B></td>
				<td><p align="center"><span><%=topic.getCreateTime() %></span></p></td>
				<td><p><span>回复次数:<font color="orange" size="15px"><%=topic.getReplyCount() %></font></span></p></td>			
			</tr>
		
			 
		     </table>          
        </div>
		
			<%
		}
	}
	catch(Exception e){
		out.print("加载出错!");
	}
%>

<center>
<a href = "index.jsp?curPage=1" >首页</a>
<a href = "index.jsp?curPage=<%=curPage-1%>" >上一页</a>
<a href = "index.jsp?curPage=<%=curPage+1%>" >下一页</a>
<a href = "index.jsp?curPage=<%=pageCount%>" >尾页</a>
第<%=curPage%>页/共<%=pageCount%>页
</center></span>

原文地址:https://www.cnblogs.com/laohuihui/p/5308754.html