Help you understand what is Session

Table of contents

1. What is a session?

2. When should you consider using Session?

3. How to use Session?

4. Detailed explanation of Session:

5. Comparison between HttpSession and Cookie

 6. What are the disadvantages of Session?


1. What is a session?

The Session we are talking about is actually the implementation class of the HttpSession interface. It's just that the implementation class of the HttpSession interface is implemented by the Tomcat server for us, and we don't need to implement it ourselves. The Session we have been talking about below is actually HttpSession.

2. When should you consider using Session?

When there is a demand: 2 Servlets come from the same website and provide services for the same user.

3. How to use Session?

Using Session is actually very simple, we only need the following code:

HttpSession session = request.getSession();
类型 x=session.getAttribute(key);//先去查询是否有session
session.setAttribute(key,value);//如果没有session,在根据逻辑,决定是否需要设置session

4. Detailed explanation of Session:

  • Session is equivalent to a map, and many keys and values ​​can be placed in this map. We can also get all keys and values. The way to get it is as follows:
Enumeration keys=session.getAttributeNames(); //java规定,其返回是一个枚举类型
 while(keys.hasMoreElements()){
     类型 Y= goodsname.nextElement();  //Y就是key
     // X就是value
     类型 X=  session.getAttribute(Y);//这里是从map拿到的,所以value一定不会为null
     out.print(": "+Y+ "  "+X);
 }
  • After the session is created, it will be placed on the server. The default survival time is 30 minutes. After this time, the session will be "killed" by the server. Of course, we can also manually set the session survival time in the web.xml file.
<Session-config>
    <Session-timeout>X</Session-timeout>这里X的单位是分钟
</Session-config>
  •  A user, a SessionID, the response packet will put the SessionID in the cookie and return it to the browser.

5. Comparison between HttpSession and Cookie

 6. What are the disadvantages of Session?

Guess you like

Origin blog.csdn.net/weixin_44362089/article/details/127226388