如何比较 EL 中的字符属性 [英] 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>
即使 product.orderStatus
值等于 'N'
命令按钮也不会显示在我的页面中.
even when the product.orderStatus
value is equal to 'N'
the command button is not displayed in my page.
这里的 product.orderStatus
是一个字符属性.
Here product.orderStatus
is a character property.
推荐答案
不幸的是,这是预期的行为.在 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
,从String
中取出char
代码> EL.请注意,这仅在您的环境支持 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
为 78.您可以通过 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 中的字符属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!