Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
353 views
in Technique[技术] by (71.8m points)

jsf - 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>

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...