Jon
----- Original Message ----- From: "Korhonen, Kalle" <[EMAIL PROTECTED]>
To: "MyFaces Discussion" <[email protected]>
Sent: Friday, March 11, 2005 5:06 PM
Subject: RE: How to execute bean method before JSF page is loaded?
-----Original Message----- From: Jonathan Eric Miller [mailto:[EMAIL PROTECTED] Subject: How to execute bean method before JSF page is loaded? Does anyone know if there is a recommended way to have a bean method executed before a JSF page is loaded? For example, I have a page with a h:dataTable in it. What I want to do is make it so that when a user brings up the page directly (by entering the URL in the browser text box rather than as the result of submitting a form), a bean method is executed which does a query to a database. I want the bean to be populated before the page is rendered. Currently, I'm doing this using
Don't know about the recommended way, but here's a few approaches: If your bean is request scoped, you can either initialize it in the constructor (which is in many cases a bad idea because the bean doesn't have the managed properties set yet) or have a special property as the last managed property and do the initialization in its setter. If your bean is not request scoped, you can have another request scoped bean that is referred on your page to initialize the other bean. You could also use Spring to initialize the beans and forward to the result page. There's also a x:bean (or something) that you could use on the page, but I don't like that approach because it moves some of your business logic to the UI layer. Lastly, you can use filters.
a servlet filter. However, one problem with this is that Faces isn't initialized at this point. This isn't a big issue, but, one issue that I ran into is that I was using a managed bean and that bean might not have been created by Faces when the filter executes. So, I put some code in to test if the bean is null or not and it creates it if necessary. I'm wondering if there is a more recommended way to do this within the context of Faces itself. i.e. maybe
You can initialize the Faces Context in a filter yourself if you like, check for example http://www.thoughtsabout.net/blog/archives/000033.html.
using a listener or something? Note, I only want the code to execute for a specific page. It seems like there should be some kind of onInit() method that could be overriden to perform initialization before a page is renderered... I don't know much about ASP.NET, but, I think it allows you to do something like this. I guess I could use a scriptlet in the JSP to do it.
There's a phase listener that you could for this, and it would fire on any page, but you could program the logic yourself to do something real only on certain views.
Kalle

