1)自定义标签处理类
package formsdemo;
import java.io.IOException;
import java.util.Collection;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class IteratorTag extends SimpleTagSupport{
//标签属性,用于指定需要被迭代的集合
private String collection;
//标签属性,指定迭代集合元素,为集合元素指定的名称
private String item;
//collection属性的setter和getter方法
public void setCollection(String collection)
{
this.collection = collection;
}
public String getCollection()
{
return this.collection;
}
//item属性的setter和getter方法
public void setItem(String item)
{
this.item = item;
}
public String getItem()
{
return this.item;
}
//标签的处理方法,简单标签处理类只需要重写doTag方法
public void doTag() throws JspException, IOException
{
//从page scope中获取属性名为collection的集合
Collection itemList = (Collection)getJspContext().
getAttribute(collection);
//遍历集合
for (Object s : itemList)
{
//将集合的元素设置到page 范围
getJspContext().setAttribute(item, s );
//输出标签体
getJspBody().invoke(null);
}
}
}
2)TLD文件中tag的定义
<tag>
<!-- 定义标签名 -->
<name>iterator</name>
<!-- 定义标签处理类 -->
<tag-class>formsdemo.IteratorTag</tag-class>
<!-- 定义标签体支持JSP脚本 -->
<body-content>scriptless</body-content>
<!-- 配置标签属性:collection -->
<attribute>
<name>collection</name>
<required>true</required>
<fragment>true</fragment>
</attribute>
<!-- 配置标签属性:item -->
<attribute>
<name>item</name>
<required>true</required>
<fragment>true</fragment>
</attribute>
</tag>
3)jsp文件中的引用
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@page import="java.util.*"%>
<%@ taglib uri="/demotag" prefix="mytag"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<h2>带标签体的标签-迭代器标签</h2>
<hr>
<%
//创建一个List对象
List<String> a = new ArrayList<String>();
a.add("hello");
a.add("world");
a.add("java");
//将List对象放入page范围内
pageContext.setAttribute("a" , a);
%>
<table border="1" bgcolor="aaaadd" width="300">
<!-- 使用迭代器标签,对a集合进行迭代 -->
<mytag:iterator collection="a" item="item">
<tr>
<td>${pageScope.item}</td>
<tr>
</mytag:iterator>
</table>
</body>
</html>