Introduction and use of cookies

 
 

Cookie has always been a snack eaten with milk. Within the Internet, however, the word "cookie" has a completely different meaning. So what exactly are "cookies"? A "cookie" is a small amount of information sent by a web server to be stored on a web browser so that the next time the unique visitor returns to the web server, this information can be read back from the browser. This is useful to let the browser remember specific information about this visitor, such as last visited location, time spent, or user preferences (such as style sheets). A cookie is a text file stored in the browser's directory, in RAM when the browser is running. Cookies may also be stored on your computer's hard drive once you log out of the website or web server. All cookies are terminated when a visitor ends their browser session.

Cookie Features

Cookie memory size is limited

null IE 6.0 IE 7.0 8.0 Opera Fire Fox Safari Chrome
Number of cookies 20 under each domain name 50 under each domain name 30 per domain name 50 per domain name no limit 53 per domain name
Cookie size 4095 bytes 4095 bytes 4096 bytes 4097 bytes 4097 bytes 4097 bytes

Cookies have a life cycle

    The cookie can keep the login information to the user's next session with the server. In other words, the next time the user visits the same website, the user will find that he has logged in without entering the user name and password (of course, it is not excluded that the user manually deletes the cookie). And some cookies are deleted when the user exits the session, which can effectively protect personal privacy.

    When a cookie is generated, an Expire value is specified, which is the life cycle of the cookie. During this cycle, the cookie is valid, and the cookie that exceeds the cycle will be cleared. Some pages set the lifetime of cookies to "0" or a negative value, so that when the browser is closed, the cookies will be cleared immediately, user information will not be recorded, and it is more secure.

Cookies satisfy the same-origin policy

Although the website images.google.com and the website www.google.com belong to Google, but the domain names are different, the two cannot operate each other's cookies.

    Here comes the question, for example:

    Do I need to re-login to my Baidu account when I visit playzhidao.baidu.com and then visit wenku.baidu.com?

    Solution: set document.domain = 'baidu.com';    

Let the page belong to this base domain name (then this page and any second-level domain name is baidu.com)

Add, delete, modify and check functions that encapsulate your own cookies

/*
    2017/02/20
    cookie manipulation
 */function setCookie(key, value, iDay) {
    var oDate = new Date();
    oDate.setDate(oDate.getDate() + iDay);
    document.cookie = key + '=' + value + ';expires=' + oDate;

}function removeCookie(key) {
    setCookie(key, '', -1);//You only need to return the Cookie shelf life to one day to delete it}function getCookie(key) {
    var cookieArr = document.cookie.split('; ');    for(var i = 0; i < cookieArr.length; i++) {        var arr = cookieArr[i].split('=');        if(arr[0] === key) {            return arr[1];
        }
    }    return false;
}

SpringMVC与Cookie

The role of @CookieValue

Used to get the value in the cookie

@RequestMapping("/testCookie")
public String testCookie(@CookieValue(value="name",required=false) String name,
        @CookieValue(value="age",required=false) Integer age){
    System.out.println(name+","+age);
    return "hello";
}

Manipulate cookies through Request

/**  
         * read all cookies  
         * Note 2. When the cookie is read from the client, other attributes including maxAge are unreadable and will not be submitted. When a browser submits a cookie, it only submits the name and value attributes. The maxAge attribute is only used by browsers to determine whether a cookie has expired  
         * @param request  
         * @param response  
         */  
        @RequestMapping("/showCookies")  
        public void showCookies(HttpServletRequest request,HttpServletResponse response ){  
               
            Cookie[] cookies = request.getCookies();//This way you can get an array of cookies  
            if (null==cookies) {  
                System.out.println("没有cookie=========");  
            } else {  
                for(Cookie cookie : cookies){  
                    System.out.println("name:"+cookie.getName()+",value:"+ cookie.getValue());  
                }  
            }  
               
        }  
        /**  
         * add cookies  
         * @param response  
         * @param name  
         * @param value  
         */  
        @RequestMapping("/addCookie")  
        public void addCookie(HttpServletResponse response,String name,String value){  
            Cookie cookie = new Cookie(name.trim(), value.trim());  
            cookie.setMaxAge(30 * 60);// set to 30min  
            cookie.setPath("/");  
            System.out.println("Added ==============");  
            response.addCookie(cookie);  
        }  
        /**  
         * Modify cookies  
         * @param request  
         * @param response  
         * @param name  
         * @param value  
         * Note 1. When modifying or deleting a cookie, all attributes of the newly created cookie except value and maxAge, such as name, path, domain, etc., must be exactly the same as the original cookie. Otherwise, the browser will consider that two different cookies will not be covered, resulting in the failure of modification and deletion.  
         */  
        @RequestMapping("/editCookie")  
        public void editCookie(HttpServletRequest request,HttpServletResponse response,String name,String value){  
            Cookie[] cookies = request.getCookies();  
            if (null==cookies) {  
                System.out.println("没有cookie==============");  
            } else {  
                for(Cookie cookie : cookies){  
                    if(cookie.getName().equals(name)){  
                        System.out.println("Original value: "+cookie.getValue());  
                        cookie.setValue(value);  
                        cookie.setPath("/");  
                        cookie.setMaxAge(30 * 60);// set to 30min  
                        System.out.println("The modified cookie name is: "+cookie.getName()+", the new value is: "+cookie.getValue());  
                        response.addCookie(cookie);  
                        break;  
                    }  
                }  
            }  
               
        }  
        /**  
         * delete cookies  
         * @param request  
         * @param response  
         * @param name  
         */  
        @RequestMapping("/delCookie")  
        public void delCookie(HttpServletRequest request,HttpServletResponse response,String name){  
            Cookie[] cookies = request.getCookies();  
            if (null==cookies) {  
                System.out.println("没有cookie==============");  
            } else {  
                for(Cookie cookie : cookies){  
                    if(cookie.getName().equals(name)){  
                        cookie.setValue(null);  
                        cookie.setMaxAge(0);// Immediately destroy the cookie  
                        cookie.setPath("/");  
                        System.out.println("The deleted cookie name is: "+cookie.getName());  
                        response.addCookie(cookie);  
                        break;  
                    }  
                }  
            }  
        }




View the original text: http://www.coder306.cn/?p=176

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324745035&siteId=291194637