I would prefer the first above the second solution. This is request scoped information and really doesn't belong in the session, it would only lead to "wtf?" experiences when you have multiple windows/tabs open in the same session.
On the link to the login page, just pass the current URL as request parameter:
<a href="/login?from=${pageContext.request.requestURI}">Login</a>
Or if it is a POST form to the login page:
<input type="hidden" name="from" value="${pageContext.request.requestURI}">
In the login form, transfer it to the next request as hidden variable:
<input type="hidden" name="from" value="${param.from}">
In the login servlet, make use of it:
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user);
response.sendRedirect(request.getParameter("from"));
} else {
// Show error.
}
Fairly simple, isn't it? :)
Some may suggest to use request.getHeader("referer")
for this inside the login form instead of request.getRequestURI()
in the link/button before login, but I wouldn't do that as this is client-controlled and doesn't always return reliable information. Some clients have disabled it or are using some software which spoofes it with an invalid value, such as most of the (cough) Symantec products do.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…