如何比较EL中的char属性 [英] How to compare a char property in EL
问题描述
我有一个命令按钮,如下所示。
I have a command button like below.
<h:commandButton value="Accept orders" action="#{acceptOrdersBean.acceptOrder}"
styleClass="button" rendered="#{product.orderStatus=='N' }"></h:commandButton>
等于'N'
命令按钮不显示在我的页面中。
even when the product.orderStatus
value is equal to 'N'
the command button is not displayed in my page.
这里 product.orderStatus
是一个字符属性。
推荐答案
在EL中,任何引用如'N'
的东西总是作为 String
和 char
属性值始终被视为数字。 char
在EL代表的Unicode代码点, 78
代表 N
。
This is, unfortunately, expected behavior. In EL, anything in quotes like 'N'
is always treated as a String
and a char
property value is always treated as a number. The char
is in EL represented by its Unicode codepoint, which is 78
for N
.
有两种解决方法:
-
使用
String#charAt()
传递0
在EL中的String
中的$ c> char 请注意,这只有在您的环境支持EL 2.2时才有效。否则,您需要安装 JBoss EL 。
Use
String#charAt()
, passing0
, to get thechar
out of aString
in EL. Note that this works only if your environment supports EL 2.2. Otherwise you need to install JBoss EL.
<h:commandButton ... rendered="#{product.orderStatus eq 'N'.charAt(0)}">
在Unicode中使用字符的数字表示, N
。您可以通过 System.out.println((int)'N')
找出正确的Unicode代码点。
Use the char's numeric representation in Unicode, which is 78 for N
. You can figure out the right Unicode codepoint by System.out.println((int) 'N')
.
<h:commandButton ... rendered="#{product.orderStatus eq 78}">
>,但是,使用枚举:
public enum OrderStatus {
N, X, Y, Z;
}
与
private OrderStatus orderStatus; // +getter
那么你可以在EL中使用所需的语法:
then you can use exactly the desired syntax in EL:
<h:commandButton ... rendered="#{product.orderStatus eq 'N'}">
额外的好处是枚举强制类型安全。您将无法指定如☆
或웃
作为订单状态值的任何字符。
Additional bonus is that enums enforce type safety. You won't be able to assign an aribtrary character like ☆
or 웃
as order status value.
这篇关于如何比较EL中的char属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!