JAVAWEB-Session technology Cookie&Session, specific usage of Cookie&Session, obtain Session object, Session life cycle

1. Introduction to conversation technology

1. Store the state of the client

In our shopping system on the website, where does the user store the purchased product information? Because the Http protocol is stateless, that is, when each client accesses server-side resources, the server does not know who the client is, so session technology is required to identify the state of the client. The conversation technology isHelp the server remember the client status (distinguish the client)

2. Conversational technology

The whole process from opening a browser to a certain site to closing the browser becomes a session. The session technology is to record the state and data of the client in this session.
Conversation technology is divided into Cookieand Session:

  • Cookie: Data is stored locally on the client, reducing the storage pressure on the server. The security is not good, and the client can clear cookies.
  • Session: Store data on the server side, with relatively good security, increasing the pressure on the server.

2. Cookie technology

For example, we are visiting the Taobao
Insert picture description here
website : the chart states that when we use the browser to visit the shopping website and add things to the shopping cart, the product information will be placed in the browser. When we close the browser and visit again, the items in the shopping cart are still displayed.

Cookie technology is a technology that stores user data on the client. We are divided into two aspects to learn:

First, how does the server send a Cookie to the client.
Second, how does the server accept the Cookie carried by the client.

Lead to the following two main points:

Three, the server sends a Cookie to the client

1. Create Cookie:

  • Cookie cookie = new Cookie(String cookieName,String cookieValue);

E.g:

Cookie cookie = new Cookie("username""zhangsan");

Then the cookie will be sent to the client in the form of a response header:
Insert picture description here

Note: Chinese cannot be stored in Cookies

2. Set the persistence time of Cookie on the client:

  • cookie.setMaxAge(int seconds); The time in parentheses here

E.g:

cookie.setMaxAge(10*60);

Set the cookie information to be stored in the browser's disk file for 10 minutes, and the browser will automatically delete the cookie information after expiration.

Note: 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 according to the length of time. In the disk file.

3. Set the cookie carrying path:

  • cookie.setPath(String path);
    Note: If the carrying path is not set, then the cookie information will carry the cookie information in the path where the web resource that generated the cookie is accessed

E.g:

cookie.setPath("/WEB16");

Represents access to any resource in the WEB16 application with cookies

cookie.setPath("/WEB16/cookieServlet");

The cookie information is only carried when the representative visits the cookieServlet in WEB16

4. Send cookies to the client:

  • response.addCookie(Cookie cookie);

5. Delete the client's cookie:

If you want to delete the stored cookie information of the client, thenOverwrite with a cookie with the same name and path with a persistence time of 0Can

Comprehensive case one:

@WebServlet(name = "SendCookieServlet",urlPatterns ="/SendCookieServlet")
public class SendCookieServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request,response);
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //1.创建Cookie对象
        Cookie cookie = new Cookie("name","zhangsan");
        //1.1 为Cookie设置持久化时间---Cookie信息在硬盘上保存的时间
        cookie.setMaxAge(60*10);//10分钟,时间设置为0代表删除该Cookie
        //1.2为Cookie设置携带路径
        cookie.setPath("/SendCookieServlet");//访问SendCookieServlet资源才携带Cookie
        cookie.setPath("/WEB16");//访问WEB16下的任何资源是都携带这个Cookie
        cookie.setPath("/");//访问服务器下的所有资源携带的Cookie
        //2.发送Cookie中存储的信息发的送到客户端====以响应头的形式
        response.addCookie(cookie);
    }
}

Comprehensive case two:

(Delete Cookie)

@WebServlet(name = "RemoveCookieServlet",urlPatterns =
"/RemoveCookieServlet")
public class RemoveCookieServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            //删除客户端保存name=zhangsan的cookie信息
        Cookie cookie = new Cookie("name","");
            //将path设置成与要删除cookie的path一致
            cookie.setPath("/WEB16");
            //设置时间为0
            cookie.setMaxAge(0);
            response.addCookie(cookie);
    }
}

Usage steps: If we visit "/SendCookieServlet" at this time, then the name = zhangsan will be stored in the Cookie, and then when we visit "/RemoveCookieServlet", we will clear its cache, just set his MaxAge=0. We visit index.jsp and will not find cookies.

4. How does the server accept cookies carried by the client?

The cookie information is sent to the server in the form of a request header. So the steps for our server to accept cookies:

  • The first step: get all cookies through request:
Cookie[] cookies = request.getCookies();
  • Step 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();
}
}

Case:

@WebServlet(name = "GetCookieServlet",urlPatterns =
"/GetCookieServlet")
public class GetCookieServlet extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //获取客户端携带的cookie的数据
         Cookie cookies[] = request.getCookies();
         //通过cookie名称获取想要的Cookie
        for (Cookie cookie :cookies){
    
    
            //获得cookie的名称
            String cookieName = cookie.getName();
            if (cookieName.equals("name")){
    
    
                String cookieValue = cookie.getValue();
                System.out.println(cookieValue);
            }
        }
    }

Five, Session technology

Session technology is a technology that stores data on the server side. It creates a memory space for each client to store the client's data, but the client needs to carry an identification ID every time to find its own memory space in the server. soThe implementation of Session is based on CookieSession needs to store the customer's unique identification JSESSIONID with the help of Cookie
Insert picture description here
In Session, we need to learn the following three questions:

How to get the session object (memory area) belonging to this client?

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

The life cycle of the session object?

1. Get the Session object

  • HttpSession session = request.getSession()
    This method will get the Session object dedicated to the current session. If the server does not have the Session object for the session, it will create a new Session and return it. If there is already a Session belonging to the session, it will directly return the existing Session (essentiallyAccording to JSESSIONID, determine whether the client already has a session on the server

Case number one:

@WebServlet(name = "SessionServlet1",urlPatterns ="/SessionServlet1")
public class SessionServlet1 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
   //创建属于该客户端(会话)的私有的session区域
   /*request.getSession()方法内部会判断 该客户端是否在服务器端已经存在session
 如果该客户端在此服务器不存在session,那么就会创建一个新的session对象
 如果该客户端在此服务器已经存在session 获得已经存在的session并返回*/
    HttpSession httpSession =  request.getSession();
    String id = httpSession.getId();//该session对象的编号id
       response.getWriter().write("JSESSIONID:"+id);
            System.out.println(id);
     }
}

The effect is as follows:
Insert picture description here

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

Session is also a regional 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)

Case 2:

Step 1: Create a SessionServlet1 object

@WebServlet(name = "SessionServlet1",urlPatterns =
"/SessionServlet1")
public class SessionServlet1 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
  HttpSession httpSession =  request.getSession();
  httpSession.setAttribute("name","yjw");
  String id = httpSession.getId();//该session对象的编号id
         response.getWriter().write("JSESSIONID:"+id);
            System.out.println(id);
        }
}

Step 2: Create a SessionServlet2

@WebServlet(name = "SessionServlet2",urlPatterns = "/SessionServlet2")
public class SessionServlet2 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //从session中获得存储数据
         HttpSession httpSession = request.getSession();
         String attribute =(String)httpSession.getAttribute("name");
         response.getWriter().write(attribute);
    }
}

The effect is as follows:
Insert picture description here

3. The life cycle of the Session object (interview questions/written test questions)

The life cycle of the Session object

  • Create: Created when request.getSession() is executed for the first time
  • destroy:
  1. When the server (unnormally) shuts down
  2. Session expired/invalid (default 30 minutes)
    Note: The starting point of the time is 30 minutes from not operating the server-side resources and can be configured in the web.xml of the project

as follows:

<session-config>
        <session-timeout>60</session-timeout>
</session-config>
  1. Manually destroy the session
  • session.invalidate()

Session scope: The
default is in a session, that is to say, any resource in a session shares a session object

Interview question: The session is destroyed when the browser is closed? ——Wrong
browser is at the client level, while session is at the server level

4. The persistence of JSESSIONID

Thought: The Session automatically set by the first Servlet to be visited, in the form of a Cookie, changes the duration of setMaxAge() access on the client side. So as to realize the persistence of JSESSIONID.

@WebServlet(name = "SessionServlet1",urlPatterns =
"/SessionServlet1")
public class SessionServlet1 extends HttpServlet {
    
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
HttpSession httpSession =  request.getSession();
String id = httpSession.getId();//该session对象的编号id
//手动创建一个存储JSESSIONID的Cookie为该Cookie设置持久化时间
 Cookie cookie = new Cookie("JSESSIONID",id);
        cookie.setPath("/WEB16");
        cookie.setMaxAge(60*10);//自行设置时间
        response.addCookie(cookie);         
        response.getWriter().write("JSESSIONID:"+id);
           System.out.println(id);
       }
}

Guess you like

Origin blog.csdn.net/Mr_GYF/article/details/109169158