1、步骤:
>标签处理类:
SimpleTag接口,接口中定义的方法:
void doTag():每次执行标签时都会调用这个方法
JspTag getParent():返回父标签(动态标签中很多标签并没有父标签)
void setParent(JspTag ):设置父标签
void setJspBody(JspFragment):设置标签体
void setJspContex(JspContext):设置jsp上下文对象,其子类是PageContext
其中,dotag()方法会在其他三个设置方法之后被服务器调用。
核心代码:
private PageContext pageContext;
private JspFragment body ;
public void doTag() throws JspException,IOException {
//通过pageContext获取out域然后输出,而pageContext对象是在服务器执行标签处理类中的其他几个方法中获取到的
pageContext.getOut().print("该标签的作用就是输出此句。")
}
注:为了避免手动获取对象(例如:pageContext对象是在服务器执行标签处理类中的其他方法中通过this.pageContext=(pageContext)JspContext;获取到的),提供类SimpleTag接口的实现类SimpleTagSupport。在继承类该类的自定义标签类中,不用再去重写其他方法以获取传递的对象,可以直接在doTag()方法中通过get()方法获取:
public void doTag() throws JspException,IOException {
this.getJspContext.getOut().print("该标签的作用就是输出此句。");
}
>tld文件(一个xml)(empty表示不包含标签体)
<taglib xmlns=……>
<tag>
<name>tag1</name>
<tag-class>com.demo.tag.tag1</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
>页面中使用<%@taglib%>来指定tld文件
<%@ taglib prefix="ts" uri="/WEB-INF/tlds/tag1.tld" />
<%@taglib ts:tag1%>
2、标签体内容类型:
<body-content></body-content>
empty:无标签体
JSP:jsp2.0已经不支持这个类型了(原本表示表示标签体内容是java脚本、标签、el表达式)
scriptless:表示是标签或其他标签
tagdependent:表示标签体内容不会被执行,而是直接赋值给标签处理类(基本不用)
3、不再执行标签下面的内容——自定义标签中SkipPageException
服务器会调用标签处理类的doTag()方法,得到在方法体中抛出的SkipPageException异常(throw new SkipPageException();),然后就会跳过该标签以后的所有内容,不再执行显示。
4、自定义标签之带有属性的标签
>在标签处理类中添加属性
public class MyTag extends SimpleTagSupport {
private boolean test;
//该方法由服务器调用,并且在doTag()方法之前
public boolean isTest() {
return test;
}
public void setTest(boolean test) {
this.test = test ;
}
public void doTag() throws JspException,IOException {
if(test) {
//执行标签体
this.getJspBody().invoke(null);//如果传递的输出流为null,表示使用的就是当前页面的out,即等同于参数是this.getJspContext().getOut()
}
}
}
>在.tld文件中部署
<tag>
<name>tag1</name>
<tag-class>com.demo.tag.tag1</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>test</name>
<required>true</required>指定属性是否是必须的
<rtexprvalue>true<rtexprvalue>指定属性是否可以使用el表达式
</attribute>
</tag>