如何将List <integer>值绑定到JSF </integer>中的selectManyListbox

时间:2012-12-13 18:07:00

标签: jsf-2 glassfish managed-bean

情况: 我有一个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;
    }
}

1 个答案:

答案 0 :(得分:8)

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

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

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

只是改为使用Integer[],其类型信息在运行时清楚地知道:

private Integer[] selection;