title: Cannot forward after response has been committed - Servlet
body: <p>I am trying to logout from the HTTPSession and redirect the user to the login page.</p>
  
  <p>Below is my complete Http servlet code as is.</p>
  
  <pre><code>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);
  }
  </code></pre>
  
  <p>}</p>
  
  <p>But getting the below exception:</p>
  
  <pre><code>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)
  </code></pre>