自定义迭代标签
开发一个迭代标签 的步骤
1, 写一个标签类.
package com.cao.tag;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
public class IterateTag extends TagSupport {
private String itemId;
private Object item;
private Iterator items =null;;
@Override
public int doEndTag() throws JspException {
// TODO Auto-generated method stub
return super.doEndTag();
}
@Override
public int doStartTag() throws JspException {
if(items.hasNext()){
item = items.next();
}else{
return this.SKIP_BODY;
}
putVariable();
return this.EVAL_BODY_INCLUDE;
}
@Override
public void release() {
// TODO Auto-generated method stub
items = null;
}
//得到要迭代的集合
public void setItems(Collection items) {
//避免当 items为空出现NullPointException
if(items.size()>0)
this.items = items.iterator();
}
// var 作为属性.
public void setVar(String var){
this.itemId = var;
}
@Override
public int doAfterBody() throws JspException {
if(items.hasNext()){
item = items.next();
}else{
return this.SKIP_BODY;
}
this.putVariable();
return this.EVAL_BODY_AGAIN;
}
private void putVariable(){
if(item == null){
pageContext.removeAttribute(itemId,PageContext.PAGE_SCOPE);
}else{
//将迭代出来的值放到page作用域里
pageContext.setAttribute(itemId, item);
}
}
}
2, 配置TLD 文件
<tag>
<name>iterator</name>
<tag-class>com.cao.tag.IterateTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>var</name>
<required>true</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
<attribute>
<name>items</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
3 在页面上导入标签库 <%@ taglib uri="/myTag" prefix="my" %>
index.jsp上的测试代码.
<%
ArrayList arrayList = new ArrayList();
arrayList.add("aaa");
arrayList.add("bbb");
arrayList.add("ccc");
pageContext.setAttribute("arrayList",arrayList);
%>
<my:iterator items="${arrayList}" var="obj">
${obj}
</my:iterator>
这样一个简单的迭代标签就写好了.