2014-03-05 117 views
0
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。我的问题是,当我删除cookies时,它不会自动重定向到index.html,我需要在重定向之前先重新加载/刷新页面。如何在删除Cookie后自动重定向?删除cookies后重定向

回答

0

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

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

+0

所以这不可能用于servlet吗? –

+0

直到你发送一个新的请求到servlet,这是不可能的。您的请求范围已完成,您看到的任何内容都已呈现并显示在您的浏览器中。当你刷新时,一个新的请求将被发送到这个servlet,这个时候你的servlet将会重定向,如果这个cookie不存在的话。 –