简体   繁体   中英

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.

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.

<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:

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.

Thanks!

Javascript AJAX requests follow redirects. It is likely that your javascript code ended up requesting the page that you wished to redirect the browser to.

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:

HEADERS_RECEIVED (numeric value 2)

All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.

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