Redirect after logout fails with java.lang.IllegalStateException: Cannot create a session after the response has been committed

回眸只為那壹抹淺笑 提交于 2020-01-02 14:47:15

问题


I have a JSF2 application. I have a login bean which is session scoped and a logout bean which is view scoped. When I login I use redirect and it works fine. However the logout fails with redirect. If I logout without redirect it works.

@ManagedBean
@ViewScoped
public class MbLogout extends BaseJsf {
    private static final long serialVersionUID = 2992671241358926373L;

    public String logout() throws DfException {
        getFacesContext().getExternalContext().invalidateSession();

        //return "login?faces-redirect=true"; // fails with this
        return "login";
    }
}

The login page has bindings to the login bean so I suspect this may have something to do with it, although I don't see why it doesn't work. The error is:

java.lang.IllegalStateException: Cannot create a session after the response has been committed

My guess is it's trying to create a session on the login page since I access the session bean although I don't see anything wrong with this and it works without redirect.

I'm using MyFaces 2.1.


回答1:


I would recommend using a Servlet rather than a bean for logout, a managed bean (especially view scoped) is not fitting for the purpose of logging out. For example:

@WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"}) // Can be configured in web.xml aswell
public class LogoutServlet extends HttpServlet {

    private static final String redirectURL = "http://www.somepage.com";

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Destroys the session for this user.
        if (request.getSession(false) != null) {
            request.getSession(false).invalidate();
            }
        response.sendRedirect(redirectURL );
    }
}



回答2:


It seems to be related to the bean being in the view scope which should by itself be serialized in the session. Make it request scoped instead. The view scope doesn't make much sense for logout anyway.

@ManagedBean
@RequestScoped
public class MbLogout extends BaseJsf {
    // ...
}


来源:https://stackoverflow.com/questions/9017487/redirect-after-logout-fails-with-java-lang-illegalstateexception-cannot-create

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!