2013-06-27 66 views
0

我正在嘗試從HTTPSession中註銷並將用戶重定向到登錄頁面。響應已提交後無法轉發 - Servlet

下面是我完整的Http servlet代碼。

import java.io.IOException; 
import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import javax.servlet.http.HttpSession; 

public class LogoutServlet extends HttpServlet { 

@Override 
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
{ 
    super.doGet(req, resp); 
    processRequest(req, resp); 
} 

@Override 
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException 
{ 
    super.doPost(req, resp); 
    processRequest(req, resp); 
} 

private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{ 
    final HttpSession session = request.getSession(false); 
    if (session != null) 
    { 
     session.invalidate(); 
    } 

    response.sendRedirect("/login.html"); 
    //getServletContext().getRequestDispatcher("/login.html").forward(request, response); 
} 

}

但是,得到以下異常:

java.lang.IllegalStateException: Cannot forward after response has been committed 
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:339) 
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:329) 
at com.controller.LogoutServlet.processRequest(LogoutServlet.java:41) 
+1

從您的位置發佈servlet的代碼processRequest() –

+0

@RaviThapliyal:使用完整代碼修改上述問題。 – Raghav

回答

4

刪除來電

super.doGet(req, resp); // and 
super.doPost(req, resp); 

基類的實現只是一味的拋出GET或不支持POST錯誤消息。

// HttpServlet#doGet() calls 
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg); 

上面的行是已經提交了響應。

+0

真棒,它運作良好。爲什麼要刪除這個特殊的原因? – Raghav

+1

這是RequestDispatcher.forward(ServletRequest req,ServletResponse resp)方法描述的一部分:「應在響應已提交給客戶端之前調用轉發(在響應正文輸出已刷新之前)。如果響應已被提交,這個方法會拋出一個IllegalStateException異常。響應緩衝區中的未提交輸出在轉發前自動清除「。你正在與這些超級調用作出迴應 – sunrize920

+0

@Raghav作爲更新回答了您的問題。 –

0

你爲什麼不重定向,而不是前鋒?

response.sendRedirect("/login.html"); 
+0

下面是例外,我得到的,如果我重定向:java.lang.IllegalStateException \t org.apache.catalina.connector.ResponseFacade.sendRedirect(ResponseFacade.java:473) \t com.controller.LogoutServlet.processRequest(LogoutServlet.java: 41) \t com.controller.LogoutServlet.doGet(LogoutServlet.java:23) \t javax.servlet.http.HttpServlet.service(HttpServlet.java:621) \t javax.servlet.http.HttpServlet.service(的HttpServlet。 java:722) – Raghav

相關問題