我终于在页面之间传递了消息,但这并没有将我重定向到用户登录页面(../../index.xhtml),而是显示了禁止的页面:
public String permission() throws IOException {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, Object> sessionMap = context.getExternalContext().getSessionMap();
String isLog = (String) sessionMap.get("isLogged");
if(isLog != "TRUE") {
System.out.println("*** The user has no permission to visit this page. *** ");
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Info : ", "Loggez-vous"));
context.getExternalContext().getFlash().setKeepMessages(true);
//context.getExternalContext().redirect("../../index.xhtml");
return "../../index.xhtml?faces-redirect=true";
} else {
System.out.println("*** The session is still active. User is logged in. *** ");
}
return "../../index.xhtml?faces-redirect=true";
}
当然,受限页面有这个:
<f:event type="preRenderView" listener="#{userloginMB.permission()}"/>
使用获取外部上下文进行重定向会导致消息丢失。
最佳答案
忽略一般设计问题(查看 here 作为起点),您似乎混淆了新的 JSF 2.2 <f:viewAction>
和旧的 JSF 2.0/2.1 <f:event type="preRenderView">
技巧。
返回导航结果为 String
仅在 <f:viewAction>
中支持 GET 请求,不在 <f:event type="preRenderView">
中。对于后者,您需要 ExternalContext#redirect()
你碰巧已经评论过了。
所以,你应该这样做
<f:event type="preRenderView" listener="#{bean.onload}"/>
public void onload() throws IOException {
// ...
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/index.xhtml");
}
或
<f:metadata>
<f:viewAction action="#{bean.onload}"/>
</f:metadata>
public String onload() {
// ...
return "/index.xhtml"; // Note: no need for faces-redirect=true!
}
不要混淆它们。
请注意,我编写代码的方式使您始终可以使用 /path
相对于网络根目录,无需摆弄 ../
废话。
另请参阅:
关于jsf - URL 重定向不适用于 preRenderView 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32544182/