如何获取selectManyCheckBox返回除List< String>以外的内容? [英] How do I get selectManyCheckBox to return something other than List<String>?
问题描述
这是一种模式,如果我可以使用的话,我会一遍又一遍地使用它.我有一个枚举名称Log.LogKey,我想让用户从中选取实例.因此,facelet具有以下功能:
This is a pattern that I would use over and over again if I get it to work. I have an enum name Log.LogKey that I want to user to pick out instances of. So the facelet has this:
<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()的吸气剂. selectItems 属性可正确调用该字符串,因为这是呈现给用户的字符串.支持豆具有以下功能:
The enum has a getter called getDisplay(). The selectItems attribute calls that correctly because that's the string that gets rendered to the user. And the backing bean has this:
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; }
}
因此,在提交表单时,将使用字符串列表而不是Log.LogKey列表来调用数组 setSelectedKeys(选定).在 selectItems 标记中对#{lk} 的引用将对象转换为字符串.正确的方法是什么?
So on the form submit, the array setSelectedKeys(selected) gets called with a List of Strings, not a List of Log.LogKey. The reference to #{lk} in the selectItems tag is converting the object to a string. What would be the right way to do this?
推荐答案
您需要指定一个转换器. JSF EL不了解泛型List
类型,因为在运行时该类型会丢失.当您未明确指定转换器时,JSF不会转换提交的String
值,并用它们简单地填充列表.
You need to specify a converter. JSF EL is not aware about the generic List
type because that's lost during runtime. When you do not explicitly specify a converter, JSF will not convert the submitted String
values and plain fill the list with them.
In your particular case, you can make use of the JSF builtin EnumConverter
, you just have to super()
the enum type in the constructor:
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);
}
}
要使用它,只需声明如下:
To use it, just declare it as follows:
<h:selectManyCheckbox value="#{test.selectedKeys}" converter="logKeyConverter">
...
</h:selectManyCheckbox>
另请参见:
- 在h:selectManyCheckbox中使用枚举
- Use enum in h:selectManyCheckbox
See also:
这篇关于如何获取selectManyCheckBox返回除List< String>以外的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!