java 自定义 JSP 标记 - 如何获取标记的正文?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2502282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom JSP tag - How do I get the body of the tag?
提问by Kyle
I have a custom jsp tag like this:
我有一个像这样的自定义 jsp 标签:
<a:customtag>
The body of the custom tag...
More lines of the body...
</a:customtag>
In the custom tag, how can I get the text of what the body is?
在自定义标签中,如何获取正文的文本?
回答by brabster
It's complicated because there are two mechanisms.
这很复杂,因为有两种机制。
If you're extending SimpleTagSupport, you get getJspBody()method. It returns a JspFragment that you can invoke(Writer writer)to have the body content written to the writer.
如果您要扩展 SimpleTagSupport,您将获得getJspBody()方法。它返回一个 JspFragment,您可以调用它(Writer writer)将正文内容写入编写器。
You should use SimpleTagSupport unless you have a specific reason to use BodyTagSupport (like legacy tag support) as it is - well - simpler.
您应该使用 SimpleTagSupport ,除非您有特定的理由使用 BodyTagSupport(如旧标签支持),因为它 - 好吧 - 更简单。
If you areusing classic tags, you extend BodyTagSupport and so get access to a getBodyContent()method. That gets you a BodyContent object that you can retrieve the body content from.
如果您正在使用经典的标签,您扩展BodyTagSupport等获得访问getBodyContent()方法。这将为您提供一个 BodyContent 对象,您可以从中检索正文内容。
回答by Alireza Fattahi
If you are using a custom tag with jsp 2.0 approach, you can do it as:
如果您使用带有 jsp 2.0 方法的自定义标记,您可以这样做:
make-h1.tag
make-h1.tag
<%@tag description="Make me H1 " pageEncoding="UTF-8"%>
<h1><jsp:doBody/></h1>
Use it in JSP as:
在 JSP 中使用它作为:
<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%>
<t:make-h1>An important head line </t:make-h1>
回答by brasskazoo
To expand on Brabster's answer, I've used SimpleTagSupport.getJspBody()to write the JspFragmentto an internal StringWriterfor inspection and manipulation:
为了扩展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());
}
}
}
}

