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时自动重定向?
答案 0 :(得分:0)
我相信您在页面加载时删除了Cookie。您需要了解servlet的请求 - 响应周期。
只有在容器收到新请求时才会执行Servlet。一旦您的页面已经加载然后清除了您的cookie,您的servlet将仅在刷新页面时执行(或者将新的请求发送到servlet)。