webtier@glassfish.java.net

Where to put one-time executed code on JSF page load

From: <webtier_at_javadesktop.org>
Date: Mon, 01 Mar 2010 12:48:31 PST

I've been reacquainting myself with the delights of JSF by writing a fairly basic user registration system (yeah, haven't we all?) when I came across a problem that I ended up solving but I think I must be missing something - hence this thread.

I have written a JSF request-scoped bean and XHTML page that is called when a user clicks on a link sent to them in an email to complete the registration process. The bean simply confirms that the user id and key match what's listed in the database and, if valid, puts out a confirmation message with a link to the login panel.

I embedded the logic processing the registration validation in a method tagged with @PostConstruct since I want to process the information before the user sees the page. The link pointing to the login page was an h:commandLink (I think you can already see where this is going) but when I clicked on it, nothing happened. I just could not get the darned thing to work at all, even though the linked page name was obviously correct.

Of course, I eventually realized that the request-scoped bean was going through the whole JSF lifecycle again, including the @PostConstruct logic that validated the registration all over again, which messed it all up. Now that I understood what was happening, it seemed pretty logical to me, but then I began to wonder -- where should I put the logic that should only be executed once on loading the page and not on any callbacks -- as in the example of validating registration from an email-originated link?

I solved the immediate problem by replacing the h:commandLink with an h:outputLink (though I don't like the inconsistency of needing the .xhtml on the outputLink when you don't need it on the commandLink), but I am still wondering, if you want a JSF bean to do something only once when it is first loaded, how should you structure the code?
[Message sent by forum member 'tacitust' (tacitus_at_yahoo.com)]

http://forums.java.net/jive/thread.jspa?messageID=389489