如何使用JSP读取cookie?
要读取cookie,您需要通过调用HttpServletRequest的getCookies()方法来创建一个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;
//获取与此域名关联的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>现在让我们将上面的代码放在main.jsp文件中,然后尝试访问它。如果将first_namecookie设置为“John”,将last_namecookie设置为“Player”,则运行 http://localhost:8080/main.jsp 将显示以下结果-
输出结果
Found Cookies Name and Value Name : first_name, Value: John Name : last_name, Value: Player
热门推荐
1 狗狗下楼训练
3 狗狗训练头盔
6 狗狗训练机构
7 训练狗狗步骤
9 狗狗能训练
10 狗狗基本动作训练方法
11 怎么训练狗狗叼饭盆
12 狗狗一岁了还能训练吗
13 训练狗狗的
14 宁波狗狗训练
15 训练狗狗拉屎
16 教狗狗训练
17 狗狗要怎么训练上厕所
18 狗狗靠的训练