0

I have the following code in JSP.

try {
   ...
   if (...)
      response.sendRedirect("secondPage.jsp");
   ...
} catch (Exception e) {
   response.sendRedirect("thirdPage.jsp");
}

The page is not redirected as per the code. I am getting IllegalStateException in server.

  • possible duplicate of [java.lang.IllegalStateException: Cannot forward after response has been committed](http://stackoverflow.com/questions/2123514/java-lang-illegalstateexception-cannot-forward-after-response-has-been-committe) – Lion Apr 29 '13 at 05:16
  • If you have an exception stacktrace, then don't forget to post the full exception stacktrace the next time. – Lion Apr 29 '13 at 05:19

3 Answers3

0

As best of my knowledge... After redirect call:

  1. A response is created by server with status code 302.
  2. Response goes to browser, But don't display anything
  3. This response has the destination resource information.
  4. Browser takes this destination resource information and generates an inbuilt request to destination(But it never displays anything for this response)
  5. Request goes to destination and final response comes to browser and browser displays it.

Here 2 things to notice:

  1. In case of response.sendRedirect(-) control goes to final destination with 1 network round trip through browser.
  2. In this case it do not use same request and response objects(As Http is stateless protocol)

So keeping this in mind you should provide the absolute url(including web context or web-root folder) upto your final destination resource rather than relative url.

madth3
  • 7,275
  • 12
  • 50
  • 74
Shailesh Saxena
  • 3,472
  • 2
  • 18
  • 28
0

Your code should work. But , I recommended to use <JSP:FORWARD>.

Example :-

<jsp:forward page="index.jsp" />

Its more relevant to your purpose.Try, and hope it will help you.

JDGuide
  • 6,239
  • 12
  • 46
  • 64
0

Ensure you have not written anything to the response before your sendRedirect command.

Since you are getting IllegalStateException it looks like your jsp has already written some content to the response and then trying to redirect.

Also better option in this scenario is to write your logic in a Servlet.

Bhushan Bhangale
  • 10,921
  • 5
  • 43
  • 71