如何比较 EL 中的 char 属性 [英] How to compare a char property in EL

查看:21
本文介绍了如何比较 EL 中的 char 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的命令按钮.

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.

有两种解决方法:

  1. 使用 String#charAt(),传递 0,从 Stringchar代码>在EL.请注意,这仅在您的环境支持 EL 2.2 时才有效.否则你需要安装 JBoss EL.

  1. Use String#charAt(), passing 0, to get the char out of a String 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 中使用 char 的数字表示,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 中的 char 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆