title: Captcha servlet causes java.lang.IllegalStateException: PWC3999: Cannot create a session after the response has been committed
body: <p>I am creating a CAPTCHA input using SimpleCaptcha, and did validation of the Captcha input. I am created a captcha input with the following codes.</p>
  
  <p>HTML Code:</p>
  
  <pre><code>&lt;form action="submit_proceed.do" method="post"&gt;
  &lt;img src="captchaImg" /&gt;&lt;input type="text" name="captcha" value=""&gt;&lt;br /&gt;
  &lt;input type="submit" value="Submit" name="submit" /&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>JavaServlet Code :</p>
  
  <pre><code>import java.io.IOException;
  import java.io.PrintWriter;
  import javax.servlet.ServletException;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.util.List;
  import java.util.Iterator;
  import nl.captcha.Captcha;
  
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();
  
  List errorMsgs = new LinkedList();
  try{
      // Validate Captcha
      HttpSession session = request.getSession(true);
      String userCaptcha = request.getParameter("captcha");
      Captcha captcha = (Captcha) session.getAttribute(Captcha.NAME);
      if (!captcha.isCorrect(userCaptcha)) {
          errorMsgs.add("Please input the correct Captcha value.");
      }
  } catch (RuntimeException e) {
      errorMsgs.add("An unexpected error: " + e.getMessage());
      RequestDispatcher view = request.getRequestDispatcher("/error.view");
      view.forward(request, response);
  }
  </code></pre>
  
  <p>However I kept getting this error:</p>
  
  <pre><code>StandardWrapperValve[Captcha]: PWC1406: Servlet.service() for servlet Captcha threw exception
  java.lang.IllegalStateException: PWC3999: Cannot create a session after the response has been committed
  </code></pre>
  
  <p>How do I create a session on my servlet? How can I resolve this issue?</p>
  
  <p>Thank you very much.</p>