TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
使用SimpleTagSupport开发一个能迭代的标签。 一样先定义一个标签处理类,该标签处理类的代码如下。 程序清单:
- package lee;
- import java.util.*;
- import javax.servlet.jsp.JspException;
- import javax.servlet.jsp.tagext.SimpleTagSupport;
- import java.io.IOException;
- public class MyIteratorTag extends SimpleTagSupport
- {
- private String bean;
- public void setBean(String bean)
- {
- this.bean = bean;
- }
- public String getBean()
- {
- return bean;
- }
- public void doTag() throws JspException, IOException
- {
- Collection< String> itemList = (Collection< String>)getJspContext().getAttribute(bean);
- for (String s : itemList)
- {
- getJspContext().setAttribute("item", s );
- getJspBody().invoke(null);
- }
- }
- }
复制代码 上面标签处理类与前面处理类并没有太大的不同,该处理类包含两个属性,并为这两个属性提供了setter和getter方法。标签处理类的doTag方法首先从page范围内获取了指定名称的Collection对象,然后遍历Collection对象的元素,每次遍历都调用了getJspBody()方法,该方法返回该标签所包含的标签体:JspFragment对象,执行该对象的invoke()方法,即可输出标签体内容。该标签的作用是:遍历指定集合,每遍历一个集合元素,即输出标签体一次。 因为该标签的标签体不为空,配置该标签时指定body-content为scriptless,该标签的配置代码片段如下所示。 程序清单:mytaglib.tld
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<jsp-version>2.0</jsp-version>
<tlib-version>1.0</tlib-version> <tag>
<name>helloWorld</name>
<tag-class>lee.HelloWorldSimpleTag</tag-class>
<body-content>empty</body-content>
</tag>
<tag>
<name>iterator</name>
<tag-class>lee.MyIteratorTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>bean</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
web.xml文件:
<?xml version="1.0" encoding="GBK"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4"> <jsp-config>
<taglib>
<taglib-uri>/tags/mytag</taglib-uri>
<taglib-location>/WEB-INF/mytaglib.tld</taglib-location>
</taglib>
</jsp-config> </web-app>
为了测试在JSP页面中使用该标签的效果,我们首先把一个List对象设置成page范围的属性,然后使用该标签来迭代输出List集合的全部元素。
JSP页面代码如下:
<%@ page contentType="text/HTML; charset=gb2312" import="java.util.*"%>
<%@ taglib prefix="mytag" uri="/tags/mytag"%>
<html> <head> <title>JSP2.0 - 简单标签</title> </head>
<body>
<h2>JSP2.0 - 简单标签</h2>
<hr>
<%
List<String> a = new ArrayList<String>();
a.add("hello");
a.add("world");
a.add("java");
pageContext.setAttribute("a" , a);
%>
<table border="1" bgcolor="aaaadd">
<mytag:iterator bean="a">
<tr> <td></td> </tr>
</mytag:iterator>
</table>
<mytag:helloWorld/>
</body>
</html>
.运行界面。
图2.37 带标签体的标签
使用iterator标签遍历集合元素的效果,从iteratorTag.jsp页面的代码来看,使用iterator标签遍历集合元素比使用JSP脚本遍历集合元素要优雅得多,这就是自定义标签的魅力。
源码下载:http://file.javaxxz.com/2014/10/2/074850734.zip |
|