Jsf 2 如何在jsf中使用if,else条件来显示图像

Jsf 2 如何在jsf中使用if,else条件来显示图像,jsf-2,jstl,Jsf 2,Jstl,我有一个条件,其中我有一个注册表单,其中如果userid为0,它应该显示虚拟图像,当我从任何更新编辑用户时,我检查userid是否不等于0,然后显示与userid对应的图像 我在jsf页面中使用了JSTL。但它总是尝试转到else循环以显示图像。该功能运行良好。唯一的问题是,当我第一次访问页面时,我不能显示虚拟图像。这是我的密码 <c:if test="${'#{user.userId}' == '0'}"> <a href="Images/thumb_02.jpg" ta

我有一个条件,其中我有一个注册表单,其中如果userid为0,它应该显示虚拟图像,当我从任何更新编辑用户时,我检查userid是否不等于0,然后显示与userid对应的图像

我在jsf页面中使用了JSTL。但它总是尝试转到else循环以显示图像。该功能运行良好。唯一的问题是,当我第一次访问页面时,我不能显示虚拟图像。这是我的密码

<c:if test="${'#{user.userId}' == '0'}">
  <a href="Images/thumb_02.jpg" target="_blank" ></a>
  <img src="Images/thumb_02.jpg" />
</c:if>
<c:otherwise>
  <a href="/DisplayBlobExample?userId=#{user.userId}" target="_blank"</a>
  <img src="/DisplayBlobExample?userId=#{user.userId}" />
</c:otherwise>


嵌套EL表达式是非法的:您应该内联它们。在您的情况下,使用JSTL是完全有效的。更正错误后,您将使代码正常工作:

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:c="http://java.sun.com/jstl/core">
    <c:if test="#{not empty user or user.userId eq 0}">
        <a href="Images/thumb_02.jpg" target="_blank" ></a>
        <img src="Images/thumb_02.jpg" />
    </c:if>
    <c:if test="#{empty user or user.userId eq 0}">
        <a href="/DisplayBlobExample?userId=#{user.userId}" target="_blank"></a>
        <img src="/DisplayBlobExample?userId=#{user.userId}" />
    </c:if>
</html>

另一种解决方案是在一个元素的EL中指定所需的所有条件。虽然它可能更重,可读性也更低,但它是:

<a href="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></a>
<img src="#{not empty user or user.userId eq 0 ? '/Images/thumb_02.jpg' : '/DisplayBlobExample?userId='}#{not empty user or user.userId eq 0 ? '' : user.userId}" target="_blank"></img>

对于像我这样的人来说,他们刚刚通过skuntsel跟踪了代码并收到了一个神秘的堆栈跟踪,请允许我为您节省一些时间

似乎
c:if
本身不能后跟
c:others

正确的解决方案如下:

<c:choose>
    <c:when test="#{some.test}">
        <p>some.test is true</p>
    </c:when>
    <c:otherwise>
        <p>some.test is not true</p>
    </c:otherwise>
</c:choose>

有些测试是真的

有些测试是不正确的

您可以在必要时添加额外的
c:when
测试。

也可以执行以下操作,而不是使用“c”标记:

<h:outputLink value="Images/thumb_02.jpg" target="_blank" rendered="#{not empty user or user.userId eq 0}" />
<h:graphicImage value="Images/thumb_02.jpg" rendered="#{not empty user or user.userId eq 0}" />

<h:outputLink value="/DisplayBlobExample?userId=#{user.userId}" target="_blank" rendered="#{not empty user and user.userId neq 0}" />
<h:graphicImage value="/DisplayBlobExample?userId=#{user.userId}" rendered="#{not empty user and user.userId neq 0}"/>

我认为这比skuntsel的备选答案更具可读性,并且使用JSF呈现属性,而不是嵌套三元运算符。
在回答问题时,您是否打算将图像放在锚定标签之间,以便图像可以单击?

您编写了一个更新,这太好了!刚刚更正了我的答案,这样它也可以编译。重读您的答案有时会有所帮助。另外值得注意的是,在应用请求值阶段,some.test的计算结果不需要为false。更多信息请参见此处(第5点):这不仅会导致(几乎)重复代码,而且会使计算时间加倍。考虑<代码> C:选择+c:当+C:否则,< /代码>。