2011-10-18 35 views
0

情況如下,我有一個頁面添加/更新用戶 prerender方法根據參數要麼創建一個新的對象或獲取現有PropertyNotFoundException:目標不可達,'userObj'返回null與jsf按鈕和請求範圍

@Component("user") 
@Scope("request") 
public class UserBean { 


    private User userObj; 
    private boolean editUser; 


    public String addUser() throws Exception { 

     if (editUser) { 
      userService.updateUser(userObj); 
     } else { 
      userService.addUser(userObj); 
     } 
     return "users?faces-redirect=true"; 
    } 

    public void preRender(ComponentSystemEvent event) throws Exception { 

      System.out.println("############ PRERENDER #############"); 
      if (editUser) { 
       userObj = userService.getUser(userID); 
       pageTitle = "Updating " + userObj.getName(); 
       buttonTitle = "Save Changes"; 
      } else { 
       userObj = new User(); 
       pageTitle = "Adding new user"; 
       buttonTitle = "Add User"; 

      } 

     } 

,並在JSF頁面我稱之爲預渲染爲:

<f:event id="event1" listener="#{user.preRender}" type="javax.faces.event.PreRenderComponentEvent" /> 

但是當我點擊添加按鈕主要內容如下:

<h:commandButton value="#{user.buttonTitle}" action="#{user.addUser}" style="width: 105px; "/> 

我收到以上異常,請指教。

+0

顯示完整的堆棧跟蹤 – Bozho

+0

我猜你的'commandButton'正在向服務器創建一個新的請求,導致UserBean創建一個新的實例。因此'userObj'爲空。 – flash

+0

@flash解決它的任何想法? –

回答

1

問題是您的h:commandButton正在向服務器創建一個新請求,導致UserBean在範圍Request中創建自己的新實例。

我可以想到幾種解決方案。

1) 看來你知道你的頁面是否處於編輯模式。然後你可以擺脫你的preRender method,而是調用userObj的獲取者時,從數據庫中獲得userObj。然後,如果您的頁面處於編輯模式,則可以傳遞給您的add method。因此,你必須修改commandButton:(注意:您必須將值更改爲當前的編輯模式)

<h:commandButton value="#{user.buttonTitle}" action="#{user.addUser}" style="width: 105px; "> 
     <f:setPropertyActionListener value="true" target="#{user.editUser}" /> 
    </h:commandButton> 

和你userBean到:

@Component("user") 
@Scope("request") 
public class UserBean { 

private User userObj; 
private boolean editUser; 

public String addUser() throws Exception { 
    userObj = getUserObj(); 
    if (editUser) { 
     userService.updateUser(userObj); 
    } else { 
     userService.addUser(userObj); 
    } 
    return "users?faces-redirect=true"; 
} 

public void setEditUser(boolean editUser) { 
    this.editUser = editUser; 
} 

public User getUserObj() { 
    if (editUser) { 
     if(userObj == null) { 
      userObj = userService.getUser(userID); 
     } 
     return userObj; 
    } 
    else { 
     return userObj = new User(); 
    } 
} 

public void setUserObj(User userObj) { 
    this.userObj = userObj; 
} 

這應該給你怎麼一個基本思路有用。訣竅是使用f:setPropertyActionListener

2)您可以使用視圖範圍來解決這個問題。問題是春天不提供這個開箱即用。好消息是你可以自己構建視圖範圍。那看一下blog post

+0

好,第二個解決方案工作的很好,但我注意到終端上的以下警告:'警告:將不可序列化的屬性值設置爲ViewMap:(key:user,value class:com.myapp.beans.UserBean)'so any想法?順便說一句,你有任何好的樣品/資源像上面使用JSF 2彈簧3 –

+0

有幾個教程[這裏](http://tutorials.slackspace.de/) – flash

+0

非常感謝,關於警告的任何想法我得到? –

相關問題