2012-01-26 22 views
2

我有一個JSF2應用程序。我有一個會話作用域的登錄bean和一個作爲視圖作用域的註銷bean。當我登錄時,我使用重定向,它工作正常。但是,註銷失敗並重定向。如果我註銷而不重定向,它的作品。註銷失敗後使用java.lang.IllegalStateException重定向:在提交響應後無法創建會話

@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"; 
    } 
} 

登錄頁面綁定到登錄bean,所以我懷疑這可能與它有關,但我不明白爲什麼它不起作用。錯誤是:

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

我的猜測是它的嘗試,因爲我訪問會話bean創建登錄頁面上的會話,雖然我看不出什麼毛病這個和它的作品沒有重定向。

我正在使用MyFaces 2.1。

回答

3

我會推薦使用Servlet而不是bean註銷,託管bean(尤其是視圖範圍)不適合註銷。例如:

@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); 
    } 
} 
+0

這是一個好主意,沒有想到這一點。我會試一試。謝謝 – rozner

0

它似乎與在視圖範圍內的bean有關,它本身應該在會話中序列化。請改爲請求作用域。無論如何,視圖範圍對退出沒有多大意義。

@ManagedBean 
@RequestScoped 
public class MbLogout extends BaseJsf { 
    // ... 
} 
相關問題