编辑对象列表未在jsf中提交

时间:2014-03-30 20:17:56

标签: jsf

托管Bean

@SuppressWarnings("serial")
@ManagedBean(name = "samplemanage")
@RequestScoped
public class SampleManage implements Serializable
{

    private List<Sample>        samplelist;

    /**
     * @return the samplelist
     */
    public List<Sample> getSamplelist()
    {
        return samplelist;
    }

    /**
     * @param samplelist the samplelist to set
     */
    public void setSamplelist(List<Sample> samplelist)
    {
        this.samplelist = samplelist;
    }

    public void docklist(ComponentSystemEvent event)
    {   
        List<Sample> samplelist = new ArrayList<Sample>();
        for(int i = 0 ; i < 10 ; i++)
        {
            Sample sa = new Sample();
            sa.setName("sample"+i);
            samplelist.add(sa);
        }
        this.samplelist = samplelist;

        for(Sample sa1 : this.samplelist)
        System.out.println("inserted name is "+sa1.getName());
    }

    public void checkaction()
    {
        for(Sample sa : samplelist)
        System.out.println("output name is "+sa.getName());
    }

}

样本类

public class Sample
{
    private String name;

    //getter and setter
}

XHTML

<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui">
<h:head>
    <f:event listener="#{samplemanage.docklist}" type="preRenderView" />
</h:head>
<h:body>
    <h:form>
        <center>
            <p:dataTable id="sample" var = "sample" value="#{samplemanage.samplelist}">

            <p:column  headerText="Name">
                <h:inputText value="#{sample.name}"></h:inputText>
            </p:column>

            </p:dataTable>
            <p:commandButton id="submit" value="Submit" type="submit" action="#{samplemanage.checkaction}">
            </p:commandButton>
        </center>
    </h:form>
</h:body>
</html>

输出

Mar 31, 2014 1:17:13 AM com.sun.faces.lifecycle.InvokeApplicationPhase execute
WARNING: #{samplemanage.checkaction}: java.lang.NullPointerException
javax.faces.FacesException: #{samplemanage.checkaction}: java.lang.NullPointerException

2014年3月31日上午1:17:13 com.sun.faces.lifecycle.InvokeApplicationPhase执行 警告:#{samplemanage.checkaction}:java.lang.NullPointerException javax.faces.FacesException:#{samplemanage.checkaction}:java.lang.NullPointerException

我需要从表单中获取已编辑的值并打印出来, 我认为这是好方法, 但我不知道为什么它返回空指针异常。 我在这里做错了什么

1 个答案:

答案 0 :(得分:0)

您的bean是@RequestScoped,因此对于每个HTTP请求,都会创建一个新的。

创建页面时,preRenderView事件调用docklist实例化sampleList属性并显示页面。

当您提交表单时,框架会创建一个新的bean,其中sampleList未分配对象,因此您将获得NPE。

制作bean @ViewScoped