tags:

views:

182

answers:

1

When a particular method in my managed bean gets called, I want to know whether I'm in the Restore View phase of the JSF Lifecycle. How can I do this?

+4  A: 

If you're already on JSF 2.0, then you can check it using FacesContext#getCurrentPhaseId():

if (FacesContext.getCurrentInstance().getCurrentPhaseId() == PhaseId.RESTORE_VIEW) {
    // Restore view called.
}

But if you're still on JSF 1.x yet, then your best resort is using a PhaseListener which listens on PhaseId.RESTORE_VIEW, sets a flag/toggle/token in the request scope during beforePhase() and removes the it during afterPhase(). Let the bean's getter method check its presence in the request scope then.

That said, what exactly do you need it for? I've never had the need for such a functional requirement. Isn't the bean's constructor or an @PostConstruct annotated method probably a better place to do initialization stuff like this?

BalusC
Im only on JSF 1.x. The reason I'm wanting to do something like this is that during the Restore View Phase, a method is called on my managed bean that I do not need to have called and it is particularly expensive. So I want to put in logic that says "If in restore view, don't do anything".
BestPractices
Have you considered the other way round? Checking if you're in `RENDER_RESPONSE`. This way you can just use `if (FacesContext.getCurrentInstance().getRenderResponse()) {}` instead which is already available since JSF 1.0. But if the bean itself is request scoped, then I'd just put it in the constructor of the bean. Unless the bean has too much responsibilities, but that's another problem ;)
BalusC
OK-- I thought of checking getRenderResponse but wasnt sure whether that would conclusively tell you whether you were in the RestoreView phase. I'll try it out...
BestPractices
It only returns `true` if you're in `RENDER_RESPONSE`. This phase is *always* executed once as last phase during a request, like as that `RESTORE_VIEW` is *always* executed once as first phase during a request.
BalusC