web development (XI) Cookie and Its Applications

The concept 1.Cookie

1. The concept of session

In daily life, from phone call to hang up the phone between a series of course you ask me answer that one session.

Session Web application is similar to the process called life, it refers to a series of consecutive occurs between a client (browser) and the Web server's request and response process, for example, a user on a website the whole shopping process is a conversation.

On the phone, the two sides will talk conversations, also in the process of client and server interaction, it could create some data. In order to save the data generated during the session, the Servlet technology, a session object for the two data, namely Cookie and Session.
Here Insert Picture Description

The concept 2.Cookie

Cookie is a browser-side session techniques . He is create the server , and send to our customer's browser, the small amount of information stored on the browser.

When the browser access to the server again will carry the cookie information earlier. (Cookie information stored), the server obtains cookie, you will come to know which browser access. (Specific to a customer)

Cookie maximum save data as 4K, you can save more than 300 Cookie general browser, each site Xiacun about 20 Cookie.

3. pondering a question: web project which data can be stored in local storage to?

  • Request domain
  • ServletContext domain (web sharing the entire project)
  • mysql and other data stored in the database (if the user is logged in, you must keep to the library, the user is not logged)
  • txt file using io storage and so on ...
Why not use the ServletContext request and the data stored in it?

Here Insert Picture Description
Question: data added to the cart to save where more appropriate?

Technical Session: Cookie browser sessions and technical sessions on the Session server technology.

The implementation of the principle of 2.Cookie (focus)

Here Insert Picture Description
Here Insert Picture Description

3.Cookie的API(重点)

1.问题1: Cookie如何创建 (Cookie理解为一个Map<String,String>)

Cookie(String name, String value)  服务器中创建Cookie

2.问题2:Cookie中可以存放什么数据?

只能存储字符串.并且是以键值对的方式存储.(类似于Properties集合)

3.问题3:Cookie如何发送到浏览器?

HttpServletResponse类中方法:
void addCookie(Cookie cookie)  把cookie添加到response中,响应的时候就将cookie带到了浏览器上

4.问题4:Cookie保存在浏览器的哪个位置?
Here Insert Picture Description
5.问题5:服务器中如何获取Cookie?

HttpServletRequest类中有获取cookie的方法
Cookie[] getCookies()  request对象一次可以获取到所有的cookie信息.

6.Cookie对象的其他方法:

String getName()		获取cookie的key值
String getValue()		获取cookie的value值
void setMaxAge(int expiry)	设置cookie在浏览器的最大保存时间 单位是秒
void setPath(String uri)	设置路径,在哪个请求路径下会携带cookie.

setPath(“路径”),Path不一样的情况下,Cookie是可以重复的。当Path一样的情况下,Key值一样的,value就会被覆盖。

注意事项

  1. cookie的生存时间单位为:
  2. 要删除已经存在的cookie,后一个用来覆盖cookie必须名称与路径与原来的cookie一致

4.Cookie的入门案例

目标: 查看cookie的执行流程 (第一次请求没有,第一次响应服务器创建了cookie,浏览器保存cookie,第二次请求携带cookie,在服务器中可以获取到cookie信息)

需求: 创建一个Servlet,中创建一个Cookie,cookie保存信息name=tom , 当用户第二次访问的时候,将携带的cookie打印出来.
代码实现:
package com.ccc.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 目标: 创建Cookie携带到浏览器 ,第二次请求该Servlet,获取cookie信息,打印里面的内容
 *
 * 观察流程:  1.第一次请求中不会携带cookie
 *           2.第一次响应,响应头中会把cookie携带到浏览器   查看响应头  查看浏览器的cookie
 *           3.第二次请求, 请求头中是否有cookie?  会!
 *           4.看控制台是否打印cookie的value值
 */
//@WebServlet(urlPatterns = "/Demo1_Cookie")
//@WebServlet(value = "/Demo1_Cookie")
@WebServlet("/Demo1_Cookie")
public class Demo1_Cookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         * 步骤
         * 1.设置编码
         * 2.创建Cookie  Cookie(String String)
         * 3.给response中	addCookie(Cookie)
         *
         * 用户第二次访问:
         * 4.获取cookie    request.getCookies();  Cookie[]
         * 5.遍历循环cookie[]  通过ke值找到我们自己设置的cookie   getName() 获取key
         * 6.通过cookie对象的getValue() 获取具体的值并打印.
         */
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        Cookie cookie = new Cookie("name","jack");
        response.addCookie(cookie);

        //获取cookie
        Cookie[] cookies = request.getCookies();  //如果用户第一次过来,没有对象是null
        if(cookies !=null && cookies.length >0){
            for (Cookie c : cookies) {
                //如果cookie的key值为name , 找到了我们自己设置的cookie对象
                if("name".equals(c.getName())){
                    String value = c.getValue();
                    System.out.println(value);
                }
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

5.Cookie默认在浏览器上的存储时间是多久?

浏览器默认保存会话的时间当会话结束,cookie就销毁 (浏览器只要关闭,cookie就消失).

观察完京东,每次添加完购物车之后,即便是关闭浏览器,再次打开,cookie有效,购物车中的数据也有效。为什么会这样呢?因为京东对cookie的保存时间进行了设置.

需求: 将浏览器的cookie信息保存一个礼拜
/**
 * 目标: 设置cookie在浏览器的最大保存时间为7天
 * Cookie对象的方法setMaxAge()
 */
@WebServlet("/Demo2_Cookie")
public class Demo2_Cookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        Cookie cookie = new Cookie("name","jack");
        //设置cookie的最大保存时间 单位是秒
        cookie.setMaxAge(60*60*24*7);
        response.addCookie(cookie);

        //获取cookie
        Cookie[] cookies = request.getCookies();  //如果用户第一次过来,没有对象是null
        if(cookies !=null && cookies.length >0){
            for (Cookie c : cookies) {
                //如果cookie的key值为name , 找到了我们自己设置的cookie对象
                if("name".equals(c.getName())){
                    String value = c.getValue();
                    System.out.println(value);
                }
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

6.设置请求携带cookie的路径

void setPath(String uri) 设置路径,在哪个请求路径下会携带cookie

模拟:项目day13 创建cookie设置cookie信息,第二次请求的时候只要访问路径:localhost:8080/day13/Demo1Servlet ,就可以携带cookie

项目day14创建cookie设置cookie信息,第二次请求的时候只要访问路径:localhost:8080/day14/Demo1Servlet ,就可以携带cookie

同一个项目如果设置了setPath, 那么在浏览器每次请求的时候,cookie只携带自己项目下的cookie,不会携带别的cookie.

案例演示: day13如果设置了setPath("/day13") ,那么浏览器请求他的时候只携带自己cookie,day14如果这时也设置了path,那么它每次也携带自己的path
Day13项目的
package com.ccc.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 目标: 设置cookie在浏览器的最大保存时间为7天
 * Cookie对象的方法setMaxAge()
 */
@WebServlet("/Demo3_Cookie")
public class Demo3_Cookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        Cookie cookie = new Cookie("name","jack");
        //设置cookie的最大保存时间 单位是秒
        cookie.setMaxAge(60*60*24*7);
        //设置path 请求路径中包含path 就会携带cookie
        cookie.setPath("/day13");
        response.addCookie(cookie);

        //获取cookie
        Cookie[] cookies = request.getCookies();  //如果用户第一次过来,没有对象是null
        if(cookies !=null && cookies.length >0){
            for (Cookie c : cookies) {
                //如果cookie的key值为name , 找到了我们自己设置的cookie对象
                if("name".equals(c.getName())){
                    String value = c.getValue();
                    System.out.println(value);
                }
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
Day14项目的
package com.ccc.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 目标: 设置cookie在浏览器的最大保存时间为7天
 * Cookie对象的方法setMaxAge()
 *
 */
@WebServlet("/Demo3_Cookie")
public class Demo3_Cookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        Cookie cookie = new Cookie("name","rose");
        //设置cookie的最大保存时间 单位是秒
        cookie.setMaxAge(60*60*24*7);
        cookie.setPath("/day14");
        response.addCookie(cookie);

        //获取cookie
        Cookie[] cookies = request.getCookies();  //如果用户第一次过来,没有对象是null
        if(cookies !=null && cookies.length >0){
            for (Cookie c : cookies) {
                //如果cookie的key值为name , 找到了我们自己设置的cookie对象
                if("name".equals(c.getName())){
                    String value = c.getValue();
                    System.out.println(value);
                }
            }
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

7.Cookie 能够在程序中销毁(本质是被覆盖了)

实现步骤:

1.创建一个名称(key)一样的cookie,value值可以任意,建议使用空字符串

2.设置新创建的cookie的最大有效时间为0

3.设置新创建的cookie的path为本项目的

4.将新创建的cookie添加到response中,发送给浏览器(浏览器会自动的销毁)

需求:

目标是删除day14路径下的cookie (name=rose)的该cookie.

代码实现

/**

 需求:
 目标是删除day14路径下的cookie (name=rose)的该cookie.

 */
@WebServlet("/Demo4_DeleteCookie")
public class Demo4_DeleteCookie extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /**
         实现步骤:
         1.创建一个名称(key)一样的cookie,value值可以任意,建议使用空字符串
         2.设置新创建的cookie的最大有效时间为0
         3.设置新创建的cookie的path为本项目的
         4.将新创建的cookie添加到response中,发送给浏览器(浏览器会自动的销毁)
         */
        Cookie cookie = new Cookie("name","");
        cookie.setMaxAge(0);
        cookie.setPath("/day14");
        response.addCookie(cookie);
        System.out.println("day14的cookie的name为rose的cookie已经删除完毕");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}

8.案例- 记录上一次访问的时间 (重点)

Requirements: If the user is the first visit CookieServlet, print the browser is your first visit if the user is not the first visit, give the browser print your last visit was on xxxx.
Address: HTTPS: / /blog.csdn.net/qq_45083975/article/details/92965972

Guess you like

Origin blog.csdn.net/qq_45083975/article/details/92854973