您的位置:首页 > Web前端 > JavaScript

JSP自定义标签简介

2019-05-30 22:29 155 查看

JSP自定义标签简介

我们熟知的jsp标签就有c:if,c:foreach,接下来我们来弄清楚jsp的怎么执行,就能自己自定义标签

首先命名一个随意名字的a.zlt 简单复制 c标签的c.zlt文件内容 ,当然不是这样简单
把其它的都删了,留下一个来测试

<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>
</tag>

我们可以把 uri=“http://java.sun.com/jsp/jstl/core” 替换称自己定义的名字


我们再准备标签助手 创建一个类继承 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:再计算主体一次
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: