【发布时间】:2011-01-30 22:20:46
【问题描述】:
我有一个这样的自定义 jsp 标签:
<a:customtag>
The body of the custom tag...
More lines of the body...
</a:customtag>
在自定义标签中,如何获取body是什么的文字?
【问题讨论】:
标签: java jsp jakarta-ee jsp-tags
我有一个这样的自定义 jsp 标签:
<a:customtag>
The body of the custom tag...
More lines of the body...
</a:customtag>
在自定义标签中,如何获取body是什么的文字?
【问题讨论】:
标签: java jsp jakarta-ee jsp-tags
这很复杂,因为有两种机制。
如果您正在扩展 SimpleTagSupport,您将获得 getJspBody() 方法。它返回一个 JspFragment,您可以通过 invoke(Writer writer) 将正文内容写入作者。
您应该使用 SimpleTagSupport,除非您有特定理由使用 BodyTagSupport(如旧标签支持),因为它 - 好 - 更简单。
如果您正在使用经典标签,您可以扩展 BodyTagSupport 并因此可以访问getBodyContent() 方法。这将为您提供一个 BodyContent 对象,您可以从中检索正文内容。
【讨论】:
如果您使用带有 jsp 2.0 方法的自定义标记,您可以这样做:
make-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>
【讨论】:
An important head line 替换为 <t:MyMessageTag key="someKey"> <jsp:doBody /> 似乎将其替换为小写 @ 987654326@ 并且不会评估该 jsp-tag。知道为什么吗?或者如何处理这种嵌套标签?
body-content 属性声明为tagdependent 而不是默认的scriptless - 现在一切都很好。
为了扩展Brabster's answer,我使用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());
}
}
}
【讨论】: