2015-04-28 111 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 –