I wrote a filter to intercept a servlet request and check if the URL needs the user to be logged in.
This doesn't seem to sound right. You should rather map the Filter
on the same url-pattern
of the Servlet
, or better yet, on the servlet-name
of the Servlet
. This way the Filter
is only invoked whenever the Servlet
is called.
Back to your actual problem: when the user is not logged in, you have two options:
Store the URL in session:
if (session.getAttribute("user") == null) {
session.setAttribute("back", httpRequest.getRequestURI());
httpRequest.sendRedirect("login");
} else {
chain.doFilter(request, response);
}
which you use on login:
User user = userDAO.find(username, password);
if (user != null) {
session.setAttribute("user", user);
String back = (String) session.getAttribute("back");
if (back != null) {
session.removeAttribute("back");
response.sendRedirect(back);
} else {
response.sendRedirect("home"); // Home page?
}
} else {
// Show error?
request.setAttribute("message", "Unknown user, please retry");
request.getRequestDispatcher("login").forward(request, response);
}
Pass the URL as request parameter:
if (session.getAttribute("user") == null) {
httpRequest.sendRedirect("login?back=" + httpRequest.getRequestURI());
} else {
chain.doFilter(request, response);
}
which you pass through to subsequent request as hidden input field:
<input type="hidden" name="back" value="${param.back}">
which you use on login:
User user = userDAO.find(username, password);
if (user != null) {
session.setAttribute("user", user);
String back = request.getParameter("back");
if (back != null) {
response.sendRedirect(back);
} else {
response.sendRedirect("home"); // Home page?
}
} else {
// Show error?
request.setAttribute("message", "Unknown user, please retry");
request.getRequestDispatcher("login").forward(request, response);
}
URL encoding as some suggest is not needed as the getRequestURI()
won't be decoded.