简体   繁体   中英

HTTP Referer after 302 Redirect

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?

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");

您可能只想将当前页面附加为GET参数,即http://yoursite.com/login?redir=/topics,以便在您的auth servlet中,如果用户没有相应的凭据,则只需获取当前页面uri,附加到登录URL并重定向。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM