当项目为null时,如何使用Primefaces和JSF EL使用三元运算符来呈现特定文本?

问题描述

如果我使用JSF Primefaces 7.0渲染xhtml文件以显示用户(括号内的用户名)或用户名(如果用户名为空或为空字符串),那么我希望仅显示不带括号的用户名。


pom.xml:

<!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.xhtml:

User: John Doe (jdoe)

渲染(在网络浏览器内部):

#{userReport.selectedUser.name}

但是,如果User: (jdoe) 为null,则会在括号内显示用户名:

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>

使用以下方法解决:

? :

有没有一种更简单的方法来做到这一点?例如,使用三元select LOG_DATE,ITEM_ID,PROBLEM,(case when row_number() over (partition by CALL_DATE,UCID,ID,ACCOUNT_NO,CALL_STATUS order by log_date desc) = 1 then call_date end) as call_date,CALL_STATUS order by log_date desc) = 1 then ucid end) as ucid,. . . from t; 运算符?

解决方法

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...