简体   繁体   English

302重定向后的HTTP Referer

[英]HTTP Referer after 302 Redirect

I am creating a website using Java servlets, and I have a page called LogIn. 我正在使用Java servlet创建一个网站,我有一个名为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. 现在,这可以通过GET或来自另一个页面的POST工作,因为前一页存储在Referer头中。 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. 但是当我重定向(302)到LogIn页面时(从用户因为未登录而无法访问的页面),Referer标头为空。

Is there any way to achieve what I want when the user is redirected to the LogIn page? 当用户被重定向到LogIn页面时,有没有办法实现我想要的?

I wouldn't trust the referer header anyway since you're dependent on the browser whether it's been sent along. 我不相信referer标题,因为你依赖浏览器它是否已被发送。 Rather supply it yourself based on the current request URI. 而是根据当前请求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. 更新 :或者如果您想要无参数(根据您对其他答案的评论),(ab)使用会话。

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并重定向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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