【问题标题】:How do I get selectManyCheckBox to return something other than List<String>?如何让 selectManyCheckBox 返回 List<String> 以外的内容?
【发布时间】:2011-09-03 16:18:23
【问题描述】:

如果我让它发挥作用,我会一遍又一遍地使用这种模式。我有一个枚举名称 Log.LogKey,我希望用户从中挑选出实例。所以facelet有这个:

             <h:form id="testForm" >

                <h:selectManyCheckbox value="#{test.selectedKeys}" >
                    <f:selectItems value="#{test.allKeys}"
                                   var="lk"
                                   itemLabel="#{lk.display}"
                                   itemValue="#{lk}" />
                </h:selectManyCheckbox>

                <h:commandButton value="Do It" action="#{test.doNothng}" />

            </h:form>

枚举有一个名为 getDisplay() 的 getter。 selectItems 属性正确调用它,因为这是呈现给用户的字符串。支持 bean 有这个:

public class Test implements Serializable {

private List<Log.LogKey> selectedKeys = null;

public List<Log.LogKey> getAllKeys() {
    return Arrays.asList(Log.LogKey.values());
}

public List<Log.LogKey> getSelectedKeys() { return selectedKeys; }

public void setSelectedKeys(List selected) {
    System.out.println("getSelecgedKeus() got " + selected.size());
    int i = 0;
    for (Object obj : selected) {
        System.out.println(i++ + " is " + obj.getClass() + ":" + obj);
    }
}

public String doNothng() { return null; }

}

所以在提交表单时,数组 setSelectedKeys(selected) 被调用一个字符串列表,而不是 Log.LogKey 列表。 selectItems 标记中对 #{lk} 的引用将对象转换为字符串。这样做的正确方法是什么?

【问题讨论】:

    标签: jsf-2


    【解决方案1】:

    您需要指定转换器。 JSF EL 不知道泛型 List 类型,因为它在运行时丢失了。如果您没有明确指定转换器,JSF 将不会转换提交的 String 值并用它们填充列表。

    在您的特定情况下,您可以使用 JSF 内置 EnumConverter,您只需 super() 构造函数中的枚举类型:

    package com.example;
    
    import javax.faces.convert.EnumConverter;
    import javax.faces.convert.FacesConverter;
    
    @FacesConverter(value="logKeyConverter")
    public class LogKeyConverter extends EnumConverter {
    
        public LogKeyConverter() {
            super(Log.LogKey.class);
        }
    
    }
    

    要使用它,只需声明如下:

    <h:selectManyCheckbox value="#{test.selectedKeys}" converter="logKeyConverter">
        ...
    </h:selectManyCheckbox>
    

    另见:

    【讨论】:

    • 我不知道我是怎么错过其他帖子的。再次感谢。
    • 不客气。也许您省略了“枚举”作为搜索关键字;)
    猜你喜欢
    • 1970-01-01
    • 2016-11-27
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多