在jsp编程中,可以通过自定义标签来将一些表现层的处理逻辑封装到java类中,在jsp页面上,只是通过简单的标签调用就可以实现比较复杂的显示逻辑。
要实现一个自定义标签,需要完成2个部分,一个是处理Java类,另一个就是.tld的标签库定义文件,在tld文件中定义了所有的处理java类对应的标签的定义规范。 然后,在页面上,就可以根据tld里面的定义来使用自定义标签了。
还是拿一个简单的例子来说明。
处理java类:
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) //得到id为’a'的集合对象的第一个元素,放入变量s。
{
//将集合的元素设置到page 范围
getJspContext().setAttribute(item, s );//将变量s以‘i1’作为id存入页面scope中。
//执行标签体
getJspBody().invoke(null);
}
}
}
页面调用的主要代码:
<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="i1">//通过调用java处理类的setter方法,告诉java处理类,对page scope内的id为‘a'的collection对象进行处理,
//进行处理
<tr>
<td>${pageScope.item}</td>//得到java处理类中迭代出的元素‘i1’。
<tr>
</mytag:iterator>
</table>
</body>