JSF 2.0:为什么我的ViewScope Bean重新创建,即使它仍然在同一个View上

时间:2011-11-06 09:12:01

标签: java exception jsf-2 scope

在我的.xhtml页面中,我有以下表格:

<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets"
            template="./../template/CustomerTemplate.xhtml"
            xmlns:h="http://java.sun.com/jsf/html"
            xmlns:f="http://java.sun.com/jsf/core"
            xmlns:p="http://primefaces.prime.com.tr/ui">

    <ui:define name="formContent">
        <h:form> 
            <p:dataGrid var="item" value="#{mrBean.items}" columns="3">
                <p:column>
                    <p:panel header="#{item.name}">
                        <h:panelGrid columns="1" style="width:100%">
                            ...
                            <h:commandButton value="Add To Cart" actionListener="#{cartBean.addItem(item.id)}" />
                            ...
                        </h:panelGrid>
                    </p:panel>
                </p:column>
            </p:dataGrid> 
        </h:form> 
    </ui:define>

</ui:composition>

CustomerTemplate.xhtml是:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:p="http://primefaces.prime.com.tr/ui">
    <h:head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        ... // import css, js files
    </h:head>

    <h:body>
        ... // Other things on the page
        <div class="grid_9 content">
            <ui:insert name="contentTitle"></ui:insert>
            <ui:insert name="formContent"></ui:insert>
        </div>
        ...
    </h:body>
</html>

这是我的ManagedBean:

@ManagedBean
@ViewScoped
public class MrBean {
    ...
    private List<ItemState> items;
    ...

    @PostConstruct
    public void prepareItemList() {
        ...
        Map<String,String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
            partnerID = Long.parseLong(params.get("partnerID"));
        ...
    }
}

如您所见,我的MrBean是一个ViewScoped ManagedBean。我预计@PostContruct函数只会在第一次呈现页面时调用一次。但是,当我单击Add To Cart按钮时,我遇到Long.parseLong(params.get("partnerID"))行的空异常,即使我仍然在同一个视图上。

如果有人能就如何解决这个问题给我建议,我将非常感激。

更新:我设法通过将commandButton包含在ajax标记中来实现此功能,如下所示:

...
<f:ajax listener="#{cartManagedBean.addItem(item.id)}">
    <h:commandButton value="Add To Cart" /> 
</f:ajax>
....

1 个答案:

答案 0 :(得分:7)

这有很多可能的原因,最终归结为JSF issue 1492中描述的鸡蛋问题。您正在使用<h:someHtmlComponent binding="...">将UI组件绑定到视图范围的托管bean属性,或者将标记处理程序的属性(如<c:if test="..."><ui:include src="...">等)绑定到视图作用域托管豆类财产。

计划在JSF 2.2中修复。在此之前,您最好的选择是寻找替代方法或将上下文参数javax.faces.PARTIAL_STATE_SAVING设置为false

另见: