JSP和Servlet里的Cookie处理

作者阿里云代理 文章分类 分类:windows图文教程 阅读次数 已被围观 1316
<%   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

image.png

可以在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:

image.png

这个服务器端读取到的Cookie是浏览器端发送给服务器并在服务器端解析的:

image.png

 

本公司销售:阿里云新/老客户,只要购买阿里云,即可享受折上折优惠!>

我有话说: