我正在使用 jSTL 进行小型测试。它没有按预期的方式工作
这是小代码:
<c:set var="id" value="#{mBlog.blog.id}"/>
${id} //printing 4
<c:if test="${id > 0}">
<h:commandButton value="Update" action="#{mBlog.update}"/> //is not rendered
</c:if>
<c:if test="${id == 0}">
<h:commandButton value="Save" action="#{mBlog.save}"/> //is not rendered
</c:if>
我不知道出了什么问题。在显示屏中我只看到 4,没有其他内容。
最佳答案
JSTL 标记和 JSF UI 组件并不像您期望的编码那样同步运行。长话短说:JSTL in JSF2 Facelets... makes sense?仔细阅读本文。
在您的具体情况下,JSTL <c:if>
标记条件似乎取决于 JSF <f:event>
的结果标签。目前<c:if>
在 View 构建期间运行 <f:event>
尚未运行,因为它在预渲染 View 事件期间运行。因此#{mBlog.blog.id}
总是null
或任何其他默认值。
您需要使用JSF组件的rendered
属性来代替。它还可以使您的代码更加简洁。
<h:commandButton value="Update" action="#{mBlog.update}" rendered="#{mBlog.blog.id gt 0}" />
<h:commandButton value="Save" action="#{mBlog.save}" rendered="#{mBlog.blog.id eq 0}" />
然而,在调用该操作时,您将来还会遇到另一个潜在的问题。确保 bean 放入 View 范围内,而不是请求范围内。
关于java - 有条件渲染 <h :commandButton> using <c:if>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9779367/