当发送的请求是 Ajax 请求时,如何从 ManagedBean 重定向?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6024815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to redirect from a ManagedBean for when the request sent is an Ajax request?
提问by Bhesh Gurung
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.
我在 JSF2 中使用 PrimeFaces。我试图通过将登录名和密码作为 Ajax 请求发送来验证用户。在支持 bean 的 action 方法中,我尝试验证用户并在验证成功时重定向到新视图。
Is this possible while using primefaces?
使用primefaces时这可能吗?
Because I think with primefaces' p:commandButton, I can only either have ajax behavior or the navigation.
因为我认为使用 primefaces' p:commandButton,我只能有 ajax 行为或导航。
回答by BalusC
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=trueto the outcome string in the action method.
是的,只需发送重定向而不是(默认)转发作为结果。该<navigation-case>稀少JSF 2.0的方式将被追加?faces-redirect=true到action方法的结果字符串。
E.g.
例如
public String login() {
// ...
return "home?faces-redirect=true";
}
回答by AlanObject
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.
这是您可能会发现有用的另一种技术。这是当您通过 AJAX 从未实现导航的 Primefaces 属性调用方法时。例如,我有一个由 nodeSelectionListener 选择的方法的 ap:tree 对象。
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.
希望您觉得这个有帮助。

