Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

res.sendRedirect()

 
Maria Smith
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Maria

Here is the code snippet

if (session == null) {

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


}

System.out.println("TEST");
 
Nathaniel Stoddard
Ranch Hand
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

What were you expecting this to do?
 
siva krishnan
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ken Robinson
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic