Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình

Cách xóa cookie với JSP

Xóa cookie rất đơn giản, làm theo 3 bước:

  1. Đọc cookie đã có và lưu vào đối tượng Cookie.
  2. Đặt tuổi cookie = 0 dùng setMaxAge() để xóa cookie hiện có.
  3. Thêm cookie này trở lại header phản hồi.

Ví dụ

Xóa cookie tên "first_name". Chạy main.jsp lần sau sẽ trả null cho first_name.

<html>
  <head> <title>Reading Cookies</title> </head>
  <body>
    <center> <h1>Reading Cookies</h1> </center>
    <%
      Cookie cookie = null;
      Cookie[] cookies = request.getCookies();
      if( cookies != null ) {
        out.println("<h2> Found Cookies Name and Value</h2>");
        for (int i = 0; i < cookies.length; i++) {
          cookie = cookies[i];
          if((cookie.getName()).compareTo("first_name") == 0) {
            cookie.setMaxAge(0);
            response.addCookie(cookie);
            out.print("Deleted cookie: " + cookie.getName() + "<br/>");
          }
          out.print("Name : " + cookie.getName() + ", ");
          out.print("Value: " + cookie.getValue() + " <br/>");
        }
      } else {
        out.println("<h2>No cookies founds</h2>");
      }
    %>
  </body>
</html>

Kết quả đầu ra

Cookies Name and Value
Deleted cookie : first_name
Name : first_name, Value: John
Name : last_name, Value: Player

Chạy lại https://localhost:8080/main.jsp – chỉ còn cookie last_name:

Found Cookies Name and Value
Name : last_name, Value: Player

Bạn cũng có thể xóa cookie thủ công trong IE: Tools → Internet Options → Delete Cookies.