File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes res.sendRedirect() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "res.sendRedirect()" Watch "res.sendRedirect()" New topic


Maria Smith
Ranch Hand

Joined: Apr 01, 2004
Posts: 40
In my servlet I am checking for the session object after user logs in.
If session == null then I am using res.sendRedirect() method to redirect
the request to login page.
But the problem is if the session is null the execution of the servlet
enters if block, after executing res.sendRedirect() method it redirects request to login page
but it also prints "TEST" on the console. I am really confused

Someone please help me

Thanks in advance

Here is the code snippet

if (session == null) {

String encodeURL = res.encodeURL(req.getScheme() + "://" +
req.getServerName() + ":" +
req.getServerPort() +/examples/jsp/login.jsp");


Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258

What were you expecting this to do?

siva krishnan

Joined: Apr 26, 2003
Posts: 21
I guess what Maria expected was that control goes to the redirect URL and never comes back to the calling servlet in which case "TEST" would not get printed.
Maria, correct me if I have interpreted your query wrong.

Cheers<br />Siva<br />SCJP 1.4<br />SCWCD 1.3
Ken Robinson
Ranch Hand

Joined: Dec 23, 2003
Posts: 101
This is expected behavior.

Calling resp.sendRedirect() is just a method call. When completed, it returns to where it was called. Your System.out.println is executed as it should be.

The javadoc for resp.sendRedirect() states that the response object is now considered complete. You cannot write anything to the repsponse object, but that does not change how java itself works.

The doPost/doGet method of a servlet will execute until the method ends, a return is encountered or an Exception is thrown. Certain actions on a response that is commited can cause an Exception to be thrown, but a System.out.println is not tied to the response, so that will execte.

Simply put a return after the sendRedirect.
[ July 13, 2004: Message edited by: Ken Robinson ]
Maria Smith
Ranch Hand

Joined: Apr 01, 2004
Posts: 40
Thank you so much for your help guys.

Ken you are right. I just used "TEST" as an example. Actually
doPost method in my servlet was getting executed.
and it was throwing a null pointer exception.

Per your suggestion I put "return" after sendredirect and it did the magic.

Once again thank you very much . I really appreciate your help!
I agree. Here's the link:
subject: res.sendRedirect()
It's not a secret anymore!