I recently studied servlet in Java and learned a lot from the video from Teacher Han shunping of Chuanzhi podcast. I would like to summarize the problems I encountered today.
Case:
There are two servlets (servlet1 and servlet2). Create a session in servlet1, write the attributes to the session, and then read the attributes of the session in servlet2. Normally, you can access servlet1 in the same browser without closing the browser, and then access servlet2, in servlet2, the session value stored in servlet1 can be retrieved. Now, if the browser is closed, access servlet2 directly and you will find that the session attribute created in servlet1 cannot be obtained at this time. I have been very entangled because the teacher repeatedly stressed that the session lifecycle has nothing to do with whether the browser is closed, but why does the browser close (the server is not closed ), when I access servlet2 again, why cannot I retrieve the attributes in the session ???
I wonder if you have ever asked me the question above. Later, instructor Han explained that when accessing servlet1, a session will be created, and the server will return the id value for creating this session. The details are as follows:
GET/test1/forbidcookie HTTP/1.1
Accept :*/*
Accept-language: ZH-CN
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; slcc2 ;. net CLR 2.0.50727 ;. net CLR 3.5.30729 ;. net CLR 3.0.30729; Media Center PC 6.0 ;. net4.0e ;. net4.0c)
Accept-encoding: gzip, deflate
HOST: localhost: 8080
Connection: keep-alive
COOKIE: JSESSIONID = 198cf8f591f240d010d82b88f6d2aa9b
There is no section in the red font. This is the reason. The session and cookie do not exist independently. They have a relationship. The above section indicates the red mark value, it will not be stored in the temporary folder of the browser. It will only be sent at the time of sending, so that when the server needs to create a session again, the tag prevails and the session does not need to be re-created.
If you want to access the session we created after the browser is closed, you can add the following statement:
When you re-open the browser, you can still access the session you just created.
Cookie = new cookie ("JSESSIONID", HS. GETID ());
Cookie. setmaxage (120 );
Response. addcookie (cookie );
Store session IDs in cookies as request messages and send them to the server!