File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Forwarding from servlet to JSP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Servlets
Bookmark "Forwarding from servlet to JSP" Watch "Forwarding from servlet to JSP" New topic

Forwarding from servlet to JSP

Raycho Belchilov

Joined: Mar 24, 2012
Posts: 7
Hi, my question is about forwarding from a servlet to a JSP. Here is my servlet:

So if the session has expired the servlet redirects to login.jsp. The problem is that codeA is also executed. I want if the session has expired, the servlet to redirect to the JSP and codeA to be ignored. CodeA must be executed only when the session is valid. I know I can do it this way:

However putting my long code in an else clause makes it more difficult to read. That's why I am asking if there is another way - a command that forwards to a JSP and discards the remaining code (like <jsp:forward page="/..."/> in JSPs).
Paul Clapham

Joined: Oct 14, 2005
Posts: 19973

This is not a question about servlets, and it's not a question about forwarding to a JSP. The code in a servlet is Java code and it follows all of the rules of Java code. Nothing special happens in your Java code because it is in a servlet.

In other words you already know the answer to this. An alternative to


Or you could put your "long code" into another method and call it from this one... there's lots of Java options you could use. Just don't get distracted by the fact that your Java code happens to be in a servlet.
Piyush Mangal
Ranch Hand

Joined: Jan 22, 2007
Posts: 196
You should probably use Filter to check if User is logged out or not. Otherwise you would have to duplicate the check in every servlet in your application.
Raycho Belchilov

Joined: Mar 24, 2012
Posts: 7
Thanks for the answers! Using a filter is really the best solution in this case.
I agree. Here's the link:
subject: Forwarding from servlet to JSP
It's not a secret anymore!