自定义标签。

自定义标签。
1. 写一个java类,继承SimpleTagSupport类,并重写 doTag()方法。
2. 在WEB-INF文件夹中新建一个.tld文件,然后在其中描述该标签。
3. 使用。使用自定义标签方式同标准标签一样。
1.
package el;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class MyForTag extends SimpleTagSupport {

    /**循环的次数。 */
    private int num;
    /**循环打印的信息。*/
    private String info;
    public int getNum()  {return num;}
    public void setNum(int num)  {this.num = num;}
    public String getInfo()  {return info;}
    public void setInfo(String info){this.info = info;}
    /**
     * 重写doTag()方法。在里面写循环的操作。
     */
    @Override
    public void doTag() throws JspException, IOException {

        for(int i=0;i<num;i++){
        getJspContext().getOut().println(info+"<br/>");
        }

    }

}
 
2.
<?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">
    
  <description>Mylitboy 1.1 Tag library</description>
  <display-name>Mylitboy Tag</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>t</short-name>                    <!-- 建议使用的名字,可以不写 -->
  <uri>http://www.mylitboy.com.cn/mytag</uri>
                                                                <!-- url,使用时需要指定相同的 -->
  <tag>
    <description>mylitboy.tag</description>
    <name>for</name>                               <!-- 标签名:使用时的标签名 -->
    <tag-class>el.MyForTag</tag-class>        <!-- 类的地址:包名.类名 -->
    <body-content>empty</body-content>     <!-- 标签体 -->
    <attribute>
        <description>number</description>
        <name>num</name>                         <!-- 属性名字 -->
        <required>true</required>                  <!-- 是否必须写num -->
        <rtexprvalue>false</rtexprvalue>         <!-- 是否能用el表达式。 -->
    </attribute>
    <attribute>
        <description>infomation</description>
        <name>info</name>                         <!-- 属性名字 -->
        <required>true</required>                 <!-- 是否必须写info -->
        <rtexprvalue>false</rtexprvalue>        <!-- 是否能用el表达式。 -->
    </attribute>
  </tag>
</taglib>
3.
使用方式如下:
在jsp文件中加上如下声明:
<%@taglib uri="http://www.mylitboy.com.cn/mytag" prefix="t"%>
使用时:
<t:for num="100" info="helloworld"/>
4.
调用jsp文件,结果如下
helloworld
helloworld
helloworld
...
2010-08-20
mylitboy

posted @ 2011-11-09 21:13  mylitboy  阅读(197)  评论(0编辑  收藏  举报