标签

来源:互联网 发布:av淘宝网址获取网站 编辑:程序博客网 时间:2024/06/12 01:38

一、简单标签 

1.创建一个标签处理器类:实现SimpleTag接口

2.在web-inf文件夹下新建一个.tld(标签库描述文件)为扩展名的xml文件,并拷入固定的部分:
     并对description,display-name,tlib-version,short-name,uri做出修改

<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>JSTL 1.1 core library</description>
  <display-name>JSTL core</display-name>
  <tlib-version>1.1</tlib-version>
  <short-name>c</short-name>
  <uri>http://java.sun.com/jsp/jstl/core</uri>
 
</taglib>


3.在tld文件中描述自定义的标签:
<!-- 描述hello的标签 -->
  <tag>
    <!-- 标签名-->
      <name>hello</name>
      <!-- 标签所在的全类名 -->
      <tag-class>com.zyd.simpleTag.Hello</tag-class>
    <!-- 标签体的类型 -->
      <body-content>empty</body-content>
  </tag>

4.在jsp页面上使用自定义标签:

    ①使用taglib指令导入标签库描述文件: <%@taglib uri="http://www.zyd.com/MyTag/core" prefix="zyd"%>

    ②使用自定义的标签:<zyd:hello/>


二、带属性的自定义标签


1.先在标签处理器类中定义setter方法,把所有的属性类型都设置为String:
  第一步:
    private PageContext pageContext;
    @Override
    public void setJspContext(JspContext arg0) {
        System.out.println("setJspContext");
        this.pageContext=(PageContext)arg0;

    }
  第二部:设置属性名
    private String value;
    private int count;
    public void setValue(String value) {
        // TODO Auto-generated method stub
        this.value=value;
    }
    public void setCount(int count) {
        // TODO Auto-generated method stub
        this.count=count;
    }
  第三部:编写逻辑
    public void doTag() throws JspException, IOException {

        JspWriter out=pageContext.getOut();
        for(int i=1;i<=count;i++){
            out.print(value);
            out.print("<br>");
        }

    }
2.在.tld描述文件中描述属性:

      <attribute>
          <name>value</name>
          <required>true</required>
          <rtexprvalue>true</rtexprvalue>
      </attribute>
            <attribute>
          <name>count</name>
          <required>false</required>
          <rtexprvalue>false</rtexprvalue>
      </attribute>

3.在jsp文件中编写属性值:<zyd:hello value="j" count="10"/>

4.通常情况下直接继承SimpleTagSupport类,则pageContext的获取方式为:

    PageContext pagecontext = getJspContext();


三、带标签体的标签

1.若一个标签有标签体:<zyd:jspFragment>helloworld</zyd:jspFragment>

  在自定义标签的标签处理器中使用JspFragment对象封装标签体信息。

2.若配置了标签有标签体,则jsp引擎会调用setJspBody() 把jspFragment传递给标签处理器类。
在simpleTagSupport中还定义了一个getJSPBody()方法,用于返回JSPFragment对象。

3.JSPFragment的invoke(Writer)方法:把标签体内容从Writer中输出,若为null,
则等同于invoke(getJSPContext().getOut()),即直接把标签体内容输出到页面上

4.在tld文件中,使用body-content节点来描述标签体的类型:

<body-content>:指点标签体的类型,共3种:

empty:没有标签体

scriptless:标签体可以包含el表达式和 JSP 动作元素,但不能包含JSP脚本元素

tagdependent:表示不处理。

1 0
原创粉丝点击