2015-04-28 114 views
1

我已经做了一个小的jsf应用程序,并且对生命周期顺序有点困惑,即使我在每个请求上创建了该对象,我仍然在回发中获得意外的NPE。有人可以解释封面下发生了什么。下面是代码:JSF生命周期阶段

Entity.java

public class Entity { 

    private Long id; 
    private String property; 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 

    public String getProperty() { 
     return property; 
    } 

    public void setProperty(String property) { 
     this.property = property; 
    } 
} 

Bean.java

import javax.enterprise.inject.Model; 

@Model 
public class Bean { 

    private Long id; 
    private Entity entity; 

    public Long getId() { 
     return id; 
    } 

    public void setId(Long id) { 
     this.id = id; 
    } 

    public Entity getEntity() { 
     return entity; 
    } 

    public void loadEntity() { 
     this.entity = new Entity(); 
    } 
} 

edit.xhtml

<!DOCTYPE html> 
<html xmlns="http://www.w3.org/1999/xhtml" 
     xmlns:h="http://xmlns.jcp.org/jsf/html" 
     xmlns:f="http://xmlns.jcp.org/jsf/core" 
     xmlns:o="http://omnifaces.org/ui"> 
    <f:view transient="true"> 
     <f:metadata> 
      <f:viewParam name="id" value="#{bean.id}"/> 
      <f:viewAction onPostback="true" action="#{bean.loadEntity()}"/> 
     </f:metadata> 
     <h:body> 
      <o:form useRequestURI="true"> 
       <h:inputText value="#{bean.entity.property}"/> 
       <h:commandButton value="Save"/> 
      </o:form> 
     </h:body> 
    </f:view> 
</html> 
+0

有关信息,我正朝着完整的无状态架构。 –

回答

2

操作方法,如<f:viewAction action>期间调用应用程序阶段被调用。模型值在更新模型值阶段更新。因此,当需要设置属性时,该实体被创建为一个阶段,并且仍然是null

摆脱<f:viewAction>并改为使其成为@PostConstruct方法。

@PostConstruct 
public void init() { 
    this.entity = new Entity(); 
} 
+0

这只是一个虚拟语句,实际上我必须从某处加载它,并且我需要id才能出现。 –

+0

然后通过['@Param'](http://showcase.omnifaces.org/cdi/Param)抓取它而不是''。 – BalusC

+0

然后我将无法通过includeViewParams –