【问题标题】:How to save a list/map/set in JSF with h:inputText + managed bean如何使用 h:inputText + 托管 bean 在 JSF 中保存列表/地图/集合
【发布时间】:2011-08-31 04:39:16
【问题描述】:

我想要达到的效果与以下链接中发布的内容非常相似。

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

我对上面链接中 Arjan Tijms 提供的答案特别着迷,但是我想要实现的目标略有不同。考虑以下代码 sn-ps。

豆子

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 个 h:inputText,当单击保存按钮时,每个 h:inputText 中的所有选项都会添加到选项列表中。我搜索了高低,但似乎找不到任何关于如何做到这一点的提示。

如果 JSF 2 真的不支持这一点,我想我将不得不使用丑陋的方式,只有一个 h:inputText 并使用转换器来转换列表,但我仍然希望这是一个理想的可以找到解决办法。

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

【问题讨论】:

    标签: jsf-2


    【解决方案1】:

    只需添加一个“添加”按钮,即可将新的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 放入视图范围时才有效。将在每个请求上构建一个请求范围的请求,并因此每次都重新创建列表。

    【讨论】:

    • 非常感谢 BalusC。像魅力一样工作。
    • 嗨 BalusC:你会回答这个场景的工作吗? stackoverflow.com/questions/19395621 能否请您详细解释一下varStatus 的工作原理。
    猜你喜欢
    • 2011-07-12
    • 2015-08-29
    • 2014-07-01
    • 1970-01-01
    • 2011-03-29
    • 2013-07-26
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    相关资源
    最近更新 更多