jsf - URL 重定向不适用于 preRenderView 事件

标签 jsf redirect jsf-2.2 prerenderview

我终于在页面之间传递了消息,但这并没有将我重定向到用户登录页面(../../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/

相关文章:

django:临时重定向和永久重定向之间有什么区别?

performance - 有没有办法在 JSF 中获得更好的缩小 HTML?

jsf - 如何退出流?

JSF 为组件声明定义自定义命名空间

java - 如何在现有的 java web 应用程序中使用 Node.js 效率

jsf - AF :convertNumber element removes zero in the end of the value

asp.net-mvc - 如何根据区域将未经授权的用户重定向到登录页面?

java - 如何使用 JSF Richfaces AJAX 向/从 bean 函数发送/接收数据?

Magento 添加到购物车并重定向到结账(产品页面 : on "Checkout" button, "Add to Cart"重定向到购物车)

hibernate-validator - 覆盖默认的 Hibernate Validator 消息