All Things Techie With Huge, Unstructured, Intuitive Leaps

JSP ~ Login before going to bookmark or URL

So you have a web app or website in JSP where you want the user to login before proceeding to a bookmarked page or a URL. And you want to proceed to that page or URL automatically after login. How do you do it?

For me, every protected JSP page has an include page:

<%@ include file="isLoggedIn.jsp"%>

That file, isLoggedIn.jsp is called on every page. In that file, the first thing that I do, is I get the request URL. I do it like this:

String redirectUrl = request.getRequestURL().toString();

Then is there is a query string afterwards ( -- the query string is showMe=cars), you need to get the query string in a separate step:

String queryString = request.getQueryString();

Since the queryString doesn't have the question mark, you need to re-assemble the called URL:

redirectUrl = redirectUrl +"?"+queryString;

Now I usually have a session attribute called "AccessGranted" or "isLoggedIn". I check for that:

String accessGranted = (String) session.getAttribute("AccessGranted");

if (accessGranted.equalsIgnoreCase("false"))

What you see above, is that I send the request URL to the login page.

On the login page, if the login is successful, I redirect to a menu page. Otherwise, I redirect to the URL that was called in the first place. I do it this way:

String redirectURL = (String) request.getParameter("requrl");
if (redirectURL == null)
redirectURL = "menuPage.jsp";

If the login fails, then:


Finally I send the user to where they have to go with the jsp redirect directive:


Easy as pie.

No comments:

Post a Comment