【问题标题】:Redirect when cookies are deleted删除 cookie 时重定向
【发布时间】:2014-03-05 22:49:34
【问题描述】:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html"); //setting the MIME of this page

    PrintWriter out = response.getWriter(); //creating a writer object          
        String sourceCookieName = "Username"; 
        String sourceCookieName2 = "Password"; 
        Cookie targetCookie = null;
        Cookie targetCookie2 = null;
        Cookie[] allCookies = request.getCookies();

        if (allCookies!=null) {
            for (Cookie cookie : allCookies) {
                if (cookie.getName().equals(sourceCookieName)) {
                    targetCookie = cookie;
                    //break;
                }
                if (cookie.getName().equals(sourceCookieName2)) {
                    targetCookie2 = cookie;
                    //break;
                }
            }
        }
        if (targetCookie != null && targetCookie2 != null) {
            //somecode
        } 
        else {
            out.print("<p><h1>You will be redirected in <span id='counter'>5</span> second(s).</h1></p>");
            out.print("<script type='text/javascript'>");
            out.print("function countdown() {");
            out.print("var i = document.getElementById('counter');");
            out.print("if (parseInt(i.innerHTML)<=1) {");
            out.print("location.href = 'index.html';");
            out.print("}");
            out.print("i.innerHTML = parseInt(i.innerHTML)-1;");
            out.print("}");
            out.print("setInterval(function(){ countdown(); },1000);");
            out.print("</script>");
            //response.sendRedirect("index.html");
            return;
        }

我有这个 servlet,它会在 cookie 被删除时重定向到 index.html。我的问题是,当我删除 cookie 时,它​​不会自动重定向到 index.html 我需要在重定向之前先重新加载/刷新页面。删除 cookie 后如何使其自动重定向?

【问题讨论】:

    标签: java servlets redirect cookies


    【解决方案1】:

    我相信您在页面已加载时正在删除 cookie。您需要了解 servlet 的请求-响应周期。

    只有在容器收到新请求时才会执行 Servlet。一旦您的页面已经加载,然后您清除了 cookie,您的 servlet 将仅在页面刷新时执行(或者将向 servlet 发送新请求)。

    【讨论】:

    • 所以这对于 servlet 是不可能的?
    • 除非您向 servlet 发送新请求,否则这是不可能的。您的请求范围已完成,您看到的任何内容都已呈现并呈现在您的浏览器中。当您刷新时,将向 servlet 发送一个新请求,这一次如果 cookie 不存在,您的 servlet 将重定向。
    猜你喜欢
    • 1970-01-01
    • 2015-12-22
    • 2010-11-19
    • 2012-11-06
    • 2016-08-12
    • 2013-03-29
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    相关资源
    最近更新 更多