从自定义标签创建 Struts2 标签
我正在尝试从自定义标记将 Struts2 标记写入我的 JSP。我有下面的代码。这实际上可能吗?还是 JSP 生命周期中存在某些因素导致这不可能?如果不可能,是否有其他方法可以完成我想做的事情?
while (iterator.hasNext()) {
Bulletin bulletin = (Bulletin) iterator.next();
if (bulletin.isApproved()) {
out.println("<s:url value=\"GetSingleBulletin\">");
out.println("<s:param name=\"id\" "
+ "value=\"%{" + bulletin.getId()+ "}\" />");
out.println(bulletin.getName() + " -- " + bulletin.getSubject()
+ " " + bulletin.getDate());
out.println("</s:url>");
out.println("<br><br>");
}
}
I'm trying to write a Struts2 tag to my JSP from a custom tag. I have the code below. Is this actually possible, or is there something about the JSP life cycle that makes this impossible? If it is impossible, is there another way to do what I'm trying to do?
while (iterator.hasNext()) {
Bulletin bulletin = (Bulletin) iterator.next();
if (bulletin.isApproved()) {
out.println("<s:url value=\"GetSingleBulletin\">");
out.println("<s:param name=\"id\" "
+ "value=\"%{" + bulletin.getId()+ "}\" />");
out.println(bulletin.getName() + " -- " + bulletin.getSubject()
+ " " + bulletin.getDate());
out.println("</s:url>");
out.println("<br><br>");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标签作为将 JSP 转换为 servlet 的“转换阶段”的一部分进行解析。通过在标签中发出其他标签,您将假设进行“第二遍”翻译,但这种情况不会发生。所以这从根本上来说是一个坏主意。
相反,我建议只发出等效的 HTML(实际上只是一个带有参数的 URL,根据上面的代码)。假设您的问题并不比上面描述的更复杂,这似乎是最简单的方法。事实上,即使您可以发出标签,我也没有看到一个非常令人信服的案例来说明为什么标签比原始 HTML 更好。 JSP 标签库应该促进自动化并尽可能减少代码;更少的代码可以减少错误并使 JSP 更易于维护。但你上面的案例并不是一个尖叫着“必须使用标签”的案例。
或者,如果您确实更喜欢使用上面的自定义标记中的标记,或者您愿意完全消除标记库,您可以在 scriptlet 中编写上面的 Java 代码,并将对其他 struts 标记的使用散布在该 scriptlet 代码之间。所以,像这样:
Tags are resolved as part of the "translation phase" that converts a JSP to a servlet. By emitting other tags in your tag, you are assuming a "2nd pass" translation, which does not happen. So it's fundamentally a bad idea.
Instead, I would suggest just emitting the equivalent HTML (really just a URL with parameters, given your code above). Assuming your problem is no more complex than what you describe above, this seems like the simplest approach. In fact, even if you could emit tags, I don't see a very convincing case here for why tags would be better than raw HTML anyway. JSP taglibs are supposed to facilitate automation and less code where possible; less code reduces errors and makes JSPs more maintainable. But your case above is not one that screams out for "must use tags".
Alternatively, if you would really prefer to use the tags you have in your custom tag above, or you would be willing to eliminate your taglib altogether, you could write the above Java code in a scriptlet and intersperse your use of the other struts tags in between that scriptlet code. So, something like:
不,不可能 out.println 仅允许在 html tag.fa 中
No its not possible out.println allowed only in html tag.fa