原创
Cooike对象是由服务器产生并保存到客户端(内存或文件中)的信息。
对于Cookie对象的使用,一般需要两步操作。首先由服务器创建Cookie对象保存到客户端,然后在JSP页面或者Servlet中读取Cookie并进行处理。
Cookie的相关方法
方法 | 说明 |
Cookie(String name,String value) | 构造函数,创建一个Cookie对象 |
void response.addCookie(Cookie c) | 向客户机添加一个Cookie对象 |
Cookie request.getCookies() | 用于取得所有Cookie对象的数据,存放到一个数组中 |
String getName() | 取得Cookie对象的属性名 |
String getValue() | 取得Cookie对象的属性对应的属性值 |
setMaxAge(int expiry) | 设置cookie有效时间,以秒为单位,设置了有效时间的cookie将以文件形式保存在客户端,否则只是存储在浏览器的内存区域中 |
String name="zhangsan"; Cookie c=new Cookie("user",name); //创建Cookie对象,对象名为user而不是c response.add(c); //将Cookie对象添加到响应中,保存到客户端
Cookie cookie[]=request.getCookies(); //获得客户端所有的Cookie对象 for(int i=0;i<cookie.length;i++){ if(cookie[i].getName().equals("user"){ out.print(cookie[i].getValue()); } }
在一个JSP页面中创建Cookie对象保存到客户端
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'cookie1.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% Cookie c1=new Cookie("name","zhangsan"); c1.setMaxAge(60*60); response.addCookie(c1); Cookie c2=new Cookie("user","lisi"); c2.setMaxAge(60*60); response.addCookie(c2); Cookie c3=new Cookie("account","zhaowu"); c3.setMaxAge(60*60); response.addCookie(c3); %> </body> </html>
无需跳转则可以在另一个JSP页面获取Cookie对象的值
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'cookie2.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <% Cookie cookie[]=request.getCookies(); if(cookie!=null){ out.print(cookie.length); System.out.println(); for(int i=0;i<cookie.length;i++){ out.print(cookie[i].getValue()); System.out.println(); } }else{ out.print("no exist cookie"); } %> </body> </html>
22:00:06
2018-11-16