How to redirect from a ManagedBean for when the request sent is an Ajax request?

42,016

Solution 1

Yes, just send a redirect instead of a (default) forward as outcome. The <navigation-case>-less JSF 2.0 way would be appending ?faces-redirect=true to the outcome string in the action method.

E.g.

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

Solution 2

Here is another technique you might find useful. This is when you invoke method via AJAX from a Primefaces attribute that does not implement navigation. For example, I have a p:tree object with a method selected by the nodeSelectionListener.

In that method, you can invoke redirection like this:

String url = (something)
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
try {
        ec.redirect(url);
} catch (IOException ex) {
        Logger.getLogger(Navigation.class.getName()).log(Level.SEVERE, null, ex);
}

Hope you find this useful.

Share:
42,016
Bhesh Gurung
Author by

Bhesh Gurung

A full-stack web applications developer.

Updated on April 10, 2020

Comments

  • Bhesh Gurung
    Bhesh Gurung about 4 years

    I am using PrimeFaces with JSF2. I am trying to authenticate user by sending login and password as an Ajax request. And in the action method of the backing bean, I am trying to validate user and redirect to a new view if the validation succeeds.

    Is this possible while using primefaces?

    Because I think with primefaces' p:commandButton, I can only either have ajax behavior or the navigation.

  • Bhesh Gurung
    Bhesh Gurung about 13 years
    Hey! I tried it and it works perfectly and it solved my problem. Thank you.
  • BalusC
    BalusC about 13 years
    This does effectively the same, but on an old fashioned JSF 1.x way.
  • Akvel
    Akvel over 11 years
    Works fine with JSF2.0 primeFace autoComplite. Thanks!
  • Hidalgo
    Hidalgo about 11 years
    Very useful code, I used it for redirection after successful login in Spring Security (form-login)