如何用 JSP 讀取 cookie?
要讀取 cookie,您需要透過呼叫 getCookies( ) HttpServletRequest 的方法來建立一個 javax.servlet.http.Cookie 物件的陣列。然後遍歷陣列,並使用 getName() 和 getValue() 方法來訪問每個 cookie 及其關聯的值。
我們現在來讀取上一個示例中設定的 cookie −
示例
<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]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } } else { out.println("<h2>No cookies founds</h2>"); } %> </body> </html>
現在讓我們將上述程式碼放入 **main.jsp **檔案中並嘗試訪問它。如果您將 first_name cookie 設為"John",將 last_name cookie 設為"Player",則執行 https://:8080/main.jsp 將顯示以下結果 −
輸出
Found Cookies Name and Value Name : first_name, Value: John Name : last_name, Value: Player
廣告