How to compare a char property in EL
Asked Answered
L

1

8

I have a command button like below.

<h:commandButton value="Accept orders" action="#{acceptOrdersBean.acceptOrder}"
   styleClass="button" rendered="#{product.orderStatus=='N' }"></h:commandButton>

even when the product.orderStatus value is equal to 'N' the command button is not displayed in my page.

Here product.orderStatus is a character property.

Lyre answered 22/1, 2013 at 8:23 Comment(4)
Is product a bean name?Bed
What do you see when you add this to your page <h:outputText value="orderstatsu= #{product.orderStatus}"/>. Is it N or something else?Puga
@Matt:yes product here is a bean nameLyre
@roel: i can see N only.Lyre
C
14

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.

There are two workarounds:

  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)}">
    
  2. 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}">
    

The real solution, however, is to use an enum:

public enum OrderStatus {
     N, X, Y, Z;
}

with

private OrderStatus orderStatus; // +getter

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.

Coexist answered 22/1, 2013 at 11:34 Comment(4)
My test case with private char testChar = 'N'; + getter/setter and with <h:commandButton action=".." value="TestButton" rendered="#{sessionBean.testChar == 'N'}"/> worked perfectly. The button is hidden if I change the test to sessionBean.testChar == 'J'.Bed
@Matt: What EL impl are you using?Coexist
It is Glassfish 3.1.2 with no extra libs installed. Must be 2.2, correct?Bed
@Matt: Apparently they enhanced(?) their EL impl. It fails in Tomcat as per EL spec.Coexist

© 2022 - 2024 — McMap. All rights reserved.