Wednesday 15 February 2012

JSF: How to bind a Double to and format it (or: How to tackle "java.lang.Long cannot be cast to java.lang.Double")

The problem:If the inputText is bound to a Double and an integer value is given (e.g. 100) then a java.lang.Long cannot be cast to java.lang.Double exception is thrown.

The solution (hint):The solution is at the end of the post..

Goal 1: Bind the Double attribute value of the ManagedBean fooBean into a inputText

<p:inputText value="#{fooBean.value}" />
OK the above works fine.

Goal 2: Add formatting

<p:inputText value="#{fooBean.value}">
  <f:convertNumber maxFractionDigits="2" type="number"/>
</p:inputText>
But...if I give as input a number without a decimal part (e.g. 100) a coversion exceptions is thrown: java.lang.Long cannot be cast to java.lang.Double. The reason for this exception is described in stack overflow Phill's post:

After some investigation (see e.g. here, here and here) that <f:convertNumber> is the problem. It seems that the number it converts to is dependent on the input you give it - it could be an integer or a floating point number. In other words, it doesn't look at the target type - it just generates an instance of java.lang.Number. Which is hardly ideal, although I can't determine whether this is because somewhere I'm using an old version of JSF or EL or something like that. Proposals from the internet:

  • Add converterId="javax.faces.Double" into ...But: accepts and validates doubles but formatting doesn't work! (see )

Solution

In a few words..Formating works only if the value is bound to a BigDecimal! Double doesn't work :(
<p:inputText value="#{fooBean.value}" style="width:50px">
  <f:validateDoubleRange />
  <f:convertNumber maxFractionDigits="2" type="number"/>
</p:inputText>

References of people tackling the same problem

No comments:

Post a Comment