JSP标签 1

JSP自定义标签

1、标签语言特点

- <开始标签 属性="属性值">标签体</结束标签>
 
 -  空标签     <br/><hr/>     <开始标签></结束标签>    <开始标签/>
 
 -  ui标签     控制标签        数据标签

2、自定义标签的开发及使用步骤

① 创建一个标签助手类(继承BodyTagSupport) , 标签属性必须助手类的属性对应、且要提供对应get/set方法;
② 创建标签库描述文件(tld),添加自定义标签的配置; 注:tld文件必须保存到WEB-INF目录或其子目录;
③ 在JSP通过taglib指令导入标签库,并通过指定后缀访问自定义标签

<tag>
  <!-- 描述 -->
    <description>
        Catches any Throwable that occurs in its body and optionally
        exposes it.
    </description>
    <!-- 标签库里的标签名-->
    <name>demo</name>
    <!-- 标签对应的助手类的全路径名-->
    <tag-class>zking.jsp.DemoTag</tag-class>
    <!-- JSP -->
    <body-content>JSP</body-content>
    <attribute>
    <!-- 描述 -->
       <description>
	       Name of the exported scoped variable for the
	       exception thrown from a nested action. The type of the
	       scoped variable is the type of the exception thrown.
        </description>
        <!-- 属性名(可以有多个) -->
        <name>test</name>
        <!-- 属性值是否必填 -->
        <required>false</required>
        <!-- 是否支持表达式 -->
        <rtexprvalue>false</rtexprvalue>
    </attribute>

3、标签生命周期

创建一个类继承 BodyTagSupport 必须写这三个方法
doStartTag() 开始标签
doAfterBody() 主体部分
doEndTag() 结束标签

public class DemoTag extends BodyTagSupport {

	private static final long serializable=-4293392180911867475L;
	
	private String test;

	public String getTest() {
		return test;
	}

	public void setTest(String test) {
		this.test = test;
	}
	
	@Override
	public int doStartTag() throws JspException {
		System.out.println("---------doStartTag----------");
		return super.doStartTag();
	}
	
	@Override
	public int doEndTag() throws JspException {
		System.out.println("---------doEndTag----------");
		return super.doEndTag();
	}
	
	@Override
	public int doAfterBody() throws JspException {
		System.out.println("---------doAfterBody----------");
		return super.doAfterBody();
	}
}

注意
① jsp上面如果有标签体,三个方法都会执行;如果没有标签体,那么doAfterBody方法不会执行就执行默认设置;
② 这时jsp上有标签体,会将doStartTag的返回值改为SKIP_BODY,那么doAfterBody也不执行 并且jsp页面主体类容显示;
③ 如果改变doAfterBody的莫认返回值为EVAL_BODY_AGAIN,那么doAfterBody会反复执行。
在这里插入图片描述
返回值:

SKIP_BODY:跳过主体
 EVAL_BODY_INCLUDE:计算标签主体内容并[输出]
 EVAL_BODY_BUFFERED:计算标签主体内容并[缓存]
 EVAL_PAGE:计算页面的后续部分
 SKIP_PAGE:跳过页面的后续部分
 EVAL_BODY_AGAIN:再计算主体一次