<% Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name",request.getParameter("last_name")); // cookie expire: 24 hours firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); response.addCookie( firstName ); response.addCookie( lastName ); %> <html> <head> <title>Setting Cookies</title> </head> <body> <center> <h1>Setting Cookies</h1> </center> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first_name")%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter("last_name")%> </p></li> </ul> </body> </html>
浏览器里打开该jsp:http://localhost:9032/jerryjsp/main.jsp?first_name=Jerry&last_name=Wang
可以在Chrome开发者工具Application标签页的Cookies区域查看到上述Java代码在响应结构里设置的Cookie.
Cookie的读取
新建一个jsp文件,源代码如下:
<html> <head> <title>Reading Cookies</title> </head> <body> <center> <h1>Reading Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; 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>
浏览器打开,可以读取出之前设置的cookie:
这个服务器端读取到的Cookie是浏览器端发送给服务器并在服务器端解析的:
我有话说: