Cookie是一小段的文本信息,客户端请求服务器,如果服务器需要记录该用户状态,就使用response向客户端浏览器颁发一个Cookie.
客户端浏览器会把Cookie保存起来.当浏览器再请求该网站时,浏览器把请求的网址连同该Cookie一同提交给服务器.
服务器检查该Cookie,以此来辨认用户状态.服务器还可以根据需要修改Cookie的内容.
查看某个网站颁发的Cookie很简单:
javascript:alert(document.cookie)
二、练习
Cookie.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" errorPage="login.jsp" %> <%@ page import="javax.servlet.http.*"%> <% request.setCharacterEncoding("UTF-8"); //设置request编码 String username = ""; //用户名 int visitTimes = 0; //访问次数 Cookie[] cookies = request.getCookies(); //所有的Cookie for(int i=0; cookies!=null&&i<cookies.length;i++){ //遍历Cookie寻找账号与登录次数 Cookie cookie = cookies[i]; //第i个Cookie if("username".equals(cookie.getName())){ //如果Cookie名为Username System.out.println(cookie.getValue()); username = cookie.getValue(); //则记录该Cookie的内容 }else if("visitTimes".equals(cookie.getName())){ //如果Cookie名为visitTimes visitTimes = Integer.parseInt(cookie.getValue()); //则记录Cookie的内容 } } if(username == null || username.trim().equals("")){ //如果没有找到用户名,则转到登录界面 throw new Exception("您还没有登录,请先登录."); } //修改Cookie,更新用户的访问次数 Cookie visitTimesCookie = new Cookie("visitTimes",Integer.toString(++visitTimes)); response.addCookie(visitTimesCookie); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>cookie.jsp</title> </head> <body> <div align="center" style="margin:10px;"> <fieldset> <legend>登录信息</legend> <form action="login.jsp" method="post"> <table> <tr> <td>您的账号:</td> <td><%= username%></td> </tr> <tr> <td>登陆次数:</td> <td><%= visitTimes%></td> </tr> <tr> <td></td> <td> <input type="button" value="刷新" onclick="location='<%= request.getRequestURI() %>?ts=' + new Date().getTime();" class="button"> </td> </tr> </table> </form> </fieldset> </div> </body> </html>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isErrorPage="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <% request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); if("POST".equals(request.getMethod())){ Cookie usernameCookie = new Cookie("username",request.getParameter("username")); //Cookie visittimesCookie = new Cookie("visitTimes","0"); response.addCookie(usernameCookie); //response.addCookie(visittimesCookie); //System.out.println(visittimesCookie.getValue()); response.sendRedirect(request.getContextPath() + "/cookie.jsp"); return; } %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>login.jsp</title> </head> <body> <div align="center" style="margin:10px;"> <fieldset> <legend>登录</legend> <form action="login.jsp" method="POST"> <table> <tr> <td></td> <td> <span style="color:red; "> <%= exception.getMessage() %> </span> </td> </tr> <tr> <td>账号:</td> <td> <input type="text" name="username" style="width:200px; "> </td> </tr> <tr> <td>密码:</td> <td> <input type="password" name="password" style="width:200px; "> </td> </tr> <tr> <td></td> <td> <input type="submit" value="登录" class="button"> </td> </tr> </table> </form> </fieldset> </div> </body> </html>
三、Cookie的不可跨域名性
Cookie具有不可跨域名性.根据Cookie规范,浏览器访问某个网站只会携带该网站的Cookie,而不会携带别的网站的Cookie.
需要注意的是:虽然网站images.google.com和www.google.com同属于Google,但是域名不一样,二者同样不能互相操作彼此的Cookie.
四、Unicode编码:保存中文
中文与英文字符不同,中文属于Unicode字符,在内存中占4个字符,而英文属于ASCII字符,内存中占2个字节.
Cookie中使用Unicode字符时需要对Unicode字符进行编码,否则会乱码.
编码可以使用java.net.URLEncoder类的 encode(String str,String encoding)方法.
解码使用java.net.URLDecoder类的decode(String str,String encoding)方法.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="java.net.URLDecoder"%> <%@page import="java.net.URLEncoder"%> <% //使用中文的Cookie. name与value都使用UTF-8编码 Cookie cookie = new Cookie(URLEncoder.encode("姓名","UTF-8"), URLEncoder.encode("刘京华","UTF-8")); response.addCookie(cookie); //发送到客户端 %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Cookie Encoding</title> </head> <body> <% Cookie[] cookie1 = request.getCookies(); if(cookie1 != null){ for(Cookie cc : cookie1){ String cookieName = URLDecoder.decode(cc.getName(),"UTF-8"); String cookieValue = URLDecoder.decode(cc.getValue(),"UTF-8"); out.println(cookieName + "=" + cookieValue + "; <br/>"); } }else{ out.println("Cookie 已经写入客户端.请刷新页面."); } %> </body> </html>