多次调用JSF Backing Bean构造函数

多次调用JSF Backing Bean构造函数

问题描述:

我正在尝试JSF 2.0(在过去几个月中使用ICEfaces 1.8之后),并且试图弄清楚为什么在JSF 2.0中我的后备bean构造函数被多次调用.

I'm trying out JSF 2.0 (after using ICEfaces 1.8 for the past few months) and I'm trying to figure out why in JSF 2.0 my backing bean constructor gets called multiple times.

该bean应该在创建时实例化一次,但是每当我单击commandButton时,都会显示"Bean Initialized"文本,表明正在实例化一个新的Bean对象.

The bean is supposed to be instantiated once upon creation, but the "Bean Initialized" text shows up whenever I click the commandButton, indicating a new Bean object being instansiated.

facelet页面:

The facelet page:

    <?xml version='1.0' encoding='UTF-8' ?>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html">

    <h:body>
        <div id="content">
            <h:form id="form">
                <h:commandButton value="Toggle" action="#{bean.toggleShowMe}"/>
            </h:form>


            <h:panelGrid rendered="#{bean.showMe}">
                <h:outputText value="Show me!"/>
            </h:panelGrid>
        </div>
    </h:body>
</html>

后备豆:

@ManagedBean
@RequestScoped
public class Bean {
    private boolean showMe = false;

    public boolean isShowMe() {
        return showMe;
    }

    public void setShowMe(boolean showMe) {
        this.showMe = showMe;
    }

    public void toggleShowMe(){
        System.out.println(showMe);
        if(showMe==true){
            showMe=false;
        }else{
            showMe=true;
        }
    }
    /** Creates a new instance of Bean */
    public Bean() {
        System.out.println("Bean Initialized");
    }

}

仅此而已.只是一个简单的测试.如果我使用ICEfaces 2.0并代替我使用的panelGrid,也会显示相同的行为:

Thats all it is. Just a simple test. The same behaviour shows itself if I use ICEfaces 2.0 and in place of the panelGrid I use:

<ice:panelPopup visible="#{bean.showMe}">

在这里,我将不胜感激.我不知所措.

I'd appreciate any help here. I'm at a loss to explain it.

更新:作为对Aba Dov的响应,我@SessionScoped bean,确定它不会在每个请求时都调用构造函数,并且会遇到相同的行为.我想念什么?

Update: In response to Aba Dov, I @SessionScoped the bean, figuring it wouldn't be calling the constructor upon each request and ran into the same behavior. What am I missing?

您已声明将bean放置在请求范围内,并且每次都通过命令按钮触发新的HTTP请求.确实,每个请求都会创建该bean.

You have declared the bean to be placed in the request scope and you're firing a new HTTP request everytime by the command button. Truly the bean will be created on every request.

如果您希望bean的生存时间与视图本身一样长(就像IceFaces在所有ajax东西的幕后所做的那样),那么您需要声明bean视图的作用域(这是JSF 2.0中的新功能).

If you want that the bean lives as long as the view itself (like as IceFaces is doing under the covers for all that ajax stuff), then you need to declare the bean view scoped (this is new in JSF 2.0).

@ManagedBean
@ViewScoped
public class Bean implements Serializable {}