在jsp页面中使用自定义标签

在某些场景中,自定义标签可封装大量代码,使页面变得更简洁,标签也可以很方便地在不同页面中实现通用而不必去粘贴大量的js代码。现在把最近做的一个自定义标签在这里总结一下。首先总结一下关于自定义标签的一些知识在jsp页面中使用自定义标签在jsp页面中使用自定义标签

首先,自定义标签是一个tld文件。

每个自定义标签都必须在TLD文件中声明,TLD文件只不过是一个XML文件。根元素是<taglib>,它包含一个或者多个<tag>标签,该元素用来声明定制标签。<taglib>元素中只有<tlib-version>元素是必须的

在jsp页面中使用自定义标签

在jsp页面中使用自定义标签

在jsp页面中使用自定义标签

在jsp页面中使用自定义标签

tld文件的元素内容如上,如下是我的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">
<!-- 自定义标签 v1.0 -->
<!-- 为页面提供分页,仅需后台封装 :1当前页pageIndex 2总页数totalPage 3每页记录数pageSize
url属性页面必须在标签中设置
@Data 2016.03.23
-->
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>ule</short-name>
<!-- 分页 -->
<tag>
<name>pagination</name>
<tag-class>
com.ule.item.csitem.web.tag.PaginationTag
</tag-class>
<body-content>jsp</body-content>
<description>用于分页的标签</description>
<attribute>
<name>pageIndex</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>当前页数</description>
</attribute>
<attribute>
<name>totalPage</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>总页数</description>
</attribute>
<attribute>
<name>url</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>分页action地址</description>
</attribute>
<attribute>
<name>pageSize</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<description>显示条数</description>
</attribute>
</tag>
</taglib>

其中<tag-class>标签就是这个自定义标签要封装的工具类,这个类必须实现最上图接口体系中的接口,我的是这样实现的

public class PaginationTag extends TagSupport{
private static final long serialVersionUID = -8831698321587203192L;
private static Logger logger = Logger.getLogger(PaginationTag.class);
private static final String DOMAINRESOURCE = PropertiesUtil.getPropertyValue("DOMAIN_RESOURCE");

//说明与代码无关,在这里private static final String DOMAINRESOURCE其实就是一个域名,直接写上也行
private int pageIndex;// 当前页数
private int totalPage;//总页数
private String url;//分页action的url地址,类似:http://localhost:7070/mitem/onlinePriPro.do?method=searchItemList

private int pageSize;//总条数
@Override
public int doEndTag() throws JspException {
try{
//获取URL
TreeMap<String, String> paramTreeMap = getParamTreeMap();
String location = generateUrl(paramTreeMap);
StringBuffer submitUrl = new StringBuffer();
submitUrl.append(url);
submitUrl.append(location);
//构造输出到jsp页面上的html代码
StringBuffer html= new StringBuffer();
html.append(getPagerCss());//添加分页标签中需要的css代码

html.append("<div class=\"ulepage\">");
//sizePage选择框,带Onchange事件
html.append("显示条数<select name='pageSize' id='pageSize' onchange='javascript:queryPage1();'>");
html.append("<option value='10' ");
if(pageSize==10){
html.append("selected='selected'");
}
html.append(">10</option>");

html.append("<option value='20' ");
if(pageSize==20){
html.append("selected='selected'");
}
html.append(">20</option>");

html.append("<option value='50' ");
if(pageSize==50){
html.append("selected='selected'");
}
html.append(">50</option>");

html.append("<option value='100' ");
if(pageSize==100){
html.append("selected='selected'");
}
html.append(">100</option>");

html.append("<option value='200' ");
if(pageSize==200){
html.append("selected='selected'");
}
html.append(">200</option>");
html.append("</select>");

html.append(getUpPageHref(submitUrl.toString(), pageIndex));//添加上一页的html代码
if (pageIndex > totalPage) pageIndex = 1; //如果页数大于总页数,则返回第一页
//页码1热键
if (pageIndex != 1) html.append("<a href=\""+ getSubmitUrl(submitUrl.toString(), 1,pageSize) + "\">1</a>");
if (pageIndex >= 5) html.append("...");
int endPage = pageIndex + 2;
if(endPage <= 5) endPage = 6;
if(endPage > totalPage) endPage = totalPage;

for (int i = pageIndex - 2; i <= endPage; i++) {
if (i > 0) {
if (i == pageIndex) {
html.append("<span>" + i + "</span>");//当前页
} else if (i != 1 && i < totalPage){
html.append("<a href=\""+ getSubmitUrl(submitUrl.toString(), i,pageSize) + "\">" + i + "</a>");
}
}
}
if (pageIndex + 3 < totalPage && totalPage > endPage + 1) html.append("...");
html.append("");
if (pageIndex != totalPage) html.append("<a href=\""+ getSubmitUrl(submitUrl.toString(), totalPage,pageSize) + "\">" + totalPage + "</a>");
html.append(getDownPageHref(submitUrl.toString(), pageIndex));
html.append("共" + totalPage + "页&nbsp;&nbsp;");
html.append("跳转到&nbsp;<input id=\"PaginationJumpInputID\" style=\"width: 30px;\" type=\"text\" />&nbsp;页<a href=\"javascript:goJump()\">GO</a>");
html.append("</div>");
//构造跳转js代码
html.append("<script type=\"text/javascript\">");
html.append("function goJump(){");
html.append("var jumpPageIndex = document.getElementById(\"PaginationJumpInputID\").value;");
html.append("if(jumpPageIndex && jumpPageIndex.match(/^[0-9]*$/)){");
html.append("if(jumpPageIndex < 1){");
html.append("jumpPageIndex = 1;}");
html.append("if(jumpPageIndex > " + totalPage + "){jumpPageIndex = " + totalPage + ";}");
html.append("}else{return;}");
html.append("window.location.href=\"" + submitUrl.toString() + "&&currentPage=" + "\" + jumpPageIndex+" +"\"&pageSize="+pageSize+"\";" );
html.append("}");
//显示条数离焦事件js
html.append(" function queryPage1(){");
html.append("var pageSize=$('#pageSize option:selected').val();");
html.append("window.location.href=\"" + submitUrl.toString() + "&currentPage=" +pageIndex+"&pageSize=\"" + " + pageSize;");
html.append("}");

html.append("</script>");
pageContext.getOut().write(html.toString());
}catch(Exception e){
logger.error("doEndTag异常:", e);
}
return this.EVAL_PAGE;
}

/***
* 组装url工具类
*/
private static String getSubmitUrl(final String url, int pageIndex,int pageSize){
StringBuffer newUrl = new StringBuffer();
newUrl.append(url).append("&currentPage=").append(pageIndex).append("&pageSize="+pageSize);
return newUrl.toString();
}
/** 获取上一页链接*/
public String getUpPageHref(String url, int pageIndex){
String upPageStr="<a title=\"上一页\" class=\"pageupon\" href=\"" + getSubmitUrl(url, pageIndex-1,pageSize) + "\" ></a>";
if(pageIndex<=1){
upPageStr="<span title=\"上一页\" class=\"pageupoff\"></span>";
}
return upPageStr;
}

/** 获取下一页链接 */
public String getDownPageHref(String url, int pageIndex){
String upPageStr="<a title=\"下一页\" class=\"pagedownon\" href=\"" + getSubmitUrl(url, pageIndex+1,pageSize) + "\" ></a>";
if(pageIndex>=totalPage){
upPageStr="<span title=\"下一页\" class=\"pagedownoff\"></span>";
}
return upPageStr;
}

/******
* 获取分页标签所需要的样式代码
*/
private static String getPagerCss(){
StringBuffer cssCode = new StringBuffer();
cssCode.append("<style>");
cssCode.append(".page a,.page span{margin:0 10px;}");
cssCode.append(".pageupon,.pageupoff,.pagedownon,.pagedownoff{background:url("+DOMAINRESOURCE+"/i/search/090609/icopagenext.png) no-repeat;display:inline-block;height:13px;width:13px;overflow:hidden;vertical-align:middle;text-indent:-9999px;text-align:left;}");
cssCode.append(".pageupon{background-position:0 -13px;}");
cssCode.append(".pageupoff{background-position:0 0;}");
cssCode.append(".pagedownon{background-position:-13px -13px;}");
cssCode.append(".pagedownoff{background-position:-13px 0;}");
cssCode.append(".ulepage{");
cssCode.append("text-align:right !important;");
cssCode.append("color:#696969;");
cssCode.append("}");
cssCode.append(".ulepage a,.ulepage span{margin:0 10px;}");
cssCode.append("</style>");
return cssCode.toString();
}

/****
* 生产URL地址,即在url后加键值对带&
*/
private String generateUrl(TreeMap<String, String> treeMap){
StringBuffer url = new StringBuffer();
String parameterName = null;
String value = null;
Iterator iterator = treeMap.keySet().iterator();
while (iterator.hasNext()) {
parameterName = (String)iterator.next();
url.append("&").append(parameterName).append("=").append(treeMap.get(parameterName));
}
HttpServletResponse response = (HttpServletResponse)pageContext.getResponse();
return response.encodeURL(url.toString());
}

/******
* 获取param参数组成的map
*/
private TreeMap<String, String> getParamTreeMap() {
TreeMap<String, String> treeMap = new TreeMap();
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
Enumeration parameterNamesEnum = request.getParameterNames();
if(parameterNamesEnum != null){
String parameterName = null;
Object value = null;
while (parameterNamesEnum.hasMoreElements()) {
parameterName = (String) parameterNamesEnum.nextElement();
if (parameterName != null && parameterName.length() > 0) {
if("currentPage".equals(parameterName) || "method".equals(parameterName) || "pageSize".equals(parameterName) ){
//过滤currentPage和method两个参数,避免重复参数
continue;
}
value = request.getParameter(parameterName);
if(value != null && value.toString().trim().length() > 0){
treeMap.put(parameterName, value.toString());
}
}
}
}
return treeMap;
}

public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public int getPageIndex() {
return pageIndex;
}
public void setPageIndex(int pageIndex) {
this.pageIndex = pageIndex;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}

public int getPageSize() {
return pageSize;
}

public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
}

至此,一个自定义标签完成。可以引入到jsp页面了。如下

<%@ taglib uri="/WEB-INF/ule.tld" prefix="ule1" %>

实现分页

<tr>
<td colspan="9">
<ule1:pagination url="${basePath}/csitem/item/queryOnlineItem.action?method=test" pageIndex='${currentPage}' totalPage='${totalPageCount}' pageSize="${pageSize }"></ule1:pagination>
</td>
</tr>

这里需后台返回当前页,总页数,每页条数这三个变量。url就是你controller的路径method=test必须要带,要在url后追加参数。具体效果如下

在jsp页面中使用自定义标签

这就是最终效果。

上一篇:JSP自定义标签/自定义标签打包


下一篇:HTML DOM (文档对象模型)