Cookie技术

a)什么是Cookie?

1.Cookie翻译过来是饼干的意思。

2.Cookie是由服务器通知客户端,并由客户端保存键值对的一种技术。

它的构造器是:public Cookie(String name, String value) {}

3.只要客户端有Cookie,每次请求都会发送给服务器。

4.每个Cookie不能超过4kb的大小

b)如何创建Cookie

1、创建一个Cookie对象

2、调用response.addCookie( cookie );

Web阶段:第十六章:Cookie技术_Cookie技术

protected void createCookie(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 1、创建一个Cookie对象
Cookie cookie = new Cookie("key1", "value1");
Cookie cookie2 = new Cookie("key2", "value2");
// 2、调用response.addCookie( cookie );
response.addCookie(cookie);
response.addCookie(cookie2);
response.getWriter().write("创建了Cookie");
}

c)服务器如何获取Cookie

只需要调用reqeust.getCookies():Cookie[]

图解如何获取Cookie。

Web阶段:第十六章:Cookie技术_服务器_02

protected void getCookie(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 获取客户端发送过来的全部的Cookie对象
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie cookie : cookies) {
response.getWriter().write("收到客户端的Cookie:" + cookie.getName() + "====" + cookie.getValue() + "<br/>");
}
}
}

工具类

public class CookieUtils {
public static Cookie findCookie(String name,Cookie[] cookies) {
if (name==null || cookies == null || cookies.length == 0) {
return null;
}
for (Cookie cookie : cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
}
return null;
}
}

d)Cookie值的修改

第一套方案是:

1、你要new一个同名的Cookie对象。

2、在构造器中传入你要修改的新值。

3、调用response.addCookie()

//    1、你要new一个同名的Cookie对象。
// 2、在构造器中传入你要修改的新值。
Cookie cookie = new Cookie("key2", "newValue2");
// 3、调用response.addCookie()
response.addCookie(cookie);

第二套方案是:

1、你需要先查找到你要修改的Cookie对象

2、然后调用setValue方法设置新的值

3、最后调用response.addCookie();

//    1、你需要先查找到你要修改的Cookie对象
Cookie cookie = CookieUtils.findCookie("key1", request.getCookies());
if (cookie != null) {
// 2、然后调用setValue方法设置新的值
cookie.setValue("newValue1");
// 3、最后调用response.addCookie();
response.addCookie(cookie);
}

在谷歌浏览器中如何查看Cookie信息

Web阶段:第十六章:Cookie技术_服务器_03

在火狐 浏览器中如何查看 Cookie信息

Web阶段:第十六章:Cookie技术_服务器_04

e)Cookie生命控制

setMaxAge() 决定Cookie存活多久。

正数 在指定的秒数后过期。

零 表示马上删除Cookie

负数 表示浏览器关闭的时候,就删除Cookie(默认的情况)

protected void deleteNow(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = CookieUtils.findCookie("key2", request.getCookies());
if (cookie != null) {
cookie.setMaxAge(0);// 立即删除Cookie
response.addCookie(cookie);
}
response.getWriter().write("key2这个Cookie没了");
}

protected void life3600(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("key2", "value3600");
cookie.setMaxAge(60*60);//表示这个Cookie一个小时后被删除
response.addCookie(cookie);
response.getWriter().write("创建一个一小时后才会被删除的Cookie");
}

protected void defaultLife(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 创建出来的Cookie,maxAge默认值是-1,表示浏览器一关,Cookie就没了。
Cookie cookie = new Cookie("key1", "value1");
response.addCookie(cookie);
response.getWriter().write("默认创建出来的Cookie,浏览器一关就没了");
}

f)Cookie有效路径Path的设置

Cookie中有一个path属性,它可以有效的过滤哪些Cookie可以不用傻傻地发送给服务器。

当一个Cookie的path值为 /day14 表示请求地址是:​​http://ip​​:port/day14/* 那么Cookie就会发送给服务器

CookieA 的path=/day14

CookieB的path=/day14/abc

那么现在请求地址为:http://ip:port/day14/c.html

CookieA会发送给服务器

如果请求的地址为:http://ip:port/day14/abc/c.html

CookieA会发送给服务器

CookieB会发送给服务器

protected void pathTest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("key3", "pathtest");
cookie.setPath(request.getContextPath() + "/abc"); // 得到 /day14/abc
response.addCookie(cookie);
response.getWriter().write("我创建了一个有path的Cookie");
}

g)Cookie练习—免输入登录用户名

Web阶段:第十六章:Cookie技术_客户端_05

表单:

<body>
<form action="userServlet">
<input type="hidden" name="action" value="login"/>
<!--用户名:<input type="text" name="username" value=" <%=request.getCookies()[0].getValue() %>"/>-->
用户名:<input type="text" name="username" value="${ cookie.username.value }"/><br/>
密码:<input type="password" name="password" /><br/>
<input type="submit" />
</form>
</body>

服务器Sevlet代码:

protected void login(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");

if ("wzg168".equals(username) && "123456".equals(password)) {
// 登录成功
Cookie cookie = new Cookie("username", username);
cookie.setMaxAge(60*60*24*7);// 用户名保留 一个星期
//如果二次的请求不同,页面可能不会显示,所以有时需要cookie .setPath("你保存在客户端cookie的路径");
response.addCookie(cookie);
System.out.println("下次再来,我记住你啦");
} else {
// 登录失败
System.out.println("登录失败!");
}
}

如果二次的请求不同,cookie中的域名不要设置localhost,会出现获取不到的情况

Web阶段:第十六章:Cookie技术_服务器_06

这里以userid为例子,http://order.gmall.com:8086的,设置userId到cookie中

主要代码就一行:

//将userId保存到cookie中

CookieUtil.setCookie(request,response,“userId”,userLogin.getId(),606024,true);

Web阶段:第十六章:Cookie技术_Cookie技术_07

http://list.gmall.com:8083的,获取cookie中的userId

主要代码就一行:

//从cookie中获取userID

String userId = CookieUtil.getCookieValue(request, “userId”, true);

Web阶段:第十六章:Cookie技术_服务器_08

工具类:

package com.javawxid.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
* @param
* @return
*/
public class CookieUtil {


/***
* 获得cookie中的值,默认为主ip:www.gmall.com
* @param request
* @param cookieName
* @param isDecoder
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
Cookie[] cookies = request.getCookies();
if (cookies == null || cookieName == null){
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals(cookieName)) {
if (isDecoder) {//如果涉及中文
retValue = URLDecoder.decode(cookies[i].getValue(), "UTF-8");
} else {
retValue = cookies[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}


/***
* 设置cookie的值
* @param request
* @param response
* @param cookieName
* @param cookieValue
* @param cookieMaxage
* @param isEncode
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
try {
if (cookieValue == null) {
cookieValue = "";
} else if (isEncode) {
cookieValue = URLEncoder.encode(cookieValue, "utf-8");
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage >= 0)
cookie.setMaxAge(cookieMaxage);
if (null != request)// 设置域名的cookie
cookie.setDomain(getDomainName(request));
// 在域名的根路径下保存
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}


/***
* 获得cookie的主域名,本系统为gmall.com,保存时使用
* @param request
* @return
*/
private static final String getDomainName(HttpServletRequest request) {
String domainName = null;

String serverName = request.getRequestURL().toString();
if (serverName == null || serverName.equals("")) {
domainName = "";
} else {
serverName = serverName.toLowerCase();
serverName = serverName.substring(7);
final int end = serverName.indexOf("/");
serverName = serverName.substring(0, end);
final String[] domains = serverName.split("\\.");
int len = domains.length;
if (len > 3) {
// www.xxx.com.cn
domainName = domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
} else if (len <= 3 && len > 1) {
// xxx.com or xxx.cn
domainName = domains[len - 2] + "." + domains[len - 1];
} else {
domainName = serverName;
}
}

if (domainName != null && domainName.indexOf(":") > 0) {
String[] ary = domainName.split("\\:");
domainName = ary[0];
}
System.out.println("domainName = " + domainName);
return domainName;
}

/***
* 将cookie中的内容按照key删除
* @param request
* @param response
* @param cookieName
*/
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
setCookie(request, response, cookieName, null, 0, false);
}


}