2

情况:我有一个 JavaServer Faces 页面和一个会话范围的托管 bean,它有两个ArrayList<Integer>属性:一个用于保存可能值的列表,另一个用于保存选定值的列表。在 JSF 页面上有一个<h:selectManyListBox>绑定了这两个属性的组件。

问题:提交表单后,所选值将转换为字符串(ArrayList 类型的属性实际上包含几个字符串!);但是,当我使用转换器时,会收到如下错误消息:

验证错误:值无效

问题:如何正确地将ArrayList<Integer>属性绑定到<h:selectManyListBox>组件?

谢谢你帮助我。

具体代码

JSF 页面:

<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core">
    <h:body>
        <h:form>
            <h:selectManyListbox value="#{testBean.selection}">
                <f:selectItems value="#{testBean.list}"></f:selectItems>
            </h:selectManyListbox>
            <h:commandButton action="#{testBean.go}" value="go" />
            <ui:repeat value="#{testBean.selection}" var="i">
                #{i}: #{i.getClass()}
            </ui:repeat>
        </h:form>
    </h:body>
</html>

和托管bean:

import java.io.Serializable;
import java.util.ArrayList;

@javax.faces.bean.ManagedBean
@javax.enterprise.context.SessionScoped
public class TestBean implements Serializable
{
    private ArrayList<Integer> selection;
    private ArrayList<Integer> list;

    public ArrayList<Integer> getList()
    {
        if(list == null || list.isEmpty())
        {
            list = new ArrayList<Integer>();
            list.add(1);
            list.add(2);
            list.add(3);
        }
        return list;
    }

    public void setList(ArrayList<Integer> list)
    {
        this.list = list;
    }

    public ArrayList<Integer> getSelection()
    {
        return selection;
    }

    public void setSelection(ArrayList<Integer> selection)
    {
        this.selection = selection;
    }

    public String go()
    {
            // This throws an exception: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
            /*for (Integer i : selection)
            {
                System.out.println(i);
            }*/
        return null;
    }
}
4

1 回答 1

8

的泛型类型信息List<Integer>在运行时丢失,因此仅看到的 JSF/ELList无法识别泛型类型Integer并假定它是默认类型(因为这是应用请求值阶段String底层调用的默认类型)。HttpServletRequest#getParameter()

您需要明确指定 a Converter,您可以使用 JSF 内置IntegerConverter

<h:selectManyListbox ... converter="javax.faces.Integer">

或者只是使用Integer[],它的类型信息在运行时是清楚的:

private Integer[] selection;
于 2012-12-13T18:32:45.273 回答