jsp自定义分页标签page
根据jsp自定义分页标签的特性,我们可以定制自己的分页标签,更加方便开发中的使用,关于jsp的自定义标签,上篇已有详细的介绍说明,
该页最下面的 分页栏,即是自定义的jsp的标签,我这里给的名字是<page:page pager="${requestScope.pb}" />,即只要引入它即可出现该分页栏,由于为了方便,样式可能不太好看,这个大家可以自己去调节。
下面我们开始实现这个page标签,首先新建一个web项目,并引入struts必要地几个jar包。新建一个包,取名为com.page.util,将page的三个实现类放在下面,分别是Pager.java,PagerHelp.java,PageTag.java,它们的实现分别如下:
Pager.java:
Java代码
/**
* 保存分页信息的类
*
*
*/
public class Pager {
private int totalRows; // 总行数
private int pageSize = 10; // 每页显示的行数
private int currentPage; // 当前页号
private int totalPages; // 总页数
private int startRow; // 当前页在数据库中的起始行
private String linkUrl; // 要跳转的URL
public Pager() {
}
public Pager(int _totalRows) {
totalRows = _totalRows;
totalPages = totalRows / pageSize;
int mod = totalRows % pageSize;
if (mod > 0) {
totalPages++;
}
currentPage = 1;
startRow = 0;
}
/**
* 设定查询的起始行数
*
* @param currentPage
*/
public void setStart(int currentPage) {
this.currentPage = currentPage;
startRow = (currentPage - 1) * pageSize;
}
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public int getStartRow() {
return startRow;
}
public void setStartRow(int startRow) {
this.startRow = startRow;
}
public String getLinkUrl() {
return linkUrl;
}
public void setLinkUrl(String linkUrl) {
this.linkUrl = linkUrl;
}
}
PagerHelp.java:
Java代码
import javax.servlet.http.HttpServletRequest;
/**
* 控制分页的类
*
*
*/
public class PagerHelper {
public static Pager getPager(HttpServletRequest req,
int totalRows) {
// 定义pager对象,用于传到页面
Pager pager = new Pager(totalRows);
// 从Request对象中获取当前页号
String currentPage = req.getParameter("cpage");
// 如果当前页号为空,表示为首次查询该页
// 如果不为空,则刷新pager对象,输入当前页号等信息
if (currentPage != null) {
pager.setStart(Integer.parseInt(currentPage));
} else {
pager.setStart(1);
}
return pager;
}
}
PageTag.java:
Java代码
import java.io.IOException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
/**
* 标签类 用于分页查询
*
*/
public class PageTag extends TagSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private Pager pager;
@SuppressWarnings("static-access")
public int doStartTag() {
////标签开始时调用的方法
try {
JspWriter out = pageContext.getOut();
if(pager==null){
out.print("没有记录");
out.flush();
return super.SKIP_BODY;
}
out.print("第 " + pager.getCurrentPage() + " 页/共 "
+ (pager.getTotalPages()) + " 页");
if (pager.getCurrentPage() == 1) {
out.print("[最首页]");
out.print("[上一页]");
}
if (pager.getCurrentPage() != 1) {
out.print("[<a href='" + pager.getLinkUrl()
+ "?cpage=1'>最首页</a>]");
out.print("[<a href='" + pager.getLinkUrl() + "?cpage="
+ (pager.getCurrentPage() - 1) + "'>上一页</a>]");
}
for (int i = pager.getCurrentPage() - 3; i <= pager
.getCurrentPage() + 3; i++) {
if (i <= 0 || i > pager.getTotalPages()) {
continue;
}
if (i == pager.getCurrentPage()) {
out
.print("[<span style='color:#FF0000; border: 1px solid #cccccc; font-weight:bold; width:15px;text-align: center;'> "
+ i + " </span>]");
} else {
out.print("[<a href='" + pager.getLinkUrl() + "?cpage="
+ i + "'> " + i + " </a>]");
}
}
if (pager.getCurrentPage() == pager.getTotalPages()
|| pager.getTotalPages() == 0) {
out.print("[下一页]");
out.print("[最末页]");
}
if (pager.getCurrentPage() != pager.getTotalPages()
&& pager.getTotalPages() != 0) {
out.print("[<a href='" + pager.getLinkUrl() + "?cpage="
+ (pager.getCurrentPage() + 1) + "'>下一页</a>]");
out.print("[<a href='" + pager.getLinkUrl() + "?cpage="
+ (pager.getTotalPages()) + "'>最末页</a>]");
}
out.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
return super.SKIP_BODY;//表示不显示标签间的文字
}
@SuppressWarnings("static-access")
public int doEndTag() {
//标签结束时调用的方法
return super.EVAL_PAGE;//表示JSP页面继续运行
}
public void setPager(Pager pager) {
this.pager = pager;
}
public Pager getPager() {
return pager;
}
}
实现类的完成即是为了实现标签的功能,这里我们在WEB-INF下新建文件夹mytag,新建文件pagetag.tld,在这个文件里对你想要声明的自定义标签,并制定它的实现类,代码如下:
Tld代码
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor">
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>My Tags</short-name>
<tag>
<name>page</name>
<tag-class>com.page.util.PageTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>pager</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>com.page.util.Pager</type>
</attribute>
</tag>
</taglib>
至此,我们的自定义page分页标签业已全部实现了,下面我们就来模拟使用下,新建com.action.TestAction.java,代码如下:
Java代码
import java.util.ArrayList;
import java.util.List;
import com.bean.TestBean;
import com.util.Pager;
import com.util.PagerHelper;
public class TestAction extends BaseAction {
private static final long serialVersionUID = 5293541447709620793L;
private List<TestBean> bList;
@Override
public String execute() throws Exception {
bList=new ArrayList<TestBean>();
for (int i = 0; i < 100; i++) {
bList.add(new TestBean(Long.parseLong(String.valueOf(i)), "person"+i, i+10+"岁", i+"@qq.com"));
}
int totalRow=bList.size();
Pager pager=null;
pager = PagerHelper.getPager(request, totalRow); // 初始化分页对象
pager.setLinkUrl(request.getRequestURI()); // 设置跳转路径
request.setAttribute("pb", pager); // 将分页信息保存在Request对象
//模拟分页时,是要传递参数,模拟传入a,b。单纯分页时,则不需要该段的4行代码
StringBuffer urlParam = new StringBuffer();
urlParam.append("&a="+100);
urlParam.append("&b="+200);
request.setAttribute("urlParam", urlParam.toString());
bList=bList.subList(pager.getStartRow(),pager.getStartRow()+10);
return SUCCESS;
}
public List<TestBean> getbList() {
return bList;
}
public void setbList(List<TestBean> bList) {
this.bList = bList;
}
}
这个类模拟了数十条的分页数据,下面新建两个jsp页面,代码分页如下:
index.jsp:
Jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP 'index.jsp' starting page</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">
-->
</head>
<body>
<a href="test.action">Test Go~~</a>
</body>
</html>
test.jsp:
Jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="page" uri="../WEB-INF/config/mytag/pagetag.tld" %>
<%
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>My JSP 'index.jsp' starting page</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" src="../js/Pager.js"></script>
</head>
<body>
<p style="margin-left: 110px;">
<table>
<tr>
<th colspan="4" ><p style="font-family: sans-serif;font-size: 20px">测试分页</p></th>
</tr>
<tr>
<td width="80px">ID</td>
<td width="80px">Name</td>
<td width="80px">Age</td>
<td width="80px">Email</td>
</tr>
<s:iterator value="bList">
<tr>
<td width="80px"><s:property value="tId"/> </td>
<td width="80px"><s:property value="tName"/> </td>
<td width="80px"><s:property value="tAge"/> </td>
<td width="80px"><s:property value="tEmail"/> </td>
</tr>
</s:iterator>
</table>
</p>
<p style="margin-left: 17px">
<page:page pager="${requestScope.pb}" />
</p>
</body>
<script>
Pager.setUrlParam("${urlParam}");
</script>
</html>
这个页面会使用到page标签,及在文件头引入所需的taglib,并引入Pager.js,该js的代码如下:
Js代码
/**
* 分页操作对象
*/
var Pager = function(){
return{
setUrlParam: function(param)
{
//为翻页标签链接增加显示flag参数
var obj=$(".pagerTarge > a");//获得分页标签下的所有<a>
//alert(obj.length);
if(obj!=null && obj.length>0)
{
for(var i=0;i<obj.length;i++)
{
var tempUrl=$(obj[i]).attr('href');
//添加flag
$(obj[i]).attr('href',tempUrl+param);
}
}
}
}
}();
至此,在web.xml和struts.xml中做好各项配置,启动服务器,键入localhost:8080/mytag/index.jsp,点击"Test Go~~"链接,即出现截图效果,如有报错,请根据错误检查各项配置。
如果需要在分页时,在页面间传递参数,如以上action代码中模拟的a和b的话,即全部用stringbuffer拼接就可以了,我们右键test.jsp效果页面时,可以看到传递的参数url,如图:
上一篇: 百度官方:关于超链作弊的算法升级