码迷,mamicode.com
首页 > Web开发 > 详细

jsp分页小结

时间:2016-07-22 19:27:12      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:

分页标签:对于分页,我整理了3个版本。1.0是直接在jsp页面写分页内容;2.0利用自定义分页标签;3.0利用自定义分页标签并打成jar包
1.0分页技术 
a.编写dao层分页跳转类(包括分页标签实体类);
b.编写action层分页控制类;
c.编写js和html前端代码;
2.0自定义标签 (传统标签)
a.开发标签处理类
b.编写标签描述符文件(*.tld)
c.在页面通过taglib引用标签
3.0自定义标签 (打成jar包)
a.新建一个web工程(必须是web工程,因为*.tld文件要放到mate—INFO目录下)
b.将标签处理类包括包名一起复制给新建工程
c.将标签实体类包括包名复制给新建工程
d.将*.tld文件放到mate—INFO目录下
e.导出工程,选择java-》jarFile,去掉工程文件的勾选
d.导完jar包,删除jar中的webroot文件夹,在META-INFO文件中加入*.tld文件




1.分页的sql语句
a. oracle(我们选取的是oracle数据库)
rownum伪列:返回行号 
示例:select * from (select rownum rn,myAddrBook.* from myAddrBook order by id) where rn>5 and rn<=10;
row_number函数
示例:select * from (select row_number() over(order by id) rn, myAddrBook.* from myAddrBook order by id) where rn>5 and rn<=10;


b.sqlserver
top语句
select top 5 * from 表名
select top 5 * from 表名 where id not in (select top 5 id from 表名)


c.mysql:
select * from 表名 limit 5,10


注:oracle 数据库中,伪列:rownum:返回行号 rowid:返回一个唯一行标识


2.分页1.0实现


jsp页面的html和js代码
   js代码:
function toPage(num){
			document.getElementById("currentPage").value=num;
			goToPage();
		}
		
		function goToPage(){
			document.myForm.action.value='findCurrentData';
			document.myForm.submit();
		}

 html代码:

<tr>
   			<td colspan="11">
   				总条数:${pageBean.totalSize}条|总页数:${pageBean.totalPage}页
   					<c:choose>
   						<c:when test="${pageBean.currentPage==1}">
   							首页
   							上一页
   							<a href="javascript:toPage(${pageBean.currentPage+1})">下一页</a>
   							<a href="javascript:toPage(${pageBean.totalPage})">最后一页</a>
   						</c:when>
   						<c:when test="${pageBean.currentPage==pageBean.totalPage}">
   							<a href="javascript:toPage(1)">首页</a>
   							<a href="javascript:toPage(${pageBean.currentPage-1})">上一页</a>
   							下一页
   							最后一页
   						</c:when>
   						<c:otherwise>
   							<a href="javascript:toPage(1)">首页</a>
   							<a href="javascript:toPage(${pageBean.currentPage-1})">上一页</a>
   							<a href="javascript:toPage(${pageBean.currentPage+1})">下一页</a>
   							<a href="javascript:toPage(${pageBean.totalPage})">最后一页</a>
   						</c:otherwise>
   					</c:choose>
   					
   					每页<input type="text" name="pageSize" value="${pageBean.pageSize}"/>条
   					第<input type="text" name="currentPage" id="currentPage" value="${pageBean.currentPage}"/>页
   					<input type="button" value="go" onclick="goToPage()"/>
   				</td>
   			</tr>

  完整的jsp代码参考:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%
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>Welcome to my address book</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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
		function doDelete(id){
			if(confirm('是否删除?')){
				location.href='action/MyAddrBookAction?action=deleteById&id='+id;
			}
		}
		
		function selectAll(){
			var deleteFlag = document.getElementById("deleteFlag");
			var ids = document.myForm.ids;
			for(var i=0;i<ids.length;i++){
				if(deleteFlag.checked){
					ids[i].checked=true;
				}else{
					ids[i].checked=false;
				}
			}
		}
		
		function doDeleteByids(){
			if(confirm('是否删除?')){
				document.myForm.action.value='deleteByIds';
				document.myForm.submit();
			}
		}
		
		function toPage(num){
			document.getElementById("currentPage").value=num;
			goToPage();
		}
		
		function goToPage(){
			document.myForm.action.value='findCurrentData';
			document.myForm.submit();
		}
	</script>
  </head>
  
  <body>
    <center>
    	<form action="action/MyAddrBookAction" name="myForm">
   		<table border="1">
   			<tr>
   				<td><input type="checkbox" id="deleteFlag" onclick="selectAll();"/>
   					<input type="hidden" name="action" value=""/>
   				</td>
   				<th>序号</th>
   				<th>ID</th>
   				<th>firstName</th>
   				<th>lastName</th>
   				<th>jobTitle</th>
   				<th>department</th>
   				<th>offPh</th>
   				<th>mobile</th>
   				<th>email</th>
   				<th>操作</th>
   			</tr>
   			<c:forEach var="myAddrBook" items="${addressList}" varStatus="status">
   				<tr>
   					<td><input type="checkbox" name="ids" value="${myAddrBook.id}"/></td>
   					<td>${status.index+1}</td>
   					<td>${myAddrBook.id}</td>
   					<td><a href="action/MyAddrBookAction?action=get&id=${myAddrBook.id}">${myAddrBook.firstName}</a></td>
   					<td>${myAddrBook.lastName}</td>
   					<td>${myAddrBook.jobtitle}</td>
   					<td>${myAddrBook.department}</td>
   					<td>${myAddrBook.offPh}</td>
   					<td>${myAddrBook.mobile}</td>
   					<td>${myAddrBook.email}</td>
   					<td><a href="javascript:doDelete(${myAddrBook.id});">删除</a></td>
   				</tr>
   			</c:forEach>
   			
   			<tr>
   				<td colspan="11">
   					总条数:${pageBean.totalSize}条|总页数:${pageBean.totalPage}页
   					<c:choose>
   						<c:when test="${pageBean.currentPage==1}">
   							首页
   							上一页
   							<a href="javascript:toPage(${pageBean.currentPage+1})">下一页</a>
   							<a href="javascript:toPage(${pageBean.totalPage})">最后一页</a>
   						</c:when>
   						<c:when test="${pageBean.currentPage==pageBean.totalPage}">
   							<a href="javascript:toPage(1)">首页</a>
   							<a href="javascript:toPage(${pageBean.currentPage-1})">上一页</a>
   							下一页
   							最后一页
   						</c:when>
   						<c:otherwise>
   							<a href="javascript:toPage(1)">首页</a>
   							<a href="javascript:toPage(${pageBean.currentPage-1})">上一页</a>
   							<a href="javascript:toPage(${pageBean.currentPage+1})">下一页</a>
   							<a href="javascript:toPage(${pageBean.totalPage})">最后一页</a>
   						</c:otherwise>
   					</c:choose>
   					
   					每页<input type="text" name="pageSize" value="${pageBean.pageSize}"/>条
   					第<input type="text" name="currentPage" id="currentPage" value="${pageBean.currentPage}"/>页
   					<input type="button" value="go" onclick="goToPage()"/>
   				</td>
   			</tr>
   		</table>
   		<a href="editAddrBook.jsp">添加通讯录</a>
   		<a href="javascript:doDeleteByids();">删除选中通讯录</a>
   		</form>
    </center>
  </body>
</html>
分页标签实体:
//当前页
private Long currentPage = new Long(1);
//每页多少条
private Long pageSize = new Long(5);
//总条数
private Long totalSize;
//总页数
private Long totalPage;


处理的处理java servlet代码:

private void findCurrentData(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//取值
		String pageSize = request.getParameter("pageSize");
		String currentPage = request.getParameter("currentPage");
		
		MyAddrBook myAddrBook = new MyAddrBook();
		if(pageSize!=null && pageSize.matches("^[0-9]+$")){
			myAddrBook.setPageSize(new Long(pageSize));
		}
		if(currentPage!=null && currentPage.matches("^[0-9]+$")){
			myAddrBook.setCurrentPage(new Long(currentPage));
		}
		
		
		//调用业务逻辑层
		try {
			LOGGER.info("开始查询通讯录");
			//设置总条数
			myAddrBook.setTotalSize(myAddrBookService.count(myAddrBook));
			request.setAttribute("pageBean",myAddrBook);
			request.setAttribute("addressList", myAddrBookService.findCurrentData(myAddrBook));
			LOGGER.info("查询通讯录成功");
		} catch (Exception e) {
			LOGGER.error("查询通讯录失败", e);
		}
		// 请求转发
		request.getRequestDispatcher("../list.jsp").forward(request, response);
	}
DAO层的方法,可以直接从service层调用:
public List<MyAddrBook> findCurrentData(MyAddrBook myAddrBook)
			throws Exception {
		List<MyAddrBook> list = new ArrayList<MyAddrBook>();
		String sql = "select id,Firstname,Lastname,Jobtitle,Department,Offph,Mobile,Email from (select rownum rn,myAddrBook.* from myAddrBook order by id) where rn>? and rn<=?";
		try{
			preStmt = super.createPreStmt(sql);
			Long start = (myAddrBook.getCurrentPage()-1)*myAddrBook.getPageSize();
			Long end = myAddrBook.getCurrentPage()*myAddrBook.getPageSize();
			preStmt.setLong(1, start);
			preStmt.setLong(2, end);
			
			rs = preStmt.executeQuery();
			while(rs.next()){
				MyAddrBook addrBook = new MyAddrBook();
				addrBook.setId(rs.getLong(1));
				addrBook.setFirstName(rs.getString(2));
				addrBook.setLastName(rs.getString(3));
				addrBook.setJobtitle(rs.getString(4));
				addrBook.setDepartment(rs.getString(5));
				addrBook.setOffPh(rs.getString(6));
				addrBook.setMobile(rs.getString(7));
				addrBook.setEmail(rs.getString(8));
				list.add(addrBook);
			}
		} catch(Exception ex){
			throw ex;
		} finally{
			close();
		}
		return list;
	}

	@Override
	public Long count(MyAddrBook myAddrBook) throws Exception {
		Long count = 0L;
		String sql = "select count(id) from myAddrBook";
		try{
			preStmt = super.createPreStmt(sql);
			
			rs = preStmt.executeQuery();
			if(rs.next()){
				count = rs.getLong(1);
			}
		} catch(Exception ex){
			throw ex;
		} finally{
			close();
		}
		return count;
	}
3 分页2.0实现
a.开发标签处理类
import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.hntest.myaddrbook.entity.PageBean;

/**
 * 分页标签
 * @author Administrator
 *
 */
public class PageTag extends TagSupport {
	private String formName;
	private String beanName;

	public void setFormName(String formName) {
		this.formName = formName;
	}

	public void setBeanName(String beanName) {
		this.beanName = beanName;
	}

	@Override
	public int doEndTag() throws JspException {
		PageBean pageBean = (PageBean) pageContext.getRequest().getAttribute(beanName);
		if(pageBean==null){
			pageBean = (PageBean) pageContext.getSession().getAttribute(beanName);
		}
		
		if(pageBean==null){
			throw new JspException("请在request或session中设置分页bean对象");
		}
		
		JspWriter out = pageContext.getOut();
		StringBuffer str = new StringBuffer("<script type='text/javascript'>");
		
		str.append("function toPage(num){")
		   .append("document.getElementById('currentPage').value=num;")
		   .append("goToPage();}")
		   .append("function goToPage(){document.").append(formName).append(".action.value='findCurrentData';")
		   .append("document.").append(formName).append(".submit();}")
		   .append("</script>");
		   
		str.append("总条数:").append(pageBean.getTotalSize())
		   .append("条|总页数:").append(pageBean.getTotalPage())
		   .append("页|");
		
		Long currentPage = pageBean.getCurrentPage();
		if(currentPage==1){
			str.append("首页|上一页|").append("<a href='javascript:toPage(").append(currentPage+1).append(")'>下一页|</a>")
			   .append("<a href='javascript:toPage(").append(pageBean.getTotalPage()).append(")'>最后一页</a>");
		}else if(currentPage.equals(pageBean.getTotalPage())){
			str.append("<a href='javascript:toPage(1)'>首页|</a>")
			   .append("<a href='javascript:toPage(").append(currentPage-1).append(")'>上一页|</a>")
			   .append("下一页|最后一页");
		}else{
			str.append("<a href='javascript:toPage(1)'>首页|</a>")
			   .append("<a href='javascript:toPage(").append(currentPage-1).append(")'>上一页|</a>")
			   .append("<a href='javascript:toPage(").append(currentPage+1).append(")'>下一页|</a>")
			   .append("<a href='javascript:toPage(").append(pageBean.getTotalPage()).append(")'>最后一页</a>");
		}
		
		str.append("每页<input type='text' name='pageSize' value='").append(pageBean.getPageSize()).append("'/>条")
		   .append("第<input type='text' name='currentPage' id='currentPage' value='")
		   .append(pageBean.getCurrentPage()).append("'/>页")
		   .append("<input type='button' value='go' onclick='goToPage()'/>");
		
		try {
			out.write(str.toString());
			out.flush();
		} catch (IOException e) {
			throw new JspException("分页标签初始化异常");
		} 
		//对于空标签,我们一般返回SKIP_BODY
		return SKIP_BODY;
	}

}

b.编写标签描述符文件(*.tld),我们可以参照jstl-impl.jar中的meta-info中的*.tld文件。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib
  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
  "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.2</jsp-version>
  <short-name>p</short-name>
  <uri>http://edu.hntest.org/tag/page</uri>
  <display-name>page tag</display-name>
  <description>分页标签</description>
  
  <tag>
  	<name>page</name>
  	<tag-class>org.hntest.myaddrbook.tag.PageTag</tag-class>
  	<body-content>empty</body-content>
  	 <attribute>
        <name>formName</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
        <name>beanName</name>
        <required>true</required>
        <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
</taglib>

c.在页面通过taglib引用标签
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
				<tr>
   				<td colspan="11">
  					<p:page formName="myForm" beanName="pageBean"/>
   				</td>
示例代码:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>
<%@ taglib prefix="p" uri="http://edu.hntest.org/tag/page"%>
<%
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>Welcome to my address book</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">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
	<script type="text/javascript">
		function doDelete(id){
			if(confirm('是否删除?')){
				location.href='action/MyAddrBookAction?action=deleteById&id='+id;
			}
		}
		
		function selectAll(){
			var deleteFlag = document.getElementById("deleteFlag");
			var ids = document.myForm.ids;
			for(var i=0;i<ids.length;i++){
				if(deleteFlag.checked){
					ids[i].checked=true;
				}else{
					ids[i].checked=false;
				}
			}
		}
		
		function doDeleteByids(){
			if(confirm('是否删除?')){
				document.myForm.action.value='deleteByIds';
				document.myForm.submit();
			}
		}
		
	</script>
  </head>
  
  <body>
    <center>
    	<form action="action/MyAddrBookAction" name="myForm">
   		<table border="1">
   			<tr>
   				<td><input type="checkbox" id="deleteFlag" onclick="selectAll();"/>
   					<input type="hidden" name="action" value=""/>
   				</td>
   				<th>序号</th>
   				<th>ID</th>
   				<th>firstName</th>
   				<th>lastName</th>
   				<th>jobTitle</th>
   				<th>department</th>
   				<th>offPh</th>
   				<th>mobile</th>
   				<th>email</th>
   				<th>操作</th>
   			</tr>
   			<c:forEach var="myAddrBook" items="${addressList}" varStatus="status">
   				<tr>
   					<td><input type="checkbox" name="ids" value="${myAddrBook.id}"/></td>
   					<td>${status.index+1}</td>
   					<td>${myAddrBook.id}</td>
   					<td><a href="action/MyAddrBookAction?action=get&id=${myAddrBook.id}">${myAddrBook.firstName}</a></td>
   					<td>${myAddrBook.lastName}</td>
   					<td>${myAddrBook.jobtitle}</td>
   					<td>${myAddrBook.department}</td>
   					<td>${myAddrBook.offPh}</td>
   					<td>${myAddrBook.mobile}</td>
   					<td>${myAddrBook.email}</td>
   					<td><a href="javascript:doDelete(${myAddrBook.id});">删除</a></td>
   				</tr>
   			</c:forEach>
   			
   			<tr>
   				<td colspan="11">
  					<p:page formName="myForm" beanName="pageBean"/>
   				</td>
   			</tr>
   		</table>
   		<a href="editAddrBook.jsp">添加通讯录</a>
   		<a href="javascript:doDeleteByids();">删除选中通讯录</a>
   		</form>
    </center>
  </body>
</html>
4.分页3.0(如上打成jar,略)




jsp分页小结

标签:

原文地址:http://blog.csdn.net/vinsuan1993/article/details/51991907

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!