定制標記庫
1 編寫標記處理類
public class TimerTag extends TagSupport{
private long start;
private long end;
public int doStartTag(){ //doStartTag標記開始方法
start=System.currentTimeMillis();
return EVAL_BODY_INCLUDE;//
}
public int doEndTag() throws JspTagException {//doEndTag標記結束方法
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 編寫.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> //對當前標記庫的描述
<tlib-version>1.0</tlib-version> //當前標記庫的版本
<short-name>util</short-name> //對當前標記庫使用時的前綴名稱
<uri>http://163.com</uri> //可任意
<tag>
<description>calc code running time</description> //對當前標記的描述
<name>timer</name> //標記我名稱
<tag-class>com.tags.TimerTag</tag-class> 當前標記對應的處理類的具體名稱
<body-content>JSP</body-content> //可有empty,JSP
</tag>
</taglib>
3 使用格式
jsp頁面
<%@ taglib prefix="util" uri="http://163.com" %> 添加指令
<util:timer></util:timer>
總結:
TLD是一個XML文件,在WEB-INF目錄下
<taglib>根元素
<tlib-version>version</tlib-version>標記庫的版本
<short-name>prefix</short-name>前綴名稱
<uri>uri</uri>引用的地址
...
<tag>
<name>tagname</name>標記名稱
<tag-class>classname</tag-class>標記對應的處理類
<tei-class>classname</tei-class>標記處理類的輔助處理類
<body-content>[JSP,empty,scriptless,tagdependent]</body-content>
//jsp表示標記中可以包含html,java代碼,這些代碼可以被運行
//empty表示標記中不包含內容
//scriptless表示標記中可以包含EL,jsp的動作代碼,不可以包括JAVA腳本代碼
//tagdependent表示標記中可以包含
<attribute>標記的屬性
<name>pattern</name>屬性的名稱
<required>false</required>表示該屬性是否是必須的
<rtexprvalue>false</rtexprvalue>該屬性是否可以是JSP的表達式
</attribute>
</tag>
</taglib>
TagSupport運行原理(不能對標記所包含的內容進行二次加工)

BodyTagSupport運行原理(可以對開始和結束標記所包含的內容進行處理)
public int doAfterBody()throws JspTagException{
BodyContent bc=getBodyContent();取內容
String input=bc.getString();取內容
JspWriter out=bc.getEnclosingWriter();
String newContent=input;
try{
out.println(newContent);
}catch(IOException e){
throw new JspTagException(e);
}
return 1;
}
posted on 2009-11-29 22:29
junly 閱讀(1499)
評論(0) 編輯 收藏 所屬分類:
jsp/servlet