[英]JSF Request Scoped Bean not displaying data in page
我正在嘗試JSF范圍,並且在請求范圍的bean中使用會話范圍的bean時遇到一些問題。
基本的工作流程是用戶單擊主頁上某個項目上的“查看”按鈕,然后調用我的代碼以加載和顯示該項目的信息。
這是我的更新代碼:
@ManagedBean(name="itemViewBean")
@RequestScoped
class ItemViewBean {
@ManagedProperty("#{itemBean}")
private ItemBean itemBean;
private ItemViewObject itemViewObject;
private int itemId;
public void init() {
itemViewObject = itemBean.readItem(itemId);
}
public String readItem(int itemId) {
// itemViewObject = itemBean.readItem(itemId); // moved to init();
return "/pages/viewItem.xhtml?faces-redirect=true";
}
public ItemViewObject getItemViewObject() {
return itemViewObject;
}
// getters & setters as needed
}
@ManagedBean(name="itemBean")
@SessionScoped
class ItemBean {
public ItemViewObject readItem(int itemId) {
// hardcoded creating a ItemViewObject for now.
// eventually would be loaded from the database.
....
}
}
然后,我的“ 更新的視圖”頁面具有以下內容:
<!-- added the metadata -->
<f:metadata>
<f:viewParam name="id" value="#{itemViewBean.itemId}" />
<f:event listener="#{itemViewBean.init}" type="preRenderView" />
</f:metadata>
<!-- same as before -->
<h:outputText value="#{itemViewBean.itemViewObject.description}" />
如果我的viewBean是請求范圍(或視圖范圍)的,則在視圖頁面上會得到空數據。 如果viewBean是會話作用域的,則一切正常。 我不明白為什么?
根據我在調試器中看到的內容,將調用readItem(itemId)(單擊視圖按鈕時從主頁上),但是當視圖頁面本身調用getItemViewObject()時,itemViewObject為null。
我究竟做錯了什么?
UPDATE我忘了前面提到我的主頁如何調用readItem方法,而那是通過命令按鈕進行的:
<h:commandButton class="btn btn-mini firefoxBtnMiniCorrection"
value="View"
action="#{itemViewBean.readItem(b.itemId)}"/>
主頁中列出的每個項目都有其自己的“查看”按鈕。
還忘了提及主頁和我的視圖頁面都在使用JSF模板。 我不知道這是否重要。
從下面人們的評論中,我想到了上面的代碼更改。 現在一切正常。 現在可以將請求范圍或視圖范圍與ItemViewBean一起使用。
我很驚訝這行得通! 我不太確定我是否完全理解它的工作原理。
我的更改是做事的正確方法嗎? 或者,還有更好的方法?
另外,我正在使用JSF 2.1。
更新2它不起作用。 范圍確定有效,但是我發現viewParam中的itemId始終為null。 為什么?
itemViewObject
在RequestScoped
bean中是私有的。 在readItem()
獲得readItem()
的值之后,該值將在此請求后被忘記,並且在下一個請求(@RequestScoped)時為null。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.