简体   繁体   English

自定义JSP标记 - 如何获取标记的主体?

[英]Custom JSP tag - How do I get the body of the tag?

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? 在自定义标记中,如何获取正文的文本?

It's complicated because there are two mechanisms. 它很复杂,因为有两种机制。

If you're extending SimpleTagSupport, you get getJspBody() method. 如果您正在扩展SimpleTagSupport,则会获得getJspBody()方法。 It returns a JspFragment that you can invoke(Writer writer) to have the body content written to the writer. 它返回一个可以调用的JspFragment (Writer 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 are using classic tags, you extend BodyTagSupport and so get access to a getBodyContent() method. 如果使用的是经典的标签,您扩展BodyTagSupport等获得访问getBodyContent()方法。 That gets you a BodyContent object that you can retrieve the body content from. 这将为您提供一个BodyContent对象,您可以从中检索正文内容。

If you are using a custom tag with jsp 2.0 approach, you can do it as: 如果您使用jsp 2.0方法的自定义标记,则可以这样做:

make-h1.tag 化妆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>

To expand on Brabster's answer , I've used SimpleTagSupport.getJspBody() to write the JspFragment to an internal StringWriter for 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());
    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM