Question

The methods

public void beforePhase(PhaseEvent event)
public void afterPhase(PhaseEvent event)

are being called AFTER the method associated with the

<p:commandButton value="Login" action="#{checkUser.login}" ajax="false" />

As I am trying to implement a Log Off functionality, right now, the button must be pressed twice in order to leave the page.

Is there any way to make the "command button" method being called BEFORE the "phase listener's" methods mentioned above?

Was it helpful?

Solution

You need to send a redirect after login and logout in order to let the client fire a new HTTP request.

E.g.

public String login() {
    // ...
    return "home?faces-redirect=true";
}

public String logout() {
    // ...
    return "login?faces-redirect=true";
}

By the way, a PhaseListener is not the right tool to perform request based authentication. You should prefer a servlet Filter for the job. The PhaseListener has the major disadvantage that it runs only on JSF requests and that it's invoked up to 12 times on a per-request basis. For a kickoff example of such a filter, see also How to provide bean methods without EL expression

OTHER TIPS

Edit: I should point out that BalusC's answer should probably be the preferred way to solve this problem. But if you still want to play with phase order, keep reading. /end-edit

Actually the phaseListeners may be invoked both before and after your method specified in action-attribute, if you implement it to Listen to every phase.

public class MyPhaseListener implements PhaseListener {
    public PhaseId getPhaseId() { return PhaseId.ANY_PHASE; }

    public void beforePhase(PhaseEvent event) {
        System.out.println("Before Phase: " + event.getPhaseId());
    }
    public void afterPhase(PhaseEvent event)  {
        System.out.println("After Phase: " + event.getPhaseId());
    }
}

activate your Listener in faces-config.xml

<faces-config ... >
    <lifecycle>
        <phase-listener>MyPhaseListener</phase-listener>
    </lifecycle>
</faces-config>

Here is the printout of all Listener invokations and when actionListener and action is invoked:

INFO: Before Phase: RESTORE_VIEW 1
INFO: After Phase: RESTORE_VIEW 1
INFO: Before Phase: APPLY_REQUEST_VALUES 2
INFO: After Phase: APPLY_REQUEST_VALUES 2
INFO: Before Phase: PROCESS_VALIDATIONS 3
INFO: After Phase: PROCESS_VALIDATIONS 3
INFO: Before Phase: UPDATE_MODEL_VALUES 4
INFO: After Phase: UPDATE_MODEL_VALUES 4
INFO: Before Phase: INVOKE_APPLICATION 5
INFO: ActionListener Done
INFO: Action Done
INFO: After Phase: INVOKE_APPLICATION 5
INFO: Before Phase: RENDER_RESPONSE 6
INFO: After Phase: RENDER_RESPONSE 6
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top