Kyl*_*yle 9 java jsp jsp-tags java-ee
我有一个这样的自定义jsp标签:
<a:customtag>
The body of the custom tag...
More lines of the body...
</a:customtag>
Run Code Online (Sandbox Code Playgroud)
在自定义标记中,如何获取正文的文本?
bra*_*ter 12
它很复杂,因为有两种机制.
如果您正在扩展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>
Run Code Online (Sandbox Code Playgroud)
在JSP中使用它:
<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%>
<t:make-h1>An important head line </t:make-h1>
Run Code Online (Sandbox Code Playgroud)
为了扩展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());
}
}
Run Code Online (Sandbox Code Playgroud)
}
| 归档时间: |
|
| 查看次数: |
15294 次 |
| 最近记录: |