stackh34p
stackh34p

Reputation: 8999

JSF input failed to Double conversion error

I have a JSF2 application that uses Spring 3.0. I have a bean that has a property of type List<Double> with 5 elements:

public class MyBean {
    private List<Double> values; 
    public List<Double> getValues() {
        if (values == null) {
            values = new ArrayList<Double>(5);
                for (int i = 0; i < 5; i++) {
                    values.add(null);
                }
        }
        return values;
    }
    public void setValues(List<Double> values) {
        this.values = values;
    }
}

In my xhtml file I have this for every element:

<h:inputText id="value1" value="#{myBean.values[0]}">
    <f:convertNumber pattern="#########0.##" />
</h:inputText>

My purpose is to retrieve the values as ArrayList. Also, I do not want to keep individual properties for each member. A future requirement will make the value's total number to be dynamic (not the hard-coded 5), so I may use a loop to define the inputs for each element, but lets not focus on this now.

So here is the problem. When I submit the page, the conversion is not correct. For instance, if my input was 1, 2.0, 3 (and 2 empty inputs for the last two elements, they are not mandatory), I am receiving the following array [1, "2.0", 3, "", ""], where 1 and 3 are of type BigDecimal, and 2.0 and the last 2 members are empty strings. This causes ClassCastexception each time I try to get a member of the array list, because by definition is generic and the generic type is Double. BigDecimal cannot be cast to Double; it is obvious that the string cast attempts will also fail. Now, I'd have expected at least all members to be converted by the converter and be of the same type. Also, I need a way to get correctly as Double. I also tried the following:

<h:inputText id="value1" value="#{myBean.values[0]}">
    <f:converter id="javax.faces.Double" />
</h:inputText>

but it caused an exception:

<f:converter> Default behavior invoked of requiring a converter-id passed in the constructor, must override ConvertHandler(ConverterConfig)

I must admit I am new to the JSF technology, but as far as this article is concerned, there was no need to override anything. Any help will be appreciated

Upvotes: 5

Views: 9097

Answers (1)

BalusC
BalusC

Reputation: 1108537

The <f:converter> doesn't have an id attribute, instead it is converterId. See also the tag documentation. So, this should do:

<h:inputText id="value1" value="#{myBean.values[0]}">
    <f:converter converterId="javax.faces.Double" />
</h:inputText>

or even

<h:inputText id="value1" value="#{myBean.values[0]}" converter="javax.faces.Double" />

Upvotes: 15

Related Questions