我正在尝试JSF示波器,并且在请求范围内使用会话范围时会遇到一些问题。
基本工作流程是用户将单击主页上的项目上的视图按钮,然后将我的代码称为加载&显示该项目的信息。
这是我的更新代码:
@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请求范围(或视图范围(,则在查看页面上获得空数据。如果视图Bean是会话范围的,则事情可以正常工作。我不明白为什么?
从我在调试器中看到的内容,ReadItem(itemID(被调用(单击视图按钮时的主页(,但是当查看页面本身调用getItemViewObject((时,itemViewObject为null。
。我在做什么错?
更新我忘了早些时候提到我的主页是如何调用readitem方法的,那是通过命令按钮:
<h:commandButton class="btn btn-mini firefoxBtnMiniCorrection"
value="View"
action="#{itemViewBean.readItem(b.itemId)}"/>
主页中列出的每个项目都有其自己的查看按钮。
还忘了提到主页和我的查看页面都使用JSF模板。我不知道这是否重要。
根据人们所做的评论,我想到了上面的代码更改。现在事情起作用了。使用请求范围或使用ItemViewBean的查看范围立即起作用。
我很惊讶这有效!我不太确定我完全了解它为什么有效。
我的变化是正确的方法吗?还是有更好的方法?
另外,我正在使用JSF 2.1。
更新2 它行不通。范围有效,但我发现ViewParam中的itemID总是无效的。为什么?
itemViewObject
在 RequestScoped
bean中是私有的。在readItem()
获得itemViewObject的值之后,此请求之后将忘记此值,并在下一个请求中为null(`@requestscoped'(。