Search code examples
javajsfjsf-2xhtmlphaselistener

Phase Listener and Command Button


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?


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