How to redirect from a ManagedBean for when the request sent is an Ajax request?
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.
Comments
-
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 about 13 yearsHey! I tried it and it works perfectly and it solved my problem. Thank you.
-
BalusC about 13 yearsThis does effectively the same, but on an old fashioned JSF 1.x way.
-
Akvel over 11 yearsWorks fine with JSF2.0 primeFace autoComplite. Thanks!
-
Hidalgo about 11 yearsVery useful code, I used it for redirection after successful login in Spring Security (form-login)