Say we have a link to a target page (not login page) in the email sent to the user. How can the user be redirected to the target page after he/she login? Spring is in the backend.
-
Please provide your current login code! – Jasdeep Khalsa Dec 25 '12 at 02:48
-
Just require a login for the target page? If the target page is requested without login, then Spring Security (or whatever authentication framework you're using, including standard Java EE container managed authentication) should already automatically remember the initially requested page and thus redirect back to it after successful login. Or are you using homegrown authentication instead? – BalusC Dec 25 '12 at 02:58
-
@BalusC We are using homegrown authentication instead. – blue123 Dec 25 '12 at 03:36
-
This is almost certainly a bad idea (TM). Since you are already using Spring, why not use Spring Security? Are your requirements so special that a mature, well-tested solution won't do? – GreyBeardedGeek Dec 25 '12 at 04:37
2 Answers
We are using homegrown authentication
At the moment when you're checking the before continuing the request (which, in case of homegrown authentication, is usually performed in a servlet filter), you can just use HttpServletRequest#getRequestURI() to get the current request URI.
String requestedURI = request.getRequestURI();
You just have to remember this in either the session scope or as a hidden input field of the login form. Once the login succeeds, then you just have to redirect to it.
response.sendRedirect(requestedURI);
-
What are the drawbacks if `Cookie` is used to store the data instead of session or hidden input? – Vikas V Dec 25 '12 at 11:24
-
It's clumsy. The session is easier to use (and is under the covers already backed by a cookie, see also http://stackoverflow.com/questions/3106452/how-do-servlets-work-instantiation-session-variables-and-multithreading/3106909#3106909). – BalusC Dec 25 '12 at 11:34
To add detail to BalusC's answer, even though you're using a home-grown solution, I highly recommend you read over Spring Security's description of "Authentication in a Web Application". It's pretty short and is essentially a direct answer to your question with some hints on how to implement. If you want to dig deeper, you can jump over to the Javadocs or even dig into the source code to see how they do it. It's a very elegant and flexible solution, and there's no harm in borrowing some ideas or even some code from the project.
- 126,015
- 21
- 180
- 199