Support for the JSF Bean constructor called multiple times

I am trying to use JSF 2.0 (after using ICEfaces 1.8 in the last few months), and I am trying to understand why my bean constructor is called several times in JSF 2.0.

It is assumed that the bean will be created once upon creation, but the text "Bean Initialized" appears whenever I press the commandButton button, pointing to the new bean that will be instantiated.

Front 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> 

Bean support:

 @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"); } } 

It's all. Just a simple test. The same behavior occurs if I use ICEfaces 2.0 and instead of the Panel used:

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

I would appreciate any help here. I can not explain it.

Refresh . In response to Aba Dov, I am an @SessionScoped bean, believing that it will not call the constructor on every request and did not encounter the same behavior. What am I missing?

+4
source share
3 answers

You declared a bean to be placed in the request area and each time you start a new HTTP request using the command button. Truly a bean will be created for every request.

If you want the bean to live as long as the view itself (for example, IceFaces makes ajax under the covers for all this stuff), you need to declare a bean viewport (this is new in JSF 2.0).

 @ManagedBean @ViewScoped public class Bean implements Serializable {} 
+6
source

The bean must be in ViewScoped.

+1
source

The bean is called every time a request appears on the page.

when you press <h:commandButton> , the form is submitted and the request is sent to the server

to prevent it, you can use the <t:saveState> or <a4j:keepAlive> for your own.

for example <a4j:keepAlive beanName="YourBean" />

these tags store the bean instance in the component tree.

also make sure your implements Serializable class is implements Serializable . therefore it can be serialized

Hope this helps

0
source

Source: https://habr.com/ru/post/1337444/


All Articles