0 Replies Latest reply on Aug 27, 2004 2:37 AM by ashishabrol

    java.lang.IllegalStateException: Cannot forward after respon

    ashishabrol Newbie

      HI Everyone

      I am facing a big problem for quite sometime now because of which I am not able to proceed further. I would really appreictae if you guys could take some time out of your precious time and help mw out.

      I have a servlet here but the problem is that when I run this servlet I get

      /////////////////////////////////////////////////////////////////////////////////
      package com.hill_assoc.esp;

      import java.util.Date;
      import javax.servlet.*;
      import javax.servlet.http.*;
      import java.sql.*;
      import java.lang.*;
      import java.util.*;
      import java.io.*;
      import oracle.jdbc.*;
      import com.hill_assoc.esp.*;
      import java.text.SimpleDateFormat;

      public class CandidateStatus extends HttpServlet {
      public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
      doGet (req, res);
      }

      public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
      HttpSession session = null;
      ServletContext application = null;
      ServletConfig config = null;
      PrintWriter out = null;

      try{
      response.setContentType ("text/html; charset=UTF-8");
      application = getServletContext ( );
      config = getServletConfig ( );
      session = request.getSession ( );
      out = response.getWriter ( );

      request.setCharacterEncoding ("UTF-8");

      // Set to expire far in the past.
      response.setHeader ("Expires", "Sat, 6 May 1995 12:00:00 GMT");

      // Set standard HTTP/1.1 no-cache headers.
      response.setHeader ("Cache-Control", "no-store, no-cache, must-revalidate");

      // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
      response.addHeader ("Cache-Control", "post-check=0, pre-check=0");

      // Set standard HTTP/1.0 no-cache header.
      response.setHeader ("Pragma", "no-cache");

      AuthControl auth = new AuthControl ( );
      auth.validate (request, response, application);

      String message = "";
      String sSearchText = "";
      String sWhereClause = " ";
      String sStatus = "";
      String prevStatus = "Show All";
      String sRedirect = "currentPage";

      System.out.println ("sRedirect iun beginning=" + sRedirect);
      ArrayList AlResult = new ArrayList ( );
      int i = 0;
      int pageNumber = 0;
      int numberOfRows = Global.MAX_RECORDS_TO_BE_DISPLAYED;

      SimpleDateFormat myFormat = new SimpleDateFormat ("dd-MMM-yyyy");

      if (request.getMethod ( ).equals ("POST") && request.getParameter ("sFlag").equals ("0")){
      if (request.getParameter ("pageNumber") != null){
      pageNumber = Integer.parseInt (request.getParameter ("pageNumber").toString ( ));
      pageNumber++;
      }

      if (request.getParameter (
      "noOfprofiles") != null && !request.getParameter ("noOfprofiles").equals ("")){
      numberOfRows = Integer.parseInt (request.getParameter ("noOfprofiles"));

      if (request.getParameter (
      "noOfprofilesChanged") != null && request.getParameter (
      "noOfprofilesChanged").equals ("1")) {
      pageNumber = 0;
      }
      }

      if (request.getParameter (
      "hiddenSearchText") != null && request.getParameter ("hiddenSearchText").length ( ) > 0){
      sSearchText = request.getParameter ("hiddenSearchText");

      if (request.getParameter ("SearchText").equals (sSearchText)) {
      pageNumber = 0;
      }

      sWhereClause
      += " INSTR(CAND_GIVEN_NAME, '" + sSearchText + "') > 0 OR INSTR(CAND_SUR_NAME, '" + sSearchText
      + "') > 0 OR INSTR(MIDDLE_NAME, '" + sSearchText + "') > 0 ";
      }

      if (request.getParameter (
      "removeFilter") != null && request.getParameter ("removeFilter").equals ("1")){
      pageNumber = 0;
      sWhereClause = " ";
      }

      if (request.getParameter ("hFilterBy") != null){
      if (!session.getAttribute ("CandidateStatus").equals (request.getParameter ("hFilterBy"))) {
      pageNumber = 0;
      }

      if (request.getParameter ("hFilterBy").equals ("Report Ready")){
      sStatus += " AND INSTR(TAB_SCR_CASE.STATUS, 'Report Ready') > 0 ";
      prevStatus = "Report Ready";
      }
      else if (request.getParameter ("hFilterBy").equals ("Submitted")){
      sStatus += " AND INSTR(TAB_SCR_CASE.STATUS, 'Submitted') > 0 ";
      prevStatus = "Submitted";
      }
      else if (request.getParameter ("hFilterBy").equals ("Terminated")){
      sStatus += " AND INSTR(TAB_SCR_CASE.STATUS, 'Terminated') > 0 ";
      prevStatus = "Terminated";
      }
      else{
      request.getParameter ("hFilterBy").equals ("Show All");
      prevStatus = "Show All";
      }
      }

      String action = request.getParameter ("report");
      String mainpk = request.getParameter ("mainid");

      // Terminate, Viewing Report
      if (action != null && action.equals ("View Report")){
      String filename = request.getParameter ("filename");
      sRedirect = Global.BASE_URL + "/screen/report.jsp?filename=" + filename + "&mainid=" + mainpk;
      response.sendRedirect (Global.BASE_URL + "/screen/report.jsp?filename=" + filename + "&mainid=" + mainpk);
      }
      else if (action.equals ("Terminate")){
      mainpk = request.getParameter ("mainid");
      StatusController sc = new StatusController (application);
      sc.terminateStatus (Long.parseLong (mainpk));
      message = "Case Terminated!";
      pageNumber = 0;
      }
      else if (mainpk != null) {
      sRedirect = Global.BASE_URL + "/screen/set_curr_emp.jsp?mainid=" + mainpk;
      response.sendRedirect (Global.BASE_URL + "/screen/set_curr_emp.jsp?mainid=" + mainpk);
      }
      }

      String result = "";

      long userid = Long.parseLong (session.getAttribute (Global.USERID).toString ( ));
      long compid = Long.parseLong (session.getAttribute (Global.COMP).toString ( ));

      String username = session.getAttribute (Global.USERNAME).toString ( );

      SelectedCheckObject sco = (SelectedCheckObject)session.getAttribute (Global.SelectedCheck);

      if (sco == null){
      sco = new SelectedCheckObject ( );
      session.setAttribute (Global.SelectedCheck, sco);
      }

      ESPDBConn dbConn = new ESPDBConn (application);
      Connection con = dbConn.getConn ( );

      String sSortFld;
      String sValue;
      sSortFld = request.getParameter ("sSortField");

      if (request.getParameter ("SortType") != null && !request.getParameter ("SortType").equals ("")) {
      pageNumber = 0;
      }

      if (sSortFld == null || sSortFld.equals ("NAME")){
      sValue = " CAND_SUR_NAME, MIDDLE_NAME, CAND_GIVEN_NAME";

      if (request.getParameter (
      "SortType") != null && request.getParameter ("SortType").equals ("DESCENDING")) {
      sValue = " CAND_SUR_NAME DESC, MIDDLE_NAME DESC, CAND_GIVEN_NAME DESC";
      }
      }
      else{
      sValue = sSortFld;

      if (request.getParameter (
      "SortType") != null && request.getParameter ("SortType").equals ("DESCENDING")) {
      sValue += " DESC";
      }
      }

      // Search for records from screen-checking table
      String sql1 = "SELECT DISTINCT CANDIDATE_ID, TAB_SCR_CASE.STATUS, DUE_DATE, SUBMIT_DATE, REJ_RECORDS, CAND_GIVEN_NAME, CAND_NICK, MIDDLE_NAME, CAND_SUR_NAME FROM TAB_SCR_CASE, CANDIDATE_PROFILE_MST WHERE CANDIDATE_PROFILE_MST.COMPANY_ID = ? AND TAB_SCR_CASE.MAIN_ID = CANDIDATE_PROFILE_MST.CANDIDATE_ID " + sStatus + " ORDER BY "
      + sValue;

      if (!sWhereClause.trim ( ).equals ("")) {
      sql1
      = "SELECT DISTINCT CANDIDATE_ID, TAB_SCR_CASE.STATUS, DUE_DATE, SUBMIT_DATE, REJ_RECORDS, CAND_GIVEN_NAME, CAND_NICK, MIDDLE_NAME, CAND_SUR_NAME FROM TAB_SCR_CASE, CANDIDATE_PROFILE_MST WHERE CANDIDATE_PROFILE_MST.COMPANY_ID = ? AND TAB_SCR_CASE.MAIN_ID = CANDIDATE_PROFILE_MST.CANDIDATE_ID " + sStatus + " AND (" + sWhereClause + ") ORDER BY "
      + sValue;
      }

      System.out.println ("sql1=" + sql1);
      PreparedStatement ps1 = con.prepareStatement (sql1);

      ps1.setLong (1, compid);
      ResultSet rs1 = ps1.executeQuery ( );
      boolean bFound = false;

      for (; rs1.next ( ); i++){
      bFound = true;
      String candname = "";
      String sql2 =
      "SELECT TAB_SCR_CHK.PRIORITY , TAB_SCR_CHK.CURRENT_EMP FROM TAB_SCR_CHK WHERE TAB_SCR_CHK.MAIN_ID=?";

      PreparedStatement ps2 = con.prepareStatement (sql2);
      ps2.setLong (1, rs1.getLong ("CANDIDATE_ID"));
      ResultSet rs2 = ps2.executeQuery ( );

      String sql3 =
      "SELECT TAB_SCR_CHK.DEF_CHKTYPE FROM TAB_SCR_CHK WHERE MAIN_ID=? AND TAB_SCR_CHK.DEF_CHKTYPE IN ( SELECT DISTINCT TAB_CHK_LV_CHKTYPE.CHKTYPE_ID FROM TAB_CHK_LV_CHKTYPE WHERE ADDITION > 0)";

      PreparedStatement ps3 = con.prepareStatement (sql3);
      ps3.setLong (1, rs1.getLong ("CANDIDATE_ID"));
      ResultSet rs3 = ps3.executeQuery ( );

      if (i % 2 == 0)
      result = "";

      else
      result = "";

      result += "<td valign=top>";
      // Column: Name
      result += "<a href=" + Global.BASE_URL + "/screen/summary?mainid=" + rs1.getString ("CANDIDATE_ID");
      result += " align=\"left\">";

      result += Util.displayName (rs1.getString ("CAND_SUR_NAME"), rs1.getString ("MIDDLE_NAME"),
      rs1.getString ("CAND_GIVEN_NAME"), rs1.getString ("CAND_NICK"));
      result += "\n";

      candname = Util.displayName (rs1.getString ("CAND_SUR_NAME"), rs1.getString ("CAND_GIVEN_NAME"),
      rs1.getString ("CAND_NICK"));
      String tempstatus = rs1.getString (2);

      // Column: Submitted on
      result += "<td class=style6 valign=top align=\"center\">" + myFormat.format (
      rs1.getDate (
      "SUBMIT_DATE")) + "\n";
      // Column: Due to

      result += "<td class=style6 valign=top align=\"center\">" + myFormat.format (
      rs1.getDate ("DUE_DATE")) + "\n";

      // Column: Status
      result += "<td class=style6 width=\"19%\" valign=top align=\"left\">" + tempstatus + "\n";

      if (tempstatus.equals ("Terminated"))
      result += "<td class=style6 width=\"19%\" valign=top align=\"left\"> \n";

      else{
      result += "<td class=style6 valign=top>";

      if (rs2.next ( )){
      if (rs2.getInt ("PRIORITY") == 1) {
      result
      += "<img src=../../image/Icon/burningBird.jpg height=20 alt='This is a priority screening case.'> ";
      }

      if (rs2.getInt ("CURRENT_EMP") == 1) {
      result
      += "<img src='../../image/Icon/screenAll.jpg' height=20 alt='Most recent employment will be checked.'> ";
      }

      else if (rs2.getInt ("CURRENT_EMP") == 0)
      result
      += "<img src='../../image/Icon/notScreenCandEmployee.jpg' height=20 alt='Most recent employment will not be checked. To activate a check with a current employer click the E icon.' onClick=\"javascript:setEmp('"
      + rs1.getLong ("CANDIDATE_ID") + "');\"> ";

      else
      result += " ";

      if (rs1.getInt ("REJ_RECORDS") != 0) {
      result += "<a href='#' onclick=parent.location.href='../InsufficientInfo.jsp?mainid="
      + rs1.getString ("CANDIDATE_ID")
      + "'><img src='../../image/Icon/insufficient_info.jpg' border=0 height=20 alt='Insufficient information provided, click to view the details.'> ";
      }
      }

      String sTemp = "";
      String sParameters = "";
      int iCount = 0;

      while (rs3.next ( )){
      sParameters += rs3.getInt (1);
      sParameters += ",";
      iCount++;
      }

      if (!sParameters.equals ("")) {
      sTemp = sParameters.substring (0, sParameters.length ( ) - 1);
      }

      String s = Util.displayName (rs1.getString ("CAND_SUR_NAME"), rs1.getString ("CAND_GIVEN_NAME"),
      rs1.getString ("CAND_NICK"));

      if (!sTemp.equals ("")){
      result
      += "<img src='../../image/Icon/magnifyGlass.jpg' border=0 height=20 alt='Additional check have been selected, click to view details.'";
      result += " onclick=\"ShowDetailView('" + sTemp + "','" + s + "'," + iCount + ");\">";
      }

      result += "\n";
      }

      // Column: Action
      if (tempstatus.equals ("Report Ready")){
      result += "<td class=style6 valign=top align=\"center\">";
      result += "<a href=\"#\" onClick=\"setMainID(" + rs1.getLong ("CANDIDATE_ID") + ", '" + candname
      + "');\"><img src='" + Global.BASE_URL
      + "/image/Icon/PDFIcon.jpg' name=\"\" border=\"0\" alt=\"Click here to view the screening report. \">\n";
      }
      else if (!tempstatus.equals ("Terminated")){
      result += "<td class=style6 valign=top align=\"center\">";
      result += "<a href=\"#\" onClick=\"Terminate_MainID(" + rs1.getLong ("CANDIDATE_ID") + ",'"
      + rs1.getString ("CAND_SUR_NAME") + " " + rs1.getString (
      "CAND_GIVEN_NAME") + "');\"><img src='"
      + Global.BASE_URL
      + "/image/Icon/Terminate.jpg' name=\"\" border=\"0\" alt=\"Click here to terminate screening of this record.\">\n";
      }
      else
      result += "<td class=style6 valign=top align=\"center\"> \n";

      AlResult.add (result);

      ps2.close ( );
      ps3.close ( );
      }

      ps1.close ( );
      dbConn.close (con);

      RequestDispatcher rd = getServletContext ( ).getRequestDispatcher ("/ClientService/status.jsp");

      session.setAttribute ("CandidateStatus", prevStatus);
      session.setAttribute ("QueryResultset", AlResult);
      session.setAttribute ("ResultSize", new Integer (i));
      session.setAttribute ("pageNumber", new Integer (pageNumber));
      session.setAttribute ("noOfprofiles", new Integer (numberOfRows));
      session.setAttribute ("RedirectTo", sRedirect);
      System.out.println ("sRedirect in servlet1=" + session.getAttribute ("Redirect"));

      if (bFound) {
      session.setAttribute ("bFound", new String ("1"));
      }
      else {
      session.setAttribute ("bFound", new String ("0"));
      }

      if (sSearchText == null) {
      session.setAttribute ("sSearchText", "");
      }
      else {
      session.setAttribute ("sSearchText", sSearchText);
      }

      rd.forward (request, response);
      // response.sendRedirect(Global.BASE_URL + "/ClientService/status.jsp");
      }catch (Throwable e) {
      e.printStackTrace ( );
      }
      }
      }
      /////////////////////////////////////////////////////////////////////////////////


      When I run this I get the following error->

      14:16:36,237 INFO [STDOUT] java.lang.IllegalStateException: Cannot forward after response has been committed
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:324)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
      14:16:36,237 INFO [STDOUT] at com.hill_assoc.esp.CandidateStatus.doGet(CandidateStatus.java:362)
      14:16:36,237 INFO [STDOUT] at com.hill_assoc.esp.CandidateStatus.doPost(CandidateStatus.java:16)
      14:16:36,237 INFO [STDOUT] at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
      14:16:36,237 INFO [STDOUT] at javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
      14:16:36,237 INFO [STDOUT] at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:72)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
      14:16:36,237 INFO [STDOUT] at org.jboss.web.tomcat.security.JBossSecurityMgrRealm.invoke(JBossSecurityMgrRealm.java:275)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:117)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
      14:16:36,237 INFO [STDOUT] at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
      14:16:36,253 INFO [STDOUT] at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929)
      14:16:36,253 INFO [STDOUT] at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160)
      14:16:36,253 INFO [STDOUT] at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
      14:16:36,253 INFO [STDOUT] at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
      14:16:36,253 INFO [STDOUT] at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577)
      14:16:36,253 INFO [STDOUT] at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
      14:16:36,253 INFO [STDOUT] at java.lang.Thread.run(Thread.java:534)


      But when I comment the response.sendRedirect statements on the line 116 and 127 it runs perfectly.