如何用 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP