Day05JavaWeb【Cookie and Session】Cookie read this one is enough! ***

learning target

Talk about Cookie first, then Session?
Cookie and Session are session-based sessions based on Cookie technology.
Target list
1.
Be able to tell the concept of session 2. Be able to tell the concept of cookie
3. Be able to create, send, receive and delete cookies
4. Be able to tell the principle of cookie execution
5. Can tell the concept of session
6. Can get session object, add, delete, and get data in session

Introduction to the conversation

  • (1) What is
    the process of a series of requests and responses between the browser and the server?
    Session start: open the browser-visit Jingdong
    Session end: close the browser
  • (2) Data generated by the session
    During the interaction between the client and the server, some data will also be generated. In order to save the data generated during the session, in Servlet technology, two objects for saving session data are provided, namely Cookie and Session
  • (3) The essence is the technology of accessing data in the browser or server

Overview of cookies

  • (1) What is Cookie
    Cookie technology is to access session data on the browser side
  • (2) What are the characteristics of cookies?
    The data is in the form of key-value name=jack
    data has survival time and can be modified.
    Some special symbols cannot be recognized, so this symbol needs to be transcoded
1)Cookie的创建
Cookie(String name, String value) 创建cookie对象
String getName()获取cookie的名称
String getValue() 获取cookie的值
(2)将cookie发送给浏览器
void addCookie(Cookie cookie)	

src\com\wzx\pack01_set_get\Demo01SetServlet.java

@WebServlet("/set")
public class Demo01SetServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //数据是key-value的形式  age 18
        //创建cookie对象
        Cookie cookie1 = new Cookie("username","jack");
        Cookie cookie2 = new Cookie("password","1234");

        //因为cookie是浏览器保存会话数据的技术 ,所以必须将cookie发给浏览器
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }
}


Cookie acquisition

Cookie[] getCookies() 获取浏览器发送的cookie  
 Cookie[] cookies = request.getCookies();

src\com\wzx\pack01_set_get\Demo02GetServlet.java

@WebServlet("/get")
public class Demo02GetServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获取cookie  ,第二次开始访问网站,此时浏览器会自动地将保存的cookie放到请求带到Servlet
        Cookie[] cookies = request.getCookies();
        //循环所有的cookie
        for(Cookie cookie:cookies){
    
    
            System.out.println(cookie.getName()+" "+cookie.getValue());
        }
    }
}

Cookie settings lifetime

void setMaxAge(int expiry) Set the maximum lifetime of the cookie (unit: second)
10 24 60*60
(1) By default, the lifetime of the cookie in the browser is a session
(2) we sometimes need to set the lifetime of the cookie Time
If you set setMaxAge, the cookie will be saved in the hard disk according to the survival time
//set the cookie survival time

cookie.setMaxAge(60*60);  //单位是秒,存活时间就是1个小时

src\com\wzx\pack02_life_time\Demo03SetServlet.java

@WebServlet("/set_time")
public class Demo03SetServlet extends HttpServlet {
    
    
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

   }

   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
       //数据是key-value的形式  age 18
       //创建cookie对象
       Cookie cookie1 = new Cookie("username","jack");
       cookie1.setMaxAge( 10*24*60*60);//修改cookie的存活时间
       Cookie cookie2 = new Cookie("password","1234");
       cookie2.setMaxAge( 10*24*60*60);
       //因为cookie是浏览器保存会话数据的技术 ,所以必须将cookie发给浏览器
       response.addCookie(cookie1);
       response.addCookie(cookie2);
   }
}

Cookie access path

1void setPath(String uri)	
设置cookie的路径——浏览器根据这个路径判断那些cookie要发送给服务器
  //方式1:/myweb/      当访问项目下的所有资源,请求都会携带Cookie
  //方式2:/myweb/abc   当访问项目下的abc下所有资源,请求都会携带Cookie
  //方式3:/                      当访问服务器中所有资源,请求都会携带Cookie
  //默认方式:/myweb/   当访问项目下的所有资源,请求都会携带Cookie

Insert picture description here
src\com\wzx\pack03_setpath\Demo04SetServlet.java

@WebServlet("/set_path")
public class Demo04SetServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //数据是key-value的形式  age 18
        //创建cookie对象
        Cookie cookie1 = new Cookie("username2","jack");
        cookie1.setMaxAge( 10*24*60*60);//修改cookie的存活时间
        Cookie cookie2 = new Cookie("password2","1234");
        cookie2.setMaxAge( 10*24*60*60);

        cookie1.setPath("/taobao");
        cookie2.setPath("/taobao");

        //因为cookie是浏览器保存会话数据的技术 ,所以必须将cookie发给浏览器
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }
}

Clear cookies

  • (1) There is no way to clear cookies
  • (2) The survival time can be modified
  • (3) You can use a null value to overwrite the original value.
    1. The cookie lifetime unit is: 0 seconds cookie1.setMaxAge(0);
    . 2. To delete an existing cookie, the latter must be used to overwrite the cookie with the same name and path as the original cookie
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

        Cookie cookie1 = new Cookie("username","");
        Cookie cookie2 = new Cookie("password","");

        cookie1.setMaxAge(1000);
        cookie2.setMaxAge(1000);
        //因为cookie是浏览器保存会话数据的技术 ,所以必须将cookie发给浏览器
        response.addCookie(cookie1);
        response.addCookie(cookie2);
    }

Cookie encoding

1)Cookie不能识别一些特殊符号,所以需要对这个符号进行转码:
编码:  URLEncoder.encode(date, "UTF-8")
 解码: URLDecoder.decode(date, "UTF-8")
(2) 有的值cookie不能保存,则先编码再保存

public class TestURLEncoder {
    
    
    //网络编码,post使用的也是这个编码
    @Test
    public void test() throws UnsupportedEncodingException {
    
    
        //中文
        //明文  密文
        String result = URLEncoder.encode("中国","utf-8");//编码 参1 明文 参2 utf-8
        System.out.println(result);
        //key name  value %E4%B8%AD%E5%9B%BD

        //密文  明文
       String result2= URLDecoder.decode("%E4%B8%AD%E5%9B%BD","utf-8");//解码 参1 密文  参2 utf-8
       System.out.println(result2);
    }
}

src\com\wzx\pack05_encoding\Demo09GetServlet.java

@WebServlet("/get_decode")
public class Demo09GetServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    

    }

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

        Cookie[] cookies = request.getCookies();//
        if(cookies != null){
    
    
            //循环所有的cookie
            for(Cookie cookie:cookies){
    
    
                System.out.println(cookie.getName()+" "+ URLDecoder.decode(cookie.getValue(),"utf-8"));
            }
        }else{
    
    
            System.out.println("没有查询到cookie");
        }


    }
}

Cookie execution process***

  • (1) The browser visits the Servlet for the first time and creates a Cookie object
  • (2) Servlet sends the generated Cookie to the browser ( Set-Cookie )
  • (3) Browser auto save
  • (4) When accessing the Servlet for the second time, the browser will automatically obtain the cookie data ( "Cookie" ) and then put it in the request
    Insert picture description here

Guess you like

Origin blog.csdn.net/u013621398/article/details/108530457