如何使用使用 JSF EL 的 Primefaces 的三元运算符在项目为空时呈现特定文本?

How to use Ternary Operator using Primefaces using JSF EL to render specific text when items are null?

我正在使用 JSF Primefaces 7.0 呈现一个 xhtml 文件以显示用户(以及括号内的用户名)如果他的名字为 null 或空字符串,我希望只显示不带括号的用户名。


pom.xml:

<dependency>
    <groupId>org.primefaces</groupId>
    <artifactId>primefaces</artifactId>
    <version>7.0</version>
</dependency>
    <dependency>
    <groupId>org.primefaces.extensions</groupId>
    <artifactId>primefaces-extensions</artifactId>
    <version>7.0.3</version>
</dependency>

所以,现在这是我正确渲染的内容:

user.xhtml:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html
        xmlns="http://www.w3.org/1999/xhtml"
        xmlns:p="http://primefaces.org/ui"
        xmlns:ui="http://java.sun.com/jsf/facelets"
        xmlns:h="http://java.sun.com/jsf/html"
        xmlns:f="http://java.sun.com/jsf/core">

    User: #{userReport.selectedUser.name} (#{userReport.selectedUser.username})
</html>

渲染(在网络浏览器中):

User: John Doe (jdoe)

但是,如果 #{userReport.selectedUser.name} 为 null,它会在括号内呈现用户名:

User: (jdoe)

我需要它像这样呈现(没有括号):

User: jdoe

尝试使用三元运算符? :

#{userReport.selectedUser.name ? userReport.selectedUser.name (#{userReport.selectedUser.username}) : #{userReport.selectedUser.username} }

这会导致以下堆栈跟踪:

javax.servlet.ServletException: The identifier [#] is not a valid Java identifier as required by section 1.19 of the EL specification (Identifier ::= Java language identifier). This check can be disabled by setting the system property org.apache.el.parser.SKIP_IDENTIFIER_CHECK to true.
    at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:749)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:475)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:111)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

用这个解决了它:

User:<c:choose>
         <c:when test="#{not empty userReport.selectedUser.name}">
             #{userReport.selectedUser.name} ({userReport.selectedUser.username})
          </c:when>
          <c:otherwise>
             #{userReport.selectedUser.username}
          </c:otherwise>
     </c:choose>

有没有更简单的方法来做到这一点?例如,使用三元运算符 ? :?

使用 ? : 三元运算符和 += 串联运算符使其工作:

User: #{!empty(userReport.selectedUser.name) ? userReport.selectedUser.name += ' (' += userReport.selectedUser.username += ')' : userReportView.selectedUser.username}