HTTP Referer after 302 Redirect

DanielGibbs picture DanielGibbs · Jan 11, 2011 · Viewed 7.4k times · Source

I am creating a website using Java servlets, and I have a page called LogIn. What I want to happen, is that once the user successfully fills out the login form, it returns them to the page that they were previously on.

Now this works fine with a GET or a POST from another page, because the previous page is stored in the Referer header. But when I redirect (302) to the LogIn page (from a page that a user cannot access because they are not logged in), the Referer header is null.

Is there any way to achieve what I want when the user is redirected to the LogIn page?

Answer

BalusC picture BalusC · Jan 11, 2011

I wouldn't trust the referer header anyway since you're dependent on the browser whether it's been sent along. Rather supply it yourself based on the current request URI.

response.sendRedirect("login?from=" + URLEncoder.encode(request.getRequestURI(), "UTF-8"));

and then in the login form

<form action="login" method="post">
    <input type="text" name="username">
    <input type="password" name="password">
    <input type="hidden" name="from" value="${param.from}">
    <input type="submit">
</form>

and then in the login action

User user = userDAO.find(username, password);
if (user != null) {
    session.setAttribute("user", user);
    response.sendRedirect(request.getParameter("from"));
} else {
    request.setAttribute("error", "Unknown login");
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
}

Update: or if you want to be parameter-less (as per your comment on other answer), (ab)use the session.

session.setAttribute("from", request.getRequestURI());
response.sendRedirect("login");

and then in the login action

response.sendRedirect((String) session.getAttribute("from"));
session.removeAttribute("from");