3

This drives me crazy, cannot find the error.

Here the xhtml page:

...
<h:selectManyListbox style="width: 207px" size="10" value="#{reportBean.selectedSeverities}">
                            <f:selectItems value="#{reportBean.severities}"/>
                        </h:selectManyListbox>
...

The report Bean:

...
private List<Severity> severities;
private List<Severity> selectedSeverities = new ArrayList<Severity>();
...
public List<Severity> getSeverities() {
   if (this.severities == null) {
        this.severities = new ArrayList<Severity>();
        this.severities.add(Severity.LOW);
        this.severities.add(Severity.HIGH);
        this.severities.add(Severity.UNDEFINED);
        this.severities.add(Severity.MEDIUM);
    }
        return severities;
}

For a command Button I have the following action method:

if (!selectedSeverities.isEmpty()) {
    Severity s = selectedSeverities.get(0);
}
return;

Wenn I select a severity(enum) and hit the commandbutton I get the following stack trace:

...
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to securityscan.util.Severity
...

I don't get it.

Any help is very apprecieated.

BR Reen

reen
  • 2,483
  • 5
  • 29
  • 40

1 Answers1

7

You can't use enums in combination with h:selectMany*** components without using a converter. JSF/EL does not see/know the generic type of each of the separate list items. In other words, it only sees a List and not List<Severity> and treats every item as a String, unless you tell it to do otherwise.

You need to create and specify a converter yourself. For enums, it's the best to extend the JSF-provided EnumConverter.

package com.example;

import javax.faces.convert.EnumConverter;
import javax.faces.convert.FacesConverter;

@FacesConverter(value="severityConverter")
public class SeverityConverter extends EnumConverter {

    public SeverityConverter() {
        super(Severity.class);
    }

}

(note that when you're still using the old JSF 1.2, you should be declaring this as <converter> in faces-config.xml instead of by @FacesConverter)

Which you use as follows:

<h:selectManyListbox converter="severityConverter">

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • You saved my live!!!! I searched all afternoon. Didn't know that I need a converter for a Enum. Thanks a lot for your help. – reen Mar 17 '11 at 15:12
  • You're welcome. It's by the way not specifically related to enums, but to all types. You would have the same problem with a `List` or something. The problem is just that JSF/EL don't know about the list type and blindlessly puts unconverted request parameter strings in there. See also the "See also" link at bottom of answer. Enums work fine without an explicit converter when using `` for example. – BalusC Mar 17 '11 at 15:13
  • OK, thats why I thought it was not necessary. I used enums in combination with – reen Mar 17 '11 at 15:31