java 如何将selectManyListbox中选择的数据存储到JSF中的列表中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2235817/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:13:04  来源:igfitidea点击:

How to store the data's selected in a selectManyListbox into a List in JSF?

javajsf

提问by Hariharbalaji

I am having a selectmanyListbox component in my JSF, now i want to store the selected data's into a List. How to do this?

我的 JSF 中有一个 selectmanyListbox 组件,现在我想将选定的数据存储到一个列表中。这个怎么做?

回答by BalusC

As with every UIInputcomponent, you just have to bind the valueattribute with a property of the backing bean. Thus, so:

与每个UIInput组件一样,您只需要将value属性与支持 bean的属性绑定。因此,所以:

<h:form>
    <h:selectManyListbox value="#{bean.selectedItems}">
        <f:selectItems value="#{bean.selectItems}" />
    </h:selectManyListbox>
    <h:commandButton value="submit" action="#{bean.submit}" />
</h:form>

with the following in Beanclass:

Bean课堂上有以下内容:

private List<String> selectedItems; // + getter + setter
private List<SelectItem> selectItems; // + getter only

public Bean() {
    // Fill select items during Bean initialization/construction.
    selectItems = new ArrayList<SelectItem>();
    selectItems.add(new SelectItem("value1", "label1"));
    selectItems.add(new SelectItem("value2", "label2"));
    selectItems.add(new SelectItem("value3", "label3"));
}

public void submit() {
    // JSF has already put selected items in `selectedItems`.
    for (String selectedItem : selectedItems) {
        System.out.println("Selected item: " + selectedItem); // Prints value1, value2 and/or value3, depending on selection.
    }
}

If you want to use non-standard objects as SelectItemvalue (i.e. not a String, Numberor Booleanfor which EL has already builtin coercions), then you'll have to create a Converterfor this. More details can be found in this blog article.

如果您想使用非标准对象作为SelectItem值(即不是 a StringNumber或者BooleanEL 已经内置强制转换),那么您必须为此创建 a Converter。可以在此博客文章中找到更多详细信息。

回答by Bozho

<h:selectManyListBox value="#{managedBean.list}">

<h:selectManyListBox value="#{managedBean.list}">

and in the managed bean:

并在托管 bean 中:

private List list;

(with the appropriate getter and setter, and if possible - using generics)

(使用适当的 getter 和 setter,如果可能 - 使用泛型)