如何用JSP刪除Cookie?
刪除Cookie非常簡單。如果你想刪除一個Cookie,那麼你只需要按照以下三個步驟進行操作 -
讀取已存在的Cookie並將它儲存在Cookie物件中。
使用setMaxAge()方法將Cookie年齡設定為零以刪除現有的Cookie。
將此Cookie重新新增到響應頭。
以下示例將向你展示如何刪除名為“first_name”的現有Cookie,並且當你下次執行main.jsp JSP時,它將為first_name返回null值。
示例
<html> <head> <title>Reading Cookies</title> </head> <body> <center> <h1>Reading Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with the this domain 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>
現在讓我們將上面的程式碼放在main.jsp檔案中並嘗試訪問它。它將顯示以下結果 -
輸出
Cookies Name and Value Deleted cookie : first_name Name : first_name, Value: John Name : last_name, Value: Player
現在再次執行 https://:8080/main.jsp ,它應該只顯示一個Cookie,如下所示 -
Found Cookies Name and Value Name : last_name, Value: Player
你可以在Internet Explorer中手動刪除Cookie。從“工具”選單開始並選擇“Internet選項”。要刪除所有Cookie,請單擊“刪除Cookie”按鈕。
廣告