JavaWeb Note 4: Session Technology Cookie&Session

conversational technology

What are conversational technologies? For example, in the shopping system of the website, where does the user store the purchased product information? Because the Http protocol is stateless, that is to say, when each client accesses server-side resources, the server does not know who the client is, so session technology is needed to identify the state of the client. Session technology is to help the server remember the client state (differentiate the client).

The whole process from opening a browser to visit a certain site to closing the browser is called a session. Session technology is to record the status and data of the client in this session. Session technology is divided into Cookie and Session:

Cookie: The data is stored locally on the client side, reducing the storage pressure on the server side. The security is not good, and the client side can clear the cookie.

Session: Store data on the server side, which has relatively good security and increases the pressure on the server.

Cookie technology

Cookie technology is a technology that stores user data to the client. We learn in two ways:

The server sends a cookie to the client

  1. Create a cookie: Cookie cookie = new Cookie(String cookieName,String cookieValue); ,For example: Cookie cookie = new Cookie("username","zhangsan");then the cookie will be sent to the client in the form of a response header. Note that Chinese cannot be stored in cookies.
  2. Set the persistence time of the cookie on the client: cookie.setMaxAge(int seconds);—time seconds, note that if the persistence time is not set, the cookie will be stored in the browser's memory, and the browser will close the cookie information destruction (session-level cookie), if the persistence time is set , the cookie information will be persisted to the browser's disk file. For example: cookie.setMaxAge(10*60); , set the storage time of cookie information in the browser's disk file to 10 minutes, and the expired browser will automatically delete the cookie information.
  3. Set the carrying path of the cookie: cookie.setPath(String path);, note that if the carrying path is not set, the cookie information will carry the cookie information on the path where the web resource that generated the cookie is accessed. Example: cookie.setPath("/WEB16"); means that any resource accessed in the WEB16 application will carry a cookie. cookie.setPath("/WEB16/cookieServlet"); means that the cookie information is only carried when accessing the cookieServlet in WEB16.
  4. Send cookie to client:response.addCookie(Cookie cookie);
  5. Delete the client’s cookie: If you want to delete the stored cookie information on the client, you can overwrite it with a cookie with the same name and the same path and a persistence time of 0
//设置cookie的最大有效时间
//cookie.setMaxAge(60*60);
//设置为-1 , 就是相当于默认有效时间, 浏览器关闭就消失.
//cookie.setMaxAge(-1);
// 标示cookie的有效时间为0.发送到浏览器就消失了.
//利用有效时间为0 这件事,我们可以做删除cookie的操作.
// 因为同一个路径 ,不能存在相同的cookie(键相同).
// 我们可以通过覆盖的方式,设置有效时间为0. 删除cookie
//cookie.setMaxAge(0);

The complete code example for sending cookies is as follows:

//1、创建cookie对象
Cookie cookie = new Cookie("name","zhangsan");

//1.1 为cookie设置持久化时间 ---- cookie信息在硬盘上保存的时间
cookie.setMaxAge(10*60);//10分钟 ---- 时间设置为0代表删除该cookie
//1.2 为cookie设置携带的路径
//cookie.setPath("/WEB16/sendCookie");//访问sendCookie资源时才携带这个cookie
cookie.setPath("/WEB16");//访问WEB16下的任何资源时都携带这个cookie
//cookie.setPath("/");//访问服务器下的所有的资源都携带这个cookie

//2、将cookie中存储的信息发送到客户端---头
response.addCookie(cookie);

How does the server accept the Cookie carried by the client?

The cookie information is sent to the server as a request header:

1. Obtain all cookies through request:

Cookie[] cookies = request.getCookies();

2. Traverse the Cookie array and get the Cookie we want by the name of the Cookie

 for(Cookie cookie : cookies){
    
    
     if(cookie.getName().equal(cookieName)){
    
    
          String cookieValue = cookie.getValue();
    }
}

Full example:

//获得客户端携带的cookie的数据
Cookie[] cookies = request.getCookies();
//Cookie cookie = new Cookie("name","zhangsan");
//通过cookie名称获得想要的cookie
if(cookies!=null){
    
    
    for(Cookie cookie : cookies){
    
    
        //获得cookie的名称
        String cookieName = cookie.getName();
        if(cookieName.equals("name")){
    
    
            //获得该cookie的值
            String cookieValue = cookie.getValue();
            System.out.println(cookieValue);
        }
    }
}

Exercise: Get the time of the user's last visit

//获得当前时间
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String currentTime = format.format(date);

//1、创建Cookie 记录当前的最新的访问时间
Cookie cookie = new Cookie("lastAccessTime",currentTime);
cookie.setMaxAge(60*10*500);
response.addCookie(cookie);

//2、获得客户端携带cookie ---- lastAccessTime
String lastAccessTime = null;
Cookie[] cookies = request.getCookies();
if(cookies!=null){
    
    
    for(Cookie coo : cookies){
    
    
        if("lastAccessTime".equals(coo.getName())){
    
    
            lastAccessTime = coo.getValue();
        }
    }
}

response.setContentType("text/html;charset=UTF-8");
if(lastAccessTime==null){
    
    
    response.getWriter().write("您是第一次访问");
}else{
    
    
    response.getWriter().write("您上次的访问的时间是:"+lastAccessTime);
}

Session technology

Session technology is a technology that stores data on the server side. It will create a memory space for each client to store customer data, but the client needs to carry an identification ID every time to find its own memory space in the server. Therefore, the implementation of Session is based on Cookie, and Session needs to use Cookie to store the customer's unique identifier JSESSIONID.

Get the Session object

HttpSession session = request.getSession();

This method will obtain the Session object exclusive to the current session. If the server does not have a Session object for the session, a new Session will be created and returned. If there is already a Session belonging to the session, the existing Session will be returned directly (essentially, according to JSESSIONID Determine whether the client already has a session on the server)

How to access data to session (session is also a domain object)

Session is also a region object for storing data, so the session object also has the following three methods:

session.setAttribute(String name,Object obj);
session.getAttribute(String name);
session.removeAttribute(String name);
HttpSession session = request.getSession();
        
    System.out.println(session.getCreationTime()); //创建时间
    System.out.println(session.getLastAccessedTime());//最后一次访问session的时间
    System.out.println(session.getId()  );//获得sessionID
    System.out.println(session.getMaxInactiveInterval());//获得最大存活时间
   //setMaxInactiveInterval(int interval)		   //invalidate 立即销毁session		   System.out.println(session.isNew());//查看当前获得的session是否是新的.只有在第一访问服务器,session是新的.		   session.invalidate();

The life cycle of the Session object

Create: created when request.getSession() is executed for the first time

destroy:

When is the starting point for
the session expiration/invalidation (30 minutes by default) when the server (abnormally) shuts down ? Start timing from not operating server-side resources, which can be configured in the project's web.xml

<session-config>
<session-timeout>30</session-timeout>
</session-config>

Destroy session manually

session.invalidate();

Scope of action

By default, in a session, that is to say, any resource in a session shares a session object.

When the browser is closed, the session is destroyed?

No, the unique identifier JSESSIONID (sessionid) that existed on the browser disappeared, but the sessionid stored in the server was not destroyed immediately.

  • When multiple tabs are opened in the same browser at the same time, and the same request or different requests are sent, the same session is still used;
  • When the same browser is not opened in the same window, the request is still the same session;
  • When using different browsers, sending requests, even if sending the same request, is a different session;
  • When all the current browser windows are closed and opened again, when the same request is initiated, it is a different session.

References:
1. https://www.cnblogs.com/ginb/p/7227240.html

Guess you like

Origin blog.csdn.net/weixin_42838061/article/details/121171907