开发者

<h:selectManyListbox JSF and Enums Class Cast error

开发者 https://www.devze.com 2023-02-17 05:56 出处:网络
This drives me crazy, cannot find the error. Here the xhtml page: ... <h:selectManyListbox style=\"width: 207px\" size=\"10\" value=\"#{reportBean.selectedSeverities}\">

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 co开发者_如何转开发mmand 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


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:

  • How to use enums in select many menus?
0

精彩评论

暂无评论...
验证码 换一张
取 消