我想要实现的内容与以下链接中发布的内容非常相似.
如何使用ui重复+ h:inputText +托管bean在JSF中保存数组?
我对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 "";
}
}
Run Code Online (Sandbox Code Playgroud)
和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>
Run Code Online (Sandbox Code Playgroud)
问题是,如果我们在开头的列表中有一些初始数据,这将有效.初始列表为空的情况怎么样?
我正在寻找的理想解决方案是每个选项都有1小时:inputText,当点击保存按钮时,每个h:inputText中的所有选项都会被添加到选项列表中.我搜索过高低,但似乎无法找到关于如何做到这一点的任何提示.
如果JSF 2真的不支持这个,我想我只需要用一个h:inputText来使用丑陋的方式并使用转换器来转换成列表,但我仍然希望理想的解决方案可以是找到.
希望来自stackoverflow的人可以为我指明正确的方向.
只需添加一个"添加"按钮,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}" />
Run Code Online (Sandbox Code Playgroud)
同
private String newChoice;
public void add() {
choices.add(newChoice);
newChoice = null;
}
// ...
Run Code Online (Sandbox Code Playgroud)
请注意,这仅适用于将bean放入视图范围的情况.将在每个请求上构建一个请求范围的请求,并在此每次重新创建列表.
| 归档时间: |
|
| 查看次数: |
9879 次 |
| 最近记录: |