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

Cách đọc cookie với JSP

Để đọc cookie, tạo mảng đối tượng javax.servlet.http.Cookie bằng cách gọi getCookies() của HttpServletRequest. Duyệt mảng, dùng getName() và getValue() để truy xuất từng cookie.

Ví dụ

Đọc cookie đã set ở ví dụ trước:

<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];
          out.print("Name : " + cookie.getName() + ", ");
          out.print("Value: " + cookie.getValue() + " <br/>");
        }
      } else {
        out.println("<h2>No cookies founds</h2>");
      }
    %>
  </body>
</html>

Đặt code vào main.jsp. Nếu set first_name cookie = "John" và last_name cookie = "Player", chạy https://localhost:8080/main.jsp cho kết quả:

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