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

2

16

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.

Teratogenic answered 17/5, 2011 at 0:4 Comment(0)
S
30

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";
}
Skip answered 17/5, 2011 at 4:55 Comment(1)
Hey! I tried it and it works perfectly and it solved my problem. Thank you.Teratogenic
B
16

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.

Bolte answered 18/5, 2011 at 18:47 Comment(3)
This does effectively the same, but on an old fashioned JSF 1.x way.Skip
Works fine with JSF2.0 primeFace autoComplite. Thanks!Kunming
Very useful code, I used it for redirection after successful login in Spring Security (form-login)Solita

© 2022 - 2024 — McMap. All rights reserved.