I am a newbie servlet programmer. I am trying to do this right.
I wrote a filter to intercept a servlet request and check if the URL needs the user to be logged in. If so the user gets directed to the login page. This is working. But then I want to redirect the user back the page he wanted to go to in the first place. What is the correct way to keep this state? Do I just store the URL in a data structure indexed using the session id from the cookie?
This doesn’t seem to sound right. You should rather map the
Filteron the sameurl-patternof theServlet, or better yet, on theservlet-nameof theServlet. This way theFilteris only invoked whenever theServletis called.Back to your actual problem: when the user is not logged in, you have two options:
Store the URL in session:
which you use on login:
Pass the URL as request parameter:
which you pass through to subsequent request as hidden input field:
which you use on login:
URL encoding as some suggest is not needed as the
getRequestURI()won’t be decoded.