要读取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_name cookie设置为“ John”,将last_name cookie设置为“ Player”,则运行 http:// localhost:8080 / main.jsp 将显示以下结果-
输出结果
Found Cookies Name and Value Name : first_name, Value: John Name : last_name, Value: Player