views:

1128

answers:

1

after commit of response as here redirect statement should give exception but it is not doing so if this redirect statemnet is in if block.but it does give exception in case it is out of if block.i have shown same statement(with marked stars ) at two places below.can u please tell me reason for it.

protected void doPost(HttpServletRequest request, HttpServletResponse response)          throws    ServletException, IOException {
           // TODO Auto-generated method stub
  synchronized (noOfRequests)
 {
  noOfRequests++;
  }
    PrintWriter pw=null;
  response.setContentType("text/html");
  response.setHeader("foo","bar");

//response is commited because of above statement

  pw=response.getWriter();
  pw.print("hello : "+noOfRequests);

//if i remove below statement this same statement is present in if block.so statement in if block should also give exception as this one do, but its not doing so.why?

***response.sendRedirect("http://localhost:8625/ServletPrc/login%  20page.html");


 if(true)
 {
                  //same statement as above
  ***response.sendRedirect("http://localhost:8625/ServletPrc/login%20page.html");
 }
 else{

  request.setAttribute("noOfReq", noOfRequests);
  request.setAttribute("name", new Name().getName());
  request.setAttribute("GmailId",this.getServletConfig().getInitParameter("GmailId") );
  request.setAttribute("YahooId",this.getServletConfig().getInitParameter("YahooId") );
  RequestDispatcher view1=request.getRequestDispatcher("HomePage.jsp");
  view1.forward(request, response);

 }


}
+1  A: 

from the servlet specs, 5.3:

These methods will have the side effect of committing the response, if it has not already been committed, and terminating it. No further output to the client should be made by the servlet after these methods are called. If data is written to the response after these methods are called, the data is ignored.

If data has been written to the response buffer, but not returned to the client (i.e. the response is not committed), the data in the response buffer must be cleared and replaced with the data set by these methods. If the response is committed, these methods must throw an IllegalStateException.

I think that these two specifications covers all your cases.

dfa
i think u shd have look upon ma question again.after execution of statement setHeader reponse is commited.so any redrect statement will throw illegal state exception.but if redirect statement is put in if block then its not throwing exception even if if block is executed .
Maddy.Shik