Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 542
Bhesh Gurung Avatar asked May 17 '11 00:05

Bhesh Gurung


2 Answers

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";
}
like image 62
BalusC Avatar answered Oct 17 '22 07:10

BalusC


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.

like image 45
AlanObject Avatar answered Oct 17 '22 07:10

AlanObject