定制標(biāo)記庫(kù)
1 編寫(xiě)標(biāo)記處理類(lèi)
public class TimerTag extends TagSupport{
private long start;
private long end;
public int doStartTag(){ //doStartTag標(biāo)記開(kāi)始方法
start=System.currentTimeMillis();
return EVAL_BODY_INCLUDE;//
}
public int doEndTag() throws JspTagException {//doEndTag標(biāo)記結(jié)束方法
end=System.currentTimeMillis();
long elapsed=end-start;
try{
JspWriter out=pageContext.getOut();
out.println("running time:"+elapsed+"ms.");
}catch(IOException e){
throw new JspTagException(e);
}
return EVAL_PAGE;//
}
}
2 編寫(xiě).tld文件
<?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>custion web utility tags</description> //對(duì)當(dāng)前標(biāo)記庫(kù)的描述
<tlib-version>1.0</tlib-version> //當(dāng)前標(biāo)記庫(kù)的版本
<short-name>util</short-name> //對(duì)當(dāng)前標(biāo)記庫(kù)使用時(shí)的前綴名稱(chēng)
<uri>http://163.com</uri> //可任意
<tag>
<description>calc code running time</description> //對(duì)當(dāng)前標(biāo)記的描述
<name>timer</name> //標(biāo)記我名稱(chēng)
<tag-class>com.tags.TimerTag</tag-class> 當(dāng)前標(biāo)記對(duì)應(yīng)的處理類(lèi)的具體名稱(chēng)
<body-content>JSP</body-content> //可有empty,JSP
</tag>
</taglib>
3 使用格式
jsp頁(yè)面
<%@ taglib prefix="util" uri="http://163.com" %> 添加指令
<util:timer></util:timer>
總結(jié):
TLD是一個(gè)XML文件,在WEB-INF目錄下
<taglib>根元素
<tlib-version>version</tlib-version>標(biāo)記庫(kù)的版本
<short-name>prefix</short-name>前綴名稱(chēng)
<uri>uri</uri>引用的地址
...
<tag>
<name>tagname</name>標(biāo)記名稱(chēng)
<tag-class>classname</tag-class>標(biāo)記對(duì)應(yīng)的處理類(lèi)
<tei-class>classname</tei-class>標(biāo)記處理類(lèi)的輔助處理類(lèi)
<body-content>[JSP,empty,scriptless,tagdependent]</body-content>
//jsp表示標(biāo)記中可以包含html,java代碼,這些代碼可以被運(yùn)行
//empty表示標(biāo)記中不包含內(nèi)容
//scriptless表示標(biāo)記中可以包含EL,jsp的動(dòng)作代碼,不可以包括JAVA腳本代碼
//tagdependent表示標(biāo)記中可以包含
<attribute>標(biāo)記的屬性
<name>pattern</name>屬性的名稱(chēng)
<required>false</required>表示該屬性是否是必須的
<rtexprvalue>false</rtexprvalue>該屬性是否可以是JSP的表達(dá)式
</attribute>
</tag>
</taglib>
TagSupport運(yùn)行原理(不能對(duì)標(biāo)記所包含的內(nèi)容進(jìn)行二次加工)
BodyTagSupport運(yùn)行原理(可以對(duì)開(kāi)始和結(jié)束標(biāo)記所包含的內(nèi)容進(jìn)行處理)
public int doAfterBody()throws JspTagException{
BodyContent bc=getBodyContent();取內(nèi)容
String input=bc.getString();取內(nèi)容
JspWriter out=bc.getEnclosingWriter();
String newContent=input;
try{
out.println(newContent);
}catch(IOException e){
throw new JspTagException(e);
}
return 1;
}