- 帶有標籤體的自定義標籤
1)若有一個標籤體:
<c1:date >sssss</c1:date>
在自定義標籤的標籤處理器中使用JspFragment對象封裝了標籤體的信息
- 若配置了標籤含有標籤體,則jsp會調用setJspBody()方法把JspFragment傳遞給標籤處理類。在SimpleTagSupport中還定義了一個getJspBody()方法用於返回JspFragment對象。
2.JspFragment的invoke(Writer)方法:把標籤體內容從Writer中輸出,若爲null,則等同於invole(getJspContext.getOut()),即直接把標籤體內容直接輸出到頁面上
public void doTag() throws JspException, IOException {
// TODO Auto-generated method stub
super.doTag();
JspFragment bFragment = getJspBody();
// JspFragment.invoke(Writer): Writer即爲標籤體內容的輸出的字符流,若爲null則爲
// 輸出到getJspContext.getOut(),即輸出到頁面上去
bFragment.invoke(null);
}
- 在tld文件中,使用<body-content>指定標籤體的類型:
大部分情況下取值爲tagdependent:
>empty:沒有標籤體
>scriptless:不能有jsp腳本元素,但是可以有el表達式和JSp動作元素
>tagdependent:表示標籤體交由標籤體本身去解析處理,若指定爲tagdependent,在標籤體中的所有代碼都會原封不懂的交給標籤處理器。而不是將執行結果傳給標籤處理器
- 開發父標籤的標籤
1)父標籤無法獲取子標籤的引用。父標籤僅把子標籤作爲標籤體來使用
2)子標籤可以通過getParent()方法來獲取父標籤的引用(需繼承SimpleTagSupport或自實現SimpleTag接口中的該方法)若子標籤的確有父標籤,JSP引擎會把父標籤的引用通過setParent(jspTag parent)付給標籤處理器
3)注意父標籤的類型時JspTag類型,該接口是一個空接口,但是來統一SimpleTag和Tag的,實際使用需要進行強制轉換爲父標籤的處理器類
- 在tld文件中,無需爲父標籤有額外的配置,但,子標籤是是以標籤體的形式存在的。所有父標籤的 <body-content>scriptless</body-content> 需要設置爲 scriptless;
下列是具體的代碼
*****************父標籤的處理器類**************
public class FatherTag extends SimpleTagSupport {
private String name;
public void doTag() throws JspException, IOException {
// TODO Auto-generated method stub
super.doTag();
System.out.println("父類標籤正在加載" + name);
//可以通過這個方法來使父標籤中的子標籤當作一個標籤來輸出
getJspBody().invoke(null);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
************************子標籤的實現*********************
public class SonTag extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
super.doTag();
// 1.獲取父類標籤的對象
JspTag f_Tag = getParent();
// 2.獲取這個父類標籤中的屬性
FatherTag fatherTag = (FatherTag) f_Tag;
String name = fatherTag.getName();
// 3.把name值打印到JSP頁面上
getJspContext().getOut().print("子標籤正在加載" + name);
}
}