[英]Custom JSP tag - How do I get the body of the tag?
我有一個這樣的自定義jsp標簽:
<a:customtag>
The body of the custom tag...
More lines of the body...
</a:customtag>
在自定義標記中,如何獲取正文的文本?
它很復雜,因為有兩種機制。
如果您正在擴展SimpleTagSupport,則會獲得getJspBody()方法。 它返回一個可以調用的JspFragment (Writer writer),以將正文內容寫入writer。
您應該使用SimpleTagSupport,除非您有特定的理由使用BodyTagSupport(如傳統標記支持),因為它更簡單。
如果使用的是經典的標簽,您擴展BodyTagSupport等獲得訪問getBodyContent()方法。 這將為您提供一個BodyContent對象,您可以從中檢索正文內容。
如果您使用jsp 2.0方法的自定義標記,則可以這樣做:
化妝h1.tag
<%@tag description="Make me H1 " pageEncoding="UTF-8"%>
<h1><jsp:doBody/></h1>
在JSP中使用它:
<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%>
<t:make-h1>An important head line </t:make-h1>
為了擴展Brabster的答案 ,我使用SimpleTagSupport.getJspBody()
將JspFragment
寫入內部StringWriter
以進行檢查和操作:
public class CustomTag extends SimpleTagSupport {
@Override public void doTag() throws JspException, IOException {
final JspWriter jspWriter = getJspContext().getOut();
final StringWriter stringWriter = new StringWriter();
final StringBuffer bodyContent = new StringBuffer();
// Execute the tag's body into an internal writer
getJspBody().invoke(stringWriter);
// (Do stuff with stringWriter..)
bodyContent.append("<div class='custom-div'>");
bodyContent.append(stringWriter.getBuffer());
bodyContent.append("</div>");
// Output to the JSP writer
jspWriter.write(bodyContent.toString());
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.