我想编写一个自定义JSP标签,其输出包括其他JSP标签,它们本身也应该是动态评估的.但是显然,我的TagSupport子类写入pageContext.getOut()的所有内容都直接进入客户端,无需任何进一步的评估.
我有一种感觉,这应该是非常简单的,因为它似乎是第一个需要使用自定义标签的东西之一:封装和重用其他自定义标签,避免代码重复.
如何使以下代码执行显然要做的事情?:
public class MyTag extends TagSupport {
public int doStartTag() throws JspException {
try {
pageContext.getOut().println(
"The output from this tag includes other tags " +
"like <mypackage:myOtherTag>this one</mypackage:myOtherTag> " +
"which should themselves be evaluated and rendered."
)
} catch (IOException e) {
throw new JspException(e);
}
return SKIP_BODY;
}
}
编辑:有些背景我的具体用例,如果它有帮助.我有一个自定义标签< user>它以对我的应用程序有用的方式(鼠标悬停名字,姓氏,电话号码等)动态呈现用户名.我正在写另一个标签< comment>用于显示用户评论,我想使用我现有的< user>在< comment>的输出中呈现用户名的标签标签.
您可以将类分成标签类和tagRenderer类.在你的情况下,会有两个名为CommentTagRenderer和UserTagRenderer的新类.
这是一个新的CommentTag的例子
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
Comment comment = getComment();
User user = getUser();
CommentTagRenderer commentRenderer = new CommentTagRenderer(out);
UserTagRenderer userRenderer = new UserTagRenderer(out);
try {
commentRenderer.renderComment(comment);
userRenderer.renderUser(user);
} catch (IOException e) {
//some error handling
}
return SKIP_BODY;
}
这里是CommentTagRenderer的一个例子
private Writer out;
public CommentTagRenderer(Writer out) {
this.out = out;
}
public void renderComment(Comment comment) throws IOException {
out.write("<div>");
out.write(comment.getComment());
out.write("</div>");
}
