【问题标题】:IllegalStateException after sendRedirectsendRedirect 后出现 IllegalStateException
【发布时间】:2017-10-26 14:52:29
【问题描述】:

我正在使用带有 JSF2 框架的 Glassfish 4 服务器。

我的问题

调用 response.sendRedirect 方法时,我遇到了 IllegalStateException。

我不知道为什么会引发此异常。

上下文

对于每个 xhtml 页面,我都会调用这个方法来检查用户是否仍然登录。

<body id="body" onload="#{utilisateurBean.isUserLoggedIn()}">

方法

public void isUserLoggedIn() throws IOException {
    if(this.user == null){
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        response.sendRedirect("Project/accueil/index.xhtml");
    }
}

例外

Infos:   Exception when handling error trying to reset the response.
java.lang.IllegalStateException

或者

Avertissement:   Servlet.service() for servlet session.AppExceptionHandler threw exception
java.lang.IllegalStateException: Cannot forward after response has been committed

我不知道为什么要提交响应。

感谢您的帮助:)

【问题讨论】:

    标签: java servlets


    【解决方案1】:

    当响应已经提交/定义时,您不能更改响应。

    这里您正在显示页面,因此您的响应已经定义。

    您必须以另一种方式执行此操作,例如显示一条错误消息,说明用户未连接并要求用户再次登录。

    您也可以使用 javascript 进行重定向。

    【讨论】:

    • 谢谢,我解决了我的问题。我不知道为什么,但删除样式标签内的 CSS(在 head 标签中)就可以了。
    【解决方案2】:

    使用以下 sn-p 更改您的代码:

    public void isUserLoggedIn() throws IOException {
    if(this.user == null){
        HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
        response.sendRedirect("Project/accueil/index.xhtml");
        return;
     }
    }
    

    或添加检查以验证是否已提交响应。

    response.isCommitted()
    

    有关已提交响应的更多信息,请查看this

    【讨论】:

    • 感谢您的回答。我的问题来自在 head 标签内编写 CSS。删除它解决了问题
    猜你喜欢
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-29
    相关资源
    最近更新 更多