Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare a char property in EL

Tags:

char

jsf

el

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.

like image 894
Sasi Kumar M Avatar asked Jan 22 '13 08:01

Sasi Kumar M


People also ask

Can I use == to compare char?

Yes, char is just like any other primitive type, you can just compare them by == .

How do I compare chars to chars?

compare(char x, char y); If both chars “x” and “y” are the same, the compare() method will return “0”. If the first char is less than the second char, it will return a negative value. Similarly, the specified method will return a positive value when the first char is greater than the second char.

How do you compare char data types?

We can compare the char values numerically by using compare(char x, char y) method of Character class. Note: Comparing char primitive values using Character. compare(char x, char y) method returns an integer value.


1 Answers

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.

like image 68
BalusC Avatar answered Sep 26 '22 06:09

BalusC