jsf-2 - 如何让 selectManyCheckBox 返回 List<String> 以外的其他内容?

标签 jsf-2

如果我让它工作,我会一遍又一遍地使用这种模式。我有一个枚举名称 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>

枚举有一个名为 的 setter/getter getDisplay() . 选择项目 属性正确调用它,因为这是呈现给用户的字符串。支持 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 列表调用。引用 #{lk} 选择项目 tag 正在将对象转换为字符串。这样做的正确方法是什么?

最佳答案

您需要指定一个转换器。 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>

也可以看看:
  • Use enum in h:selectManyCheckbox
  • 关于jsf-2 - 如何让 selectManyCheckBox 返回 List<String> 以外的其他内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7294284/

    相关文章:

    java - JSF 2.1 重定向到 portlet

    css - 如何停止 richfaces 风格?

    java - JSF 2.0。无法在 preRenderView 事件处理程序中获取 POST 参数和 cookie

    jsf - 托管 Bean 作为 Facelet 参数让复合组件阻止解析

    jquery - 如何从 bean 跳转到 Primefaces 数据表到最后一页?

    javascript - 单击 commandButton 时更新 div

    中继器的 JSF2 寻呼/寻呼机

    javascript - 如何使用 javascript/JQuery 调用 jsf 页面上的隐藏按钮

    jsf - CompositeComponent 出现 javax.el.PropertyNotFoundException?

    java - 如何ajax jsf 2输出链接