js / java get, add, modify, delete cookie (and most complete)

A, cookie Introduction

1.cookie true colors

  HTTP protocol itself is stateless. What it is stateless, that server can not determine the user's identity. Cookie is actually a short text message (key-value format). The client initiates a request to the server, if users need to record the state, issued a response on the use of Cookie to the client browser. Cookie client browser will be saved. When a browser requests that site again, the browser URL along with the request submitted with the Cookie to the server. The server checks the Cookie, in order to identify user state.

Originally operating mechanism 2.cookie

  When the user first visits a site and log in, cookie settings and will send through the following four steps:

  The client sends a request to the server - "server sends a response to the client HttpResponse, which comprises a Set-Cookie header -" Cookie stored client, after sending the request to the server, the request will include the HttpRequest of a Cookie head - "the server returns the response data.

3.cookie attributes and values

 

  name-cookie name (name is case-sensitive)

  Value- string values ​​stored in a cookie, and when the value Chinese, url must be encoded.

  Max-Age / Expires-cookie Validity (default: -1)
  This property is used to set the validity Cookie. Cookie in maxAge attribute used to indicate the seconds.

  In js, the cookie expiration time set by the Expires;

  In java by getMaxAge () and setMaxAge (int maxAge) Max-Age attribute to read and write.

  maxAge There are three values, namely a positive, negative, and 0.

  If maxAge attribute is positive, it indicates that the Cookie will automatically expire after maxAge seconds. Browser will maxAge Cookie is a positive number of persistence, i.e. the file is written to the corresponding Cookie (position of each browser stores inconsistent). Whether a customer closes the browser or computer, as long as before still maxAge seconds, visit the website of the Cookie is still valid.

  When maxAge attribute is negative, it indicates that the Cookie Cookie is a temporary, not persisted, valid only in this sub-window or the browser window of the present window is open, the Cookie fail immediately after the browser is closed.

  When maxAge is 0, the delete Cookie immediately.

  Domain-cookie domain (default: current domain URL)

  Cookie is not cross-domain, privacy, security mechanism prevents the site from illegally obtaining Cookie other sites.

  Normally, two second-level domain of a domain is the same cookies can not be used interchangeably, and such test1.mcrwayfun.com test2.mcrwayfun.com, because the two are not identical domains. If you want to mcrwayfun.com second-level domain name can use the Cookie, Cookie parameters need to set the domain is .mcrwayfun.com, so use test1.mcrwayfun.com and test2.mcrwayfun.com will be able to access the same cookie.  

  Level domain, also known as top-level domain, generally by the string + suffix. The domain name has a familiar baidu.com, qq.com. com, cn, net and so is a common suffix.
  Secondary domain is derived in a domain, such as domain names have a mcrfun.com, and the blog.mcrfun.com www.mcrfun.com which are derived from the secondary domain.

  path- represent the cookie affect the path, with the browser will send the cookie path matches the specified domain under this configuration. (Default: Only valid request in the current path and a sub path)

  HttpOnly- tells the browser does not allow script to change this value by document.cookie, can not get through the document.cookie the cookie. (Default: false), may be provided by the server, the front end can not be set.

But Zhang http request will still carry this cookie. Note that this value can not be obtained though in the script, but still exists in the form of a file in the browser installation directory. This setting is usually set on the server side. You can also view through the browser's developer tools.

  secure- safety signs, after the specified only be sent to the server using SSL link when the link is http if it is not delivered this information. Even setting up secure property also does not mean that others can not see your machine locally stored cookie information, so do not put a cookie on important information to the server-side settings. (Default value: false)

Two, js get, add, modify, delete cookie

  Preparation: open the browser, just visit a web page, f12 open the web debug tool.

1. Obtain cookie

  Get All cookie

var cookies = document.cookie;  

  Example: Enter document.cookie console -> ENTER -> output is the site of all the cookie information.

  Gets the specified cookie (before optimization)

var cookieName = "cookie名称";
var cookieValue = document.cookie.match(new RegExp("(^| )" + cookieName + "=([^;]*)(;|$)"))[2];

  Example: Gets the value of the cookie _ga.

   Gets the specified cookie (optimized)

var cookieName = "cookie name"; 
var cookieValue = ""; 
the try { 
    cookieValue = document.cookie.match (new new the RegExp ( "(^ |)" + the cookieName + "= ([^;] *) (; | $) ")) [2]; 
} the catch (E) {// the caught exception object is to make the following code continues to execute; because when looking for cookie does not exist, the line of code error. 
    = null cookieValue; 
}; 

2. Add cookie

  2.1 format:

  document.cookie = "cookie = cookie name value; expires = expiration time; path = / path has access to the cookie; domain = domain; secure = true / false;";

  2.2 add only cookie, do not set the property.

  For example: Enter the console document.cookie = "username = Marydon;"; -> Enter

  2.3 Add cookie, setting the access path

  Example: Add cookie on this page

  Step 1: Check the access path of the current page

  http: // localhost: 8080 / zz / weixin / about.do, access path is: /zz/weixin/about.do, in order to take effect only on the current page in the cookie, you will need to be set to the full path of the page access path.

  Step two: Enter the console document.cookie = "username = Marydon; path = / zz / weixin / about.do"; -> Enter;

  第三步:刷新当前页面cookie-->cookie已经添加成功-->cookie的路径已经设置好。 

  2.4探究一:添加cookie,不设置path属性与添加cookie,设置path属性的区别

  先看看添加cookie,不设置path属性de默认path的值

  添加成功后,你会发现:当不设置path属性时,cookie的默认路径为该页面请求路径的上级目录,即:/zz/weixin,

  表示的是:所有页面路径在/zz/weixin/*下都可获取到该cookie值。

  小结:

  也就是说:未设置path属性时,并不是只有当前页面可以访问得到,和它同级的访问路径(/zz/weixin/about2.do)都可以访问得到。

  添加cookie,设置path属性时,path的路径可以随意设置,既可以设置仅仅本页面有效,也可以设置其它页面有效。

  2.5探究二:添加cookie,必须设置path属性的情景

  在A页面添加cookie,供B页面使用,而A、B两个页面又不是同级目录(不是磁盘目录而是通过浏览器访问该页面时的请求路径)时,必须将path属性设置为B页面的访问路径。

  两个页面虽然同在同一目录,但是通过浏览器并不是直接访问该页面,而是通过服务器转发到对应页面。

  about.jsp的访问路径为:http://localhost:8080/zz/weixin/about.do

  about2.jsp的访问路径为:http://localhost:8080/zz/weixin2/about.do

  访问A页面,添加cookie,不设置path属性;

  此时,username的可访问路径为/zz/weixin,只有/zz/weixin/*路径下可访问到该cookie。

  访问B页面,未找到cookie:username。

  在A页面控制台添加path,设置为:/zz/weixin2/about.do

  添加成功,刷新A页面的cookie,该cookie并未添加到该页面,说明逻辑没有错误,这才是合理情况。

  再次来到B页面,刷新cookie,username添加成功。 

  这就是解决两个完全不同访问路径下,能够实现cookie传递的本质。 

  2.6探究三:添加cookie,不设置path属性

  此时,和它同级的访问路径(/zz/weixin/about2.do)都可以访问得到,下面来证实一下。

  没有添加path属性

  按照道理来讲,/zz/weixin/aa.do该页面是可以访问得到该cookie的。

  没有问题,结论正确。 

  2.7添加cookie, 设置有效期。

  举例:1分钟之后过期。

// 1分钟之内有效
var oDate = new Date();
oDate.setMilliseconds(oDate.getMilliseconds() + 1*60*1000);
var time = oDate.toUTCString();
/*添加cookie,设置有效期*/document.cookie = "username=Marydon;expires=" + time + ";";

  添加成功后,刷新cookie,设置成功。

   一分钟后,再次刷新cookie。

  username的cookie已经消失。 

3.修改、删除cookie

  3.1修改cookie;

  和添加cookie的方法一致,直接赋值即可。

  格式:document.cookie = "cookie名称=cookie值;expires=过期时间;path=/可以访问到该cookie的路径;domain=网站域名;secure=true/false;";

  举例1:没有设置path和domain(path和domain都采用默认值)

  修改前

  修改后,document.cookie="username=Mary"

  举例2: 设置path(path没有采用默认值)

  修改前,path=/zz/index.jsp

  修改后,document.cookie="username=Marydon;path=/zz/index.jsp"

  注意:

  第一点,cookie区分大小写,如果大小写不一致就变成了添加而不是修改;

  第二点,如果设置了path或domain,则也需要保持一致,否则,也会变成添加而不是修改。

  3.2删除cookie。

  cookie没有提供删除的方法,但是我们可以曲线救国。

  方法一:将cookie的值清空。

  正确方式:

documen.cookie="username=";//默认path和domain

  错误方式一: document.cookie="username=null";

    

  错误方式二:document.cookie="username=''";

  cookie的值只有一种表现形式:字符串。这两种方式都是犯了同样的错误,不管你设置成什么,表现形式都只是字符串。

  按照正确方式清空cookie后,该cookie的返回值为""。

  方法二:设置cookie过期。

  让cookie立马过期,本质就是立马删除这个cookie。只需要将指定cookie的过期时间设置为当前时间之前即可。

var cookieName = "username";
// 将指定cookie的过期时间设置为当前时间之前
var expires=new Date();
expires.setTime(expires.getTime()-1);
document.cookie= cookieName + "=;expires=" + expires.toGMTString();

  将以上代码拷贝到控制台,运行,删除成功。

三、java  获取、添加、修改、删除cookie

导包:

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;  

1.获取cookie

  方式一:获取cookie对象

/**
 * 获取cookie对象
 * @param cookieName cookie名称
 * @return cookie对象
 */
public Cookie getCookie(String cookieName) {
    // 这里需要获取request对象TODO
    HttpServletRequest request = null;
    // 获取所有的cookie
    Cookie[] array = request.getCookies();
    if (array != null) {
        for (Cookie cookie : array) {
            if (cookieName.equals(cookie.getName())) {
                return cookie;
            }
        }
    }
    return null;
}

  方式二:获取cookie值

/**
 * 获取cookie对应的值
 * @param cookieName cookie名称
 * @return cookie对应的值
 */
public String getCookieValue(String cookieName) {
    // 这里需要获取request对象TODO
    HttpServletRequest request = null;
    // 获取所有的cookie
    Cookie[] array = request.getCookies();
    if (array != null) {
        for (Cookie cookie : array) {
            if (cookieName.equals(cookie.getName())) {
                // 中文需要编码,所以这里需要解码
                return AESEncryptUtil.decrypt(cookie.getValue());
            }
        }
    }
    return "";
}

2.添加cookie

/**
 * 添加cookie
 * @param cookieName cookie名
 * @param cookieValue cookie值
 * @param maxAge 有效期,单位:秒
 *  不设置,传0,默认为:session会话关闭时,cookie失效,即关闭浏览器
 * @param path 可访问该cookie的路径
 *  不设置,传"",默认为:当前请求de路径   
 */
public void addCookie(String cookieName, String cookieValue, int maxAge, String path) {
    // 这里需要获取request对象TODO
    HttpServletRequest request = null;
    HttpServletResponse response = null;
    // 创建cookie
    Cookie cookie = new Cookie(cookieName, cookieValue);
    // 默认为:session会话关闭失效,即关闭浏览器
    if (0 != maxAge) {
        cookie.setMaxAge(maxAge);
    }
    //默认为:当前请求de路径
    if (!"".equals(path)) {
        // 项目根路径
        String webAppPath = request.getContextPath();
        // 判断即将设置的路径是否以本项目的上下文开头
        //(不加项目头,则该cookie的可访问路径将脱离项目,也就是说在项目内永远无法访问到它。)
        if (!path.startsWith(webAppPath)) {
            path = "/".equals(webAppPath) ? webAppPath + path : webAppPath + "/" + path;
        }
        cookie.setPath(path);
    }
    response.addCookie(cookie);
}

3.修改cookie

/**
 * 修改cookie
 * @param cookieName cookie名
 * @param cookieValue cookie值
 * @param maxAge 有效期,单位:秒
 *  不设置,传0,默认为:session会话关闭时,cookie失效,即关闭浏览器(如果想要删除,调delCookie())
 *  禁止传path参数,因为传的话,还要限制最终结果是实现了修改而不是添加(路径不同,将导致新增一个cookie)
 */
public void updateCookie(String cookieName, String cookieValue, int maxAge) {
    // 这里需要获取request对象TODO
    HttpServletRequest request = null;
    HttpServletResponse response = null;
    Cookie[] array = request.getCookies();
    if (array != null) {
        for (Cookie cookie : array) {
            if (cookieName.equals(cookie.getName())) {
                if (0 != maxAge) {
                    cookie.setMaxAge(maxAge);
                }
                // 只有获取该cookie所在路径,才能实现对应的修改
                cookie.setPath(cookie.getPath());
                response.addCookie(cookie);
            }
            break;
        }
    }
}

4.删除cookie

  方式一:删除客户端指定cookie

/**
 * 清除客户端指定cookie
 * @param cookieName 要删除的cookie的名称
 */
public void delCookie(String cookieName) {
    // 这里需要获取request对象TODO
    HttpServletRequest request = null;
    HttpServletResponse response = null;
    Cookie[] array = request.getCookies();
    if (array != null) {
        for (Cookie cookie : array) {
            if (cookieName.equals(cookie.getName())) {
                // 当maxAge为0时,表示立即删除Cookie。
                cookie.setMaxAge(0);
                // 只有获取该cookie所在路径,才能实现对应的删除
                cookie.setPath(cookie.getPath());
                response.addCookie(cookie);
            }
            break;
        }
    }
}  

  方式二:删除客户端所有的cookie

/**
 * 清除客户端所有的cookie
 */
public void clear() {
    // 这里需要获取request对象TODO
    HttpServletRequest request = null;
    HttpServletResponse response = null;
    Cookie[] array = request.getCookies();
    if (array != null) {
        for (Cookie cookie : array) {
            // 当maxAge为0时,表示立即删除Cookie。
            cookie.setMaxAge(0);
            // 只有获取该cookie所在路径,才能实现对应的删除
            cookie.setPath(cookie.getPath());
            response.addCookie(cookie);
        }
    }
}

  

写在最后

  哪位大佬如若发现文章存在纰漏之处或需要补充更多内容,欢迎留言!!!

 相关推荐:

 

Guess you like

Origin www.cnblogs.com/Marydon20170307/p/11978930.html