2014-03-05 6 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; 
     } 

쿠키를 삭제할 때이 서블릿을 index.html로 리디렉션합니다. 내 문제는 내가 쿠키를 삭제할 때, 그것이 리디렉션되기 전에 자동으로 페이지를 새로 고침/새로 고침해야 index.html로 리다이렉트하지 않는다는 것입니다. 쿠키 삭제시 자동으로 리디렉션되도록하려면 어떻게해야합니까?쿠키 삭제시 리디렉션

답변

0

페이지가 이미로드되었을 때 쿠키를 삭제한다고 생각합니다. 서블릿의 요청 - 응답주기를 이해해야합니다.

서블릿은 컨테이너에서 새 요청을 받으면 실행됩니다. 페이지가 이미로드 된 다음 쿠키를 지우면 페이지가 새로 고쳐 지거나 서블릿에 새 요청이 전송 될 때만 서블릿이 실행됩니다.

+0

그래서 서블릿에서는 불가능합니다. –

+0

서블릿에 새로운 요청을 보내지 않는 한 불가능합니다. 요청 범위가 완료되었으며 브라우저에 렌더링되고 표시되는 내용을 볼 수 있습니다. 새로 고침 할 때 서블릿에 새로운 요청이 전송되고 쿠키가 없으면 서블릿이 리디렉션됩니다. –