如何使用h:inputText + managed bean在JSF中保存列表/ map / set

时间:2011-08-31 04:39:16

标签: jsf-2

我想要实现的目标非常类似于以下链接中发布的内容。

How to save an array in JSF with ui:repeat + h:inputText + managed bean?

我对Arjan Tijms在上面的链接中提供的答案特别着迷,但我想要达到的目标略有不同。请考虑以下代码段。

豆子

import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;

@RequestScoped
@Named
public class MyBean {

    List<String> choices;

    public List<String> getChoices() {
        return choices;
    }

    @PostConstruct
    public void initChoices() {
        choices= new ArrayList<String>();
    }

    public String save() {
        // should save all the choices into some repository
        return "";
    }
}

和facelet页面

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"        
    xmlns:ui="http://java.sun.com/jsf/facelets">

    <h:body>

        <h:form>
            <ui:repeat value="#{myBean.choices}" varStatus="status">            
                <h:inputText value="#{myBean.choices[status.index]}" />
            </ui:repeat>
            <h:commandButton value="Save" action="#{myBean.save}" />
        </h:form>
    </h:body>
</html>

问题是,如果我们在开头的列表中有一些初始数据,这将有效。初始列表为空的情况怎么样?

我正在寻找的理想解决方案是每个选项都有1小时:inputText,当点击保存按钮时,每个h:inputText中的所有选项都会添加到选项列表中。我已经搜索过高低,但似乎无法找到关于如何做到这一点的任何提示。

如果JSF 2真的不支持这个,我想我只需要用一个h:inputText来使用丑陋的方式并使用转换器转换为列表和从列表转换但是我仍然希望这是理想的解决方案可以找到。

希望来自stackoverflow的人可以为我指明正确的方向。

1 个答案:

答案 0 :(得分:6)

只需添加一个“添加”按钮,即可将新的String添加到列表中。

<ui:repeat value="#{myBean.choices}" varStatus="status">            
    <h:inputText value="#{myBean.choices[status.index]}" />
</ui:repeat>
<h:inputText value="#{myBean.newChoice}" />
<h:commandButton value="Add" action="#{myBean.add}" />
<h:commandButton value="Save" action="#{myBean.save}" />

private String newChoice;

public void add() {
    choices.add(newChoice);
    newChoice = null;
}

// ...

请注意,这仅适用于将bean放入视图范围的情况。将在每个请求上构建一个请求范围的请求,并在此每次重新创建列表。