aspose file tools*
The moose likes Web Component Certification (SCWCD/OCPJWCD) and the fly likes sendRedirect not throwing IllegalStateException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Web Component Certification (SCWCD/OCPJWCD)
Bookmark "sendRedirect not throwing IllegalStateException" Watch "sendRedirect not throwing IllegalStateException" New topic
Author

sendRedirect not throwing IllegalStateException

Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

Hello ranchers,when i noticed that forward() inside my jsp , throws IllegalStateException with this code.

java.lang.IllegalStateException: getOutputStream() has already been called for this response
So i tired the same with response.sendRedirect() which was not throwing an exception.
myjsp.jsp

This is all i have have written inside my jsp.So now when i invoke this jsp it successfully invokes the html page ? instead of exception.
Can someone explain why is it was throwing the exception in the previous case (with request dispatcher)?
and why it is not throwing in this case ?

So if any question related to this comes in exam say suppose the above code will throw exception Or not ? what should i answer.??
Regards Sagar.


OCJP-90%,OCPWCD-95%
Roel De Nijs
Bartender

Joined: Jul 19, 2004
Posts: 4919
    
  10

You should answer: "Bad design! Flow control logic should never be in a jsp, but in a servlet."


SCJA, SCJP (1.4 | 5.0 | 6.0), SCJD
http://www.javaroe.be/
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

Roel De Nijs wrote:You should answer: "Bad design! Flow control logic should never be in a jsp, but in a servlet."


I dint said that such question might appear.I meant "what if a question comes related to this concept which is unclear to me".
It will be helpful if someone solves my doubt.

Regards sagar.
Rohini Sahuji
Greenhorn

Joined: Jul 06, 2007
Posts: 19



java.lang.IllegalStateException is thrown if the response was already committed

that means..this exception occurs if you try to modify response object after you have performed forward.

the html code

%>
</body>
</html>

after forward be the reason...


SCJP
varun Dosapati
Ranch Hand

Joined: Nov 18, 2010
Posts: 30

Sagar





Are you trying to access directly the jsp.

Thanks
Varun Dosapati
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

varun Dosapati wrote:Sagar

Are you trying to access directly the jsp.

Thanks
Varun Dosapati


Yes Varun,i have not commited the response then why is it throwing one exception when i do forward,and why is it not throwing an exception when i do redirect ? Even in the logs it's not showing up.

Varun i have one more question to ask i tried this in my code.

but none of them is throwing Illegalstate exception.Someone suggested me to check out the generated servlet file and i did checked out but i
still dont get it.

Regards Sagar
varun Dosapati
Ranch Hand

Joined: Nov 18, 2010
Posts: 30

Sagar

I found some of the resources which might helpful to understand how the response.sendRedirect(/path) and dispatcher.forward(request,response) works.

http://www.theserverside.com/discussions/thread.tss?thread_id=26425

The below resource is for out.flush().
http://www.coderanch.com/t/172181/java-Web-Component-SCWCD/certification/flush-jsp-include

It looks like response.sendRedirect(/path) and out.flush() might having some temporary behavior.

Hope this helps.

Thanks
Varun Dosapati
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

CONFUSION 1

1) If you use a RequestDispatcher, the target servlet/JSP receives the same request/response objects as the original servlet/JSP. Therefore, you can pass data between them using request.setAttribute(). With a sendRedirect(), it is a new request from the client, and the only way to pass data is through the session or with web parameters (url?name=value).

2) A sendRedirect() also updates the browser history. Suppose you have JSP-1 which has a form that targets Servlet-2, which then redirects to JSP-3. With a redirect, the user's address bar will read "http://[host]/JSP-3". If the user clicks the Reload/Refresh button, only JSP-3 will be re-executed, not Servlet-2.

If you use a RequestDispatcher to forward from Servlet-2 to JSP-3, the user's address bar will read "http://[host]/Servlet-2". A reload/refresh will execute both Servlet-2 and JSP-3. This can be important if Servlet-2 performs some system update (such as credit-card processing).

That is nice to know.I never knew this.
But that still din't clear my doubt of why i am getting java.lang.IllegalStateException: getOutputStream() has already been called for this response
when i do this

My html has only 1 line which is simly a template text "Hello HTML"

CONFUSION 2
And comming to this

If we are allowed to do this then why is it mentioned in Head First Servlets on pg.no 137 that once committed too late rule applies also to setting headers,cookies,status codes,content type and so on.

Rancher really need your help in these two confusions i have mentioned above
varun Dosapati
Ranch Hand

Joined: Nov 18, 2010
Posts: 30


Confusion 2:
If we are allowed to do this then why is it mentioned in Head First Servlets on pg.no 137 that once committed too late rule applies also to setting headers,cookies,status codes,content type and so on.


Head Frist Servelt book is not a spec. It is just a reference which can have mistakes in it.

See this link: http://oreilly.com/catalog/errata.csp?isbn=9780596005405

So I you need accurate information go through the Servlet/JSP specification.
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202



See this link: http://oreilly.com/catalog/errata.csp?isbn=9780596005405

So I you need accurate information go through the Servlet/JSP specification.


But bro there is no errata mentioned for that page ?
Anyone please with a solution for my 2 confusions mentioned above ?
Sagar Shroff
Ranch Hand

Joined: Jun 07, 2011
Posts: 202

Any one please can explain the above two confusions
Frits Walraven
Creator of Enthuware JWS+ V6
Bartender

Joined: Apr 07, 2010
Posts: 1529
    
  22

Hi Sagar,

There is a difference in the behaviour of the HttpServletResponse.sendRedirect() and the RequestDispatcher.forward() methods

Here, the explanation from the Servlet specs (3.0)

5.3 Convenience Methods
  • sendRedirect
  • sendError
  • ...
    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.


    9.4 The Forward Method
    The forward method of the RequestDispatcher interface may be called by the calling servlet only when no output has been committed to the client. If output data exists in the response buffer that has not been committed, the content must be cleared before the target servlet's service method is called. If the response has been committed, an IllegalStateException must be thrown.


    Regards,
    Frits
    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202

    Frits Walraven wrote:


    9.4 The Forward Method
    If output data exists in the response buffer that has not been committed, the content must be cleared before the target servlet's service method is called. If the response has been committed, an IllegalStateException must be thrown.


    Regards,
    Frits

    Thanks for your reply but as the statement says that the if the response has been committed then an IllegalStateException must be thrown.,where as i have not committed my reponse.
    I have called my jsp directly form my browser and it contains only these two statements

    then why an exception ?
    The above spec content also says that the content must be cleared before the target servlet's service method is called.So i added an response.reset() between those two statements in the above code.
    But still it is throwing an exception.

    Regards,
    Sagar.
    Frits Walraven
    Creator of Enthuware JWS+ V6
    Bartender

    Joined: Apr 07, 2010
    Posts: 1529
        
      22

    then why an exception ?


    The exception is thrown because you are forwarding away from this JSP, and after the forward is called (at the end of this JSP) the container is trying to commit the response (but is has already been committed by forwarding to the html file).

    Regards,
    Frits
    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202

    So since the container always commits the response at the end of the jsp,this means that it is simply not possible to do a forward from a JSP ? then we can never use a JSP standard forward action?
    OR is there any mechanism to avoid the exception ?

    Regards Sagar.
    Frits Walraven
    Creator of Enthuware JWS+ V6
    Bartender

    Joined: Apr 07, 2010
    Posts: 1529
        
      22

    this means that it is simply not possible to do a forward from a JSP ? then we can never use a JSP standard forward action?

    It is good to explore the possibilities in a JSP, especially for certification reasons, but don't loose sight of reality.

    As Roel was saying earlier: Bad design! Flow control logic should never be in a jsp, but in a servlet. Furthermore, JSP 2.x was made to create scriptless JSPs.
    Conclusion: good learning stuff, but don't use it in real life.

    OR is there any mechanism to avoid the exception ?

    Yes there is, you can use the sendRedirect() method, but then you will have to use those ugly scripts again (<% ... %>).
    The other possibility is to use JSTL:
    which uses a HttpServletResponse.sendRedirect() method under the covers.....

    Regards,
    Frits
    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202

    ohkie frits.

    I have one more doubt,can you tell me why HFS on pg no 137 has mentioned that " once committed too late rule applies also to setting headers,cookies,status codes,content type and so on "
    I tried this

    and it was not throwing any exception.
    can you elaborate this sentence a bit.Because i think i am getting wrong somewhere in understanding this statement
    Frits Walraven
    Creator of Enthuware JWS+ V6
    Bartender

    Joined: Apr 07, 2010
    Posts: 1529
        
      22

    What is explained on that page is that you cannot commit the response and then forward.

    Like this is going to throw an java.lang.IllegalStateException:

    They also say that for practical reasons you can't write to the response and then forward (however the sendRedirect() won't throw an exception, the forward on a RequestDispatcher will)

    like this:

    Does this explanation make it any clearer?

    Regards,
    Frits
    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202

    Thanks for your time and explanation.
    Does this explanation make it any clearer?


    That's what i had thought about it.But its not working as it is saying because when i set an header or a cookie and do a forward its not getting any exception.
    I even checked the logs and its not showing any.I am using tomcat 6.
    Have you tried and have you got any exception ? Any idea about why i am not getting one ?

    Regard's Sagar
    Frits Walraven
    Creator of Enthuware JWS+ V6
    Bartender

    Joined: Apr 07, 2010
    Posts: 1529
        
      22

    Have you tried and have you got any exception ? Any idea about why i am not getting one ?

    The sendRedirect() won't throw an exception (as explained in HFS pag 137: "But some picky professor will tell you that technically, you could write to the stream without flushing, and then sendRedirect() wouldn't cause an Exception"

    Regards,
    Frits
    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202

    But i did a forward (Request Dispatcher) from my servlet and it din't threw any exception
    I give request to my servlet and this is my servlet


    and i am successfully getting the contents of inc.jsp.No exception.Not even shown in logs.

    Regards,
    Sagar.
    Frits Walraven
    Creator of Enthuware JWS+ V6
    Bartender

    Joined: Apr 07, 2010
    Posts: 1529
        
      22

    Ok, from a Servlet, you won't get an Exception and from a JSP you will get an Exception.

    The thing I said earlier is "What is explained on that page is that you cannot commit the response and then forward". This can also be found in the API and the Servlet specs.

    The other explanation in HFS is "for practical reasons you can't write to the response and then forward", meaning: you can do it but it doesn't make sense as the response is handled in the forwarded JSP, and not in this JSP. What should happen in such a case is not mandated by the specs....

    Regards,
    Frits
    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202

    Thanks
    R. Jain
    Ranch Hand

    Joined: Aug 11, 2012
    Posts: 367
        
        1

    Sagar Shroff wrote:Hello ranchers,when i noticed that forward() inside my jsp , throws IllegalStateException with this code.

    java.lang.IllegalStateException: getOutputStream() has already been called for this response
    So i tired the same with response.sendRedirect() which was not throwing an exception.
    myjsp.jsp

    This is all i have have written inside my jsp.So now when i invoke this jsp it successfully invokes the html page ? instead of exception.
    Can someone explain why is it was throwing the exception in the previous case (with request dispatcher)?
    and why it is not throwing in this case ?

    So if any question related to this comes in exam say suppose the above code will throw exception Or not ? what should i answer.??
    Regards Sagar.



    Update your code to add this : -



    I think it should work...
    R. Jain
    Ranch Hand

    Joined: Aug 11, 2012
    Posts: 367
        
        1

    R. Jain wrote:
    Sagar Shroff wrote:Hello ranchers,when i noticed that forward() inside my jsp , throws IllegalStateException with this code.

    java.lang.IllegalStateException: getOutputStream() has already been called for this response
    So i tired the same with response.sendRedirect() which was not throwing an exception.
    myjsp.jsp

    This is all i have have written inside my jsp.So now when i invoke this jsp it successfully invokes the html page ? instead of exception.
    Can someone explain why is it was throwing the exception in the previous case (with request dispatcher)?
    and why it is not throwing in this case ?

    So if any question related to this comes in exam say suppose the above code will throw exception Or not ? what should i answer.??
    Regards Sagar.



    Update your code to add this : -



    I think it should work...


    But in my case both are working: -

    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202

    R. Jain wrote:

    But in my case both are working: -


    How come ? as frits mentioned that after forward from your jsp it tries to commit the response so it should throw one exception.
    I guess you must be calling forward from your servlet.Try calling it from a jsp and then you'll get one.
    R. Jain
    Ranch Hand

    Joined: Aug 11, 2012
    Posts: 367
        
        1

    Sagar Shroff wrote:
    R. Jain wrote:

    But in my case both are working: -


    How come ? as frits mentioned that after forward from your jsp it tries to commit the response so it should throw one exception.
    I guess you must be calling forward from your servlet.Try calling it from a jsp and then you'll get one.


    Hello Sagar,

    I think I have the complete post before posting one myself.... And I also think that I very much know the difference between a Servlet and a JSP....

    I have added these codes to a JSP and it is working fine.... I though that forward will trouble only when, you modify the response object before forwarding.... But still then it is working fine....
    Now here I am myself confused...

    So, if anyone can explain, what exactly is the behaviour of this forward thing in JSP... it would be helpful for me...
    R. Jain
    Ranch Hand

    Joined: Aug 11, 2012
    Posts: 367
        
        1

    R. Jain wrote:
    Sagar Shroff wrote:
    R. Jain wrote:

    But in my case both are working: -


    How come ? as frits mentioned that after forward from your jsp it tries to commit the response so it should throw one exception.
    I guess you must be calling forward from your servlet.Try calling it from a jsp and then you'll get one.


    I though that forward will trouble only when, you modify the response object before forwarding.... But still then it is working fine....
    Now here I am myself confused...


    Yeah got it.... Modification of response object will not give an exception....
    Try to use: -
    response.flushBuffer() before forwarding the request.... You will get an error...
    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202

    R. Jain wrote:
    I have added these codes to a JSP and it is working fine.... I though that forward will trouble only when, you modify the response object before forwarding.... But still then it is working fine....
    Now here I am myself confused...
    So, if anyone can explain, what exactly is the behaviour of this forward thing in JSP... it would be helpful for me...

    Hey sorry i just had a guess that you might be using a servlet.

    When you send a request to this jsp

    it forward's the request to the html file.The response gets committed whenever you do a forward
    After the html file completes its response the control comes back to this jsp,(at the end of the jsp) the container tries to commit the response.It's kindda auto commit which
    i think container does to every jsp.So you should get an exception.

    Regards,
    Sagar.
    R. Jain
    Ranch Hand

    Joined: Aug 11, 2012
    Posts: 367
        
        1

    Sagar Shroff wrote:it forward's the request to the html file.The response gets committed whenever you do a forward
    After the html file completes its response the control comes back to this jsp,(at the end of the jsp) the container tries to commit the response.It's kindda auto commit which
    i think container does to every jsp.So you should get an exception.

    Regards,
    Sagar.


    I think what you are saying, happens in case of requestDispatcher.include() where you get the control back.... Not in forward....

    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202

    R. Jain wrote:
    I think what you are saying, happens in case of requestDispatcher.include() where you get the control back.... Not in forward....

    Nope it also happens in forward.

    Regards,
    Sagar.
    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202

    I have read about it.And if you dont believe me look at what other's have to say.
    Frits Walraven wrote:
    then why an exception ?


    The exception is thrown because you are forwarding away from this JSP, and after the forward is called (at the end of this JSP) the container is trying to commit the response (but is has already been committed by forwarding to the html file).

    Regards,
    Frits


    Regards,
    Sagar.

    R. Jain
    Ranch Hand

    Joined: Aug 11, 2012
    Posts: 367
        
        1

    Sagar Shroff wrote:I have read about it.And if you dont believe me look at what other's have to say.
    Frits Walraven wrote:
    then why an exception ?


    The exception is thrown because you are forwarding away from this JSP, and after the forward is called (at the end of this JSP) the container is trying to commit the response (but is has already been committed by forwarding to the html file).

    Regards,
    Frits


    Regards,
    Sagar.



    http://www.coderanch.com/t/362021/Servlets/java/RequestDispatcher-include-forward
    See this link..

    http://www.theserverside.com/discussions/thread.tss?thread_id=2205
    and this...


    You can also check the documentation for these methods... It will be clear...

    http://docs.oracle.com/javaee/5/api/javax/servlet/RequestDispatcher.html


    I says, you should not commit response before forward... Though you can commit after forward, as the control will never come back, so it doesn't matter whether the JSP page is commited after forward or not....
    It happens in include, and you will get exception....
    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202


    Yes buddy i know the difference between forward and include and i also know that the include is like a method call which happens at runtime/request time whatevr.
    But i have read about this concept that when you do a forward the container does give back the control to the one who makes the call.
    Though nothing will be printed after the forward.Do a sys.out and let me know.

    Regards,
    Sagar
    Sagar Shroff
    Ranch Hand

    Joined: Jun 07, 2011
    Posts: 202

    I will make it more easy for you read this
    http://www.coderanch.com/t/352916/Servlets/java/Servlet-Forward-behaves-like-break

    Regards,
    Sagar.
    A. Aka
    Ranch Hand

    Joined: Sep 08, 2012
    Posts: 44
    Hi,

    Why I am not getting any Exception as Sagar Shroff said with my JSP?





    My second question, the rule is what ? we should get IllegalStateException (with sendRedirect and RequestDispatcher)because we did a forward after writing to the response or after committing the response ?

    regards,

    Frits Walraven
    Creator of Enthuware JWS+ V6
    Bartender

    Joined: Apr 07, 2010
    Posts: 1529
        
      22

    Why I am not getting any Exception as Sagar Shroff said with my JSP?

    Yes, I also tried it and I also do not get an exception.

    My second question, the rule is what ? we should get IllegalStateException (with sendRedirect and RequestDispatcher)because we did a forward after writing to the response or after committing the response ?

    The specs say: an IllegalStateException should be thrown when the response has been committed. If you write to the response and then forward is not specified in the Servlet specs.

    Regards,
    Frits
    A. Aka
    Ranch Hand

    Joined: Sep 08, 2012
    Posts: 44
    @Frits

    maybe we are not getting Sagar Shroff exception because we are using a recent container, right ?
    I try this code I get a blank page and not IllegalStateException, why ?

    Frits Walraven
    Creator of Enthuware JWS+ V6
    Bartender

    Joined: Apr 07, 2010
    Posts: 1529
        
      22

    After some setups I think that I have got the explanation. I tested both on Tomcat 5.5 and Tomcat 7.0.

    Both throw an IllegalStateException from a JSP if you try to forward to a static HTML file:
    Both servers do not throw an exception when the forward is from a JSP to another JSP:
    Conclusion: the container handles a static HTML file different from a JSP file (although the generated java files of both JSPs look the same)

    Then coming back to your question:
    I try this code I get a blank page and not IllegalStateException, why ?

    System.out.println("before flush: " + response.isCommitted());
    Cookie c=new Cookie("mycoo","mycoo");
    response.addCookie(c); // write to the response
    response.setHeader("h","testh");
    response.addHeader("hh","testhhh");

    response.flushBuffer(); // commit the response
    System.out.println("after flush: " + response.isCommitted());

    You only make the response commit, but you don't do a forward. If you forward using the RequestDispatcher you will get an IllegalStateException

    Regards,
    Frits
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: sendRedirect not throwing IllegalStateException
     
    Similar Threads
    response.sendRedirect() behaviour
    sendRedirect method
    SendError function not throwing IllegalStateException
    IllegalStateException
    What is allowed after forward() ?