简体   繁体   English

javascript-处理来自http响应的重定向

[英]javascript - Handling redirect from http response

I am trying to build a html page that when I enter it, it will redirect me to another page, depending on an attribute in the session. 我正在尝试构建一个html页面,当我输入它时,它将根据会话中的属性将我重定向到另一个页面。

If there is an attribute named "username" in the session, it will not redirect me, and otherwise it will. 如果会话中有一个名为“用户名”的属性,它将不会重定向我,否则它将重定向。

In order to do so, I wrote a javascript function that calles a java servlet that checks whether or not the attribute exists. 为了做到这一点,我编写了一个JavaScript函数,该函数调用一个Java servlet,以检查该属性是否存在。

<script type="text/javascript">
    var req = new XMLHttpRequest();
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            var data = req.responseText;
        }
        document.write(req.readyState);
    }
    req.open('POST','sessionCheck',true);
    req.send(null);
</script>

The code in the servlet is: Servlet中的代码是:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    HttpSession hs = request.getSession();
    String username = (String) hs.getAttribute("username");
    if (username == null)
            response.sendRedirect("/login.html");

}

I know that the resonse did send the redirect but the webpage was not redirected. 我知道共鸣确实发送了重定向,但网页未重定向。

*Note: I am using Eclipse Java EE for Web Developers. *注意:我正在使用Eclipse Java EE for Web Developers。

Thanks! 谢谢!

Javascript AJAX requests follow redirects. Javascript AJAX请求遵循重定向。 It is likely that your javascript code ended up requesting the page that you wished to redirect the browser to. 您的JavaScript代码很可能最终请求了您希望将浏览器重定向到的页面。

Try returning the page to redirect to as your response and then getting the browser to navigate to that page. 尝试返回要重定向到的页面作为您的响应,然后让浏览器导航到该页面。

You can see that the XMLHttpRequest standard states that redirects will be followed: 您可以看到XMLHttpRequest标准指出将遵循重定向:

HEADERS_RECEIVED (numeric value 2) HEADERS_RECEIVED(数值2)

All redirects (if any) have been followed and all HTTP headers of the final response have been received. 遵循所有重定向(如果有),并且已收到最终响应的所有HTTP标头。 Several response members of the object are now available. 该对象的几个响应成员现在可用。

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

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