Maddy.Shik
Maddy.Shik

Reputation: 6787

java servlet:response.sendRedirect() not giving illegal state exception if called after commit of response.why?

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);

    }


}               

Upvotes: 1

Views: 4554

Answers (2)

abhijit
abhijit

Reputation: 11

try putting a response.flush just before your first block ends, write as much as you want to but unless it is sent out of the buffer it is still not committed.

Upvotes: 1

dfa
dfa

Reputation: 116334

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.

Upvotes: 2

Related Questions