7
resp.sendRedirect("/myurl");
req.getSession().setAttribute("foo", "bar");

In this case, do I have access to the foo attribute after the redirect? On generally speaking, a servlet is completely executed before the redirect is made or it stops it's execution after the redirect line?

Thanks

KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
TGM
  • 1,659
  • 10
  • 30
  • 45
  • 5
    From my personal experience, it should be noted that after `sendRedirect` has been called, the response has been committed so any further modifications to the response will result in an exception being thrown. Therefore your function should `return` once you have invoked `sendRedirect`. – Hamed Sep 30 '11 at 16:00
  • Related: http://stackoverflow.com/questions/2123514/java-lang-illegalstateexception-cannot-forward-after-response-has-been-committed/2125045#2125045 – BalusC Sep 30 '11 at 16:01
  • I agree with @Hamed; it's confusing to continue processing, although if you're not modifying the response, you *can*. – Dave Newton Sep 30 '11 at 16:10

3 Answers3

8

It continues execution.

It's not a return, it just adds information to the response.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
0

after redirecting to that particular page, the control goes to that page and come back to old page and execute the req.getSession().setAttribute("foo", "bar"); also. this is the sendRedirect() bahaviour

chakri
  • 629
  • 3
  • 11
  • 21
0

I found out a more generic approach that works for jsp files as well as for servlets.

String url = "http://google.com";

response.reset();
response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setHeader("Location",url);
response.getWriter().close();
response.getWriter().flush();
Dirk
  • 1
  • 1