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後重定向
所以這不可能用於servlet嗎? –
直到你發送一個新的請求到servlet,這是不可能的。您的請求範圍已完成,您看到的任何內容都已呈現並顯示在您的瀏覽器中。當你刷新時,一個新的請求將被髮送到這個servlet,這個時候你的servlet將會重定向,如果這個cookie不存在的話。 –