JSF:将字符串添加到列表 [英] JSF: Adding a String to List

查看:138
本文介绍了JSF:将字符串添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSF 2.0应用程序,该应用程序具有一个保存字符串列表的bean.

I have an JSF 2.0 application that has a bean that holds a list of Strings.

我想将<h:inputText>/>中的字符串添加到我的列表中并显示我的列表.

I want to add the String from an <h:inputText>/> to my List and display my list.

以下代码只是将引用放入我的列表中.因此,列表中的每个元素都设置为最后一个输入.

The following code just put references in my List. So every element from my List is set to the last input.

@ManagedBean
@ApplicationScoped
public class Bean {

private String name;
private ArrayList<String> test = new ArrayList<String>();

public Bean() {
}

public Bean(String name) {
    this.name = name;
}


public String addtoList(String _name){
    test.add(_name);
    return "./index.xhtml";
} 


/***************GETTER/SETTER/HASHCODE/EQUALS**************************/
   ...

}

这是我的index.xhtml的一部分:

here a part of my index.xhtml:

        <h:inputText id="name"
                         value="#{bean.name}"
                         required="true">
        </h:inputText>
        <h:commandButton value="Post"  
                         action="#{bean.addtoList(name)}"/>  
        <br/>
        <h:dataTable var="bean"
                     value="#{bean.test}">
            <h:column>
                <h:outputText value="#{bean.name}"/>
            </h:column>

        </h:dataTable>

推荐答案

尝试一下:

public String addtoList() { // no parameter
    test.add(this.name); // add value of bean's property
    return "./index.xhtml";
}

和在方面:

<h:commandButton
    value="Post"
    action="#{bean.addtoList}"/> <!-- no parameter passed -->

关键是要使用不带参数的addToList方法,并且添加到列表中的字符串应该是后备bean的name属性的值.

The point is to have the addToList method without parameters and the string you add to the list should be the value of the name property of the backing bean.

而且,在数据表中,不要将var命名为与支持bean相同的名称.这令人困惑,并可能导致错误.使用类似这样的内容:

And also, in the datatable, do not name the var the same as the backing bean. It's confusing and potentially leads to bugs. Use something like this:

<h:dataTable
    var="it"
    value="#{bean.test}">
    <h:column>
        <h:outputText value="#{it}" />
    </h:column>
</h:dataTable>

这篇关于JSF:将字符串添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆