This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
I've got very simple code which only test if the managed bean method is called on button click.
Is this kind of a bug that my managed bean method is being called every time the page is loaded?
... and the bean:
I am using Netbeans 7.1.1 with tomcat 7.0.22 and JSF 2.1
First, JSF is based on the concept of "postback". Unlike other frameworks, where a URL loads a page and that's it, JSF presents a View as a page and keeps presenting it until instructed to navigate to some other View. So the same "page" may be loaded multiple times - once for each postback operation.
Secondly, J2EE Request scope is based on page load requests. So each postback generates a new page load request, even though the same View is being presented. Request scope objects are created to support the request and then destroyed at the end of the request, so each update of the View causes an entirely new request bean to be created and destroyed - no state data (property values) carry between requests and it's all rebuilt from the beginning each time. Request scope is actually mostly useless in JSF.
Finally, JSF is based on a well-defined lifecycle where the Controller references the Model to create a View using a Model, accept data input from a View, validate the incoming data, update the Model from the View (IF and ONLY IF every data item passes validation). And in the case of Request-scope - destroy the updated Model.
To do all of the above, the set/get methods of the Model object (backing bean) properties may be called many times, since the Model is the official copy of the data - JSF doesn't keep internal copies. And for that reason, multiple calls to set/get methods are not a bug, but an inherent part of how the JSF lifecycle works. Which means that get/set methods should avoid having side-effects and should definitely avoid doing high-overhead operations.
An IDE is no substitute for an Intelligent Developer.
Joined: Jun 09, 2012
Thank very much for the exhaustive answer, Tim.
It was awkward for me that when my application gets deployed and the view is rendered for the first time I got the bean method, given as a value to the "onclick" attribute, called.
I redeployed a couple of times and this strange behaviour disappeared.