Session is a server-side storage space maintained by the application server. When you connect to the server, the server generates a unique SessionID, use this SessionID as the identifier to access the Session bucket on the server. SessionID is saved to the client and saved using cookies. When a user submits a page, the SessionID is submitted to the server to access Session data. This process requires no developer intervention. Therefore, once the Cookie is disabled on the client, the Session will also become invalid.
The server can also pass the SessionID value through URL rewriting, so it is not completely dependent on cookies. If the client Cookie is disabled, the server can automatically save the Session value by rewriting the URL, and this process is transparent to the programmer.
You can try to use the request even if no Cookie is written. getCookies (); the length of the retrieved Cookie array is also 1, and the Cookie name is JSESSIONID. There is also a long binary string, which is the value of SessionID.
Cookie is the storage space of the client, which is maintained by the browser.
In some situations such as voting, we usually require that each person only vote for one vote because of the principles of fairness. In some WEB development, similar situations are also found. At this time, we usually use cookies to implement such a vote, for example, the following code:
<% Cookie [] cookies = request. getCookies ();
If (cookies. lenght = 0 | cookies = null)
DoStuffForNewbie ();
// No Access
}
Else
{
DoStuffForReturnVisitor (); // already accessed
}
%>
This is an easy-to-understand principle. Check the existence of a COOKIE. If the existence of a COOKIE indicates that the Code that has been written to the COOKIE has been run. However, after the above Code is run, doStuffForReturnVisitor () is executed whenever the result is returned (), you can use control panel-Internet option-settings-to view the file but cannot see the generated cookie file. It is strange that the code is clearly correct. However, if there is a cookie, it will be displayed.
Cookie [] cookies = request. getCookies ();
If (cookies. lenght = 0 | cookies = null)
Out. println ("Has not visited this website ");
}
Else
{
For (int I = 0; I <cookie. length; I ++)
{
Out. println ("cookie name:" + cookies [I]. getName () + "cookie value:" +
Cookie [I]. getValue ());
}
}
Running result:
Cookie name: JSESSIONID cookie value: KWJHUG6JJM65HS2K6
Why is there a cookie? As we all know, http is a stateless protocol. Every time a customer reads a web page, the server opens a new session, and the server does not automatically maintain the customer's context information, so how can we implement the shopping cart in the online store? session is a mechanism for storing context information. It targets every user and stores the variable values on the server, session IDs are used to differentiate different customers. sessions are implemented based on cookies or URL rewriting. By default, the system creates an output cookie named JSESSIONID, which is called session cookie, in order to distinguish persistent cookies, that is, the cookie we usually call. Note that session cookies are stored in the browser memory and are not written to the hard disk. This is the JSESSIONID we just saw, we usually cannot see JSESSIONID, but when we disable the cookie of the browser, the web server will use the URL In the address bar, we can see strings such as Sessionid = KWJHUG6JJM65HS2K6.
After understanding the principles, we can easily distinguish the differences between persistent cookies and session cookies. The discussions on the security of the two on the Internet are clear. session cookies are for a session, session cookie disappears, while the persistent cookie is only a piece of text (usually encrypted) stored on the client's hard disk ), in addition, cookie spoofing and cross-site scripting attacks against cookies are not as secure as session cookies.
Generally, session cookies cannot be used across windows. When you open a new browser window to enter the same page, the system will give you a new sessionid, in this way, we cannot achieve the purpose of information sharing. At this time, we can first save the sessionid in the persistent cookie, and then read it out in the new window to get the SessionID of the previous window, in this way, session cookie and persistent cookie are combined to achieve cross-window session tracking ).
In some web development books, Session and cookie are usually used as two parallel http transmission methods. session cookies are on the server side, and persistent cookies are on the client side, however, session is based on cookies. It is not difficult to select the appropriate technology to develop web services by understanding the relationship and difference between the two.
Certificate -----------------------------------------------------------------------------------------------------------------------------------
I. Differences between cookie and session mechanisms
Specifically, the cookie mechanism adopts the client-side persistence scheme, while the session mechanism adopts the server-side persistence scheme.
At the same time, we can also see that because the server-side persistence scheme also needs to save an identifier on the client, the session mechanism may need to use the cookie Mechanism to save the identifier, but there are actually other options.
Ii. Differences between session cookies and persistent cookies
If no expiration time is set, it indicates that the life cycle of the cookie is the browser session period, and the cookie disappears as long as the browser window is closed. This cookie is called a session cookie. Session cookies are generally stored in memory instead of hard disks.
If the expiration time is set, the browser will save the cookie to the hard disk, and then open the browser again. These cookies are still valid until the preset expiration time is exceeded.
Cookies stored on hard disks can be shared among different browser processes, such as two IE Windows. For Cookies stored in the memory, different browsers have different processing methods.
Iii. How to Achieve Automatic Login
After a user registers for a website, the user will receive a cookie with a unique user ID. When the customer reconnects, the user ID will be automatically returned, and the server will check it to see if it is a registered user and has chosen automatic logon, in this way, you can access resources on the server without providing a clear user name and password.
4. How to customize websites based on users' interests
Websites can use cookies to record users' wishes. For simple settings, websites can store page settings in cookies for customization. However, for more complex customization, the website only needs to send a unique identifier to the user, and the page settings corresponding to each identifier are stored in the database on the server side.
5. Sending cookies
1. Create a Cookie object
2. Set the maximum validity period
3. Put the Cookie in the HTTP Response Header
If you create a cookie and send it to the browser, It is a session-level cookie by default, which is stored in the browser memory and deleted after the user exits the browser. If you want your browser to store the cookie on a disk, you need to use maxAge and give a time in seconds. If the maximum validity period is set to 0, the browser deletes the cookie.
To send a cookie, you must use the addCookie method of HttpServletResponse to insert the cookie into a Set-Cookie HTTP request header. Because this method does not modify any previously specified Set-Cookie header, but creates a new header, we call this method addCookie instead of setCookie. Remember that the response header must be set before any document content is sent to the client.
6. cookie reading
1. Call request. getCookie
To obtain a cookie sent by a browser, you need to call the getCookies method of HttpServletRequest. This call returns an array of Cookie objects, corresponding to the value entered by the Cookie header in the HTTP request.
2. Loop the array and call the getName method of each cookie until the cookie is found.
Cookies are related to your host (domain), not your servlet or JSP page. Therefore, although your servlet may only send a single cookie, you may also get many irrelevant cookies.
For example:
String cookieName = "userID ";
Cookie cookies [] = request. getCookies ();
If (cookies! = Null ){
For (int I = 0; I <cookies. length; I ++ ){
Cookie cookie = cookies [I];
If (cookieName. equals (cookie. getName ())){
DoSomethingWith (cookie. getValue ());
}
}
}
7. How to use cookies to detect new visitors
A. Call HttpServletRequest. getCookies () to obtain the Cookie Array
B. Check whether the cookie with the specified name exists and whether the corresponding value is correct in the loop.
C. If yes, exit the loop and set the differential identifier.
D. Determine whether the user is the first visitor Based on the Difference Identification to perform different operations.
8. Use cookies to detect Common Errors of new visitors
The user cannot be considered as a new visitor simply because the cookie array does not exist in a specific data item. If the cookie array is null, the client may be a first-time visitor, or the result may be caused by the deletion or disabling of cookies.
However, if the array is not null, it only shows that the customer has visited your website or domain. It does not indicate that they have visited your servlet. Other Servlets, JSP pages, and non-Java Web applications can set cookies. Based on the path settings, any cookies may be returned to the user's browser.
The correct method is to determine whether the cookie array is empty and whether the specified Cookie object exists and the value is correct.
IX. Notes on cookie attributes
Attributes are part of the header sent from the server to the browser, but they do not belong to the header returned by the browser to the server.
Therefore, except for the name and value, the cookie attribute only applies to the cookies that are output from the server to the client. The cookies from the browser on the server are not set.
Therefore, do not expect this attribute to be used in cookies obtained through request. getCookies. This means that you cannot just set the maximum validity period of a cookie, send it, search for the appropriate cookie in the subsequent input array, and read its value, modify it and save it back to the Cookie to realize the continuously changing cookie value.
10. How to use cookies to record the access count of each user
1. Obtain the cookie value used by the cookie array to count the number of user visits
2. Convert the value to the int type.
3. Add Value 1 and create a Cookie object with the original name.
4. Reset the maximum validity period.
5. Output new cookies
11. Different definitions of sessions in different environments
Session, which is often translated into sessions in Chinese. Its original meaning refers to a series of actions/messages that start and end, for example, a call is a process from picking up a phone call and dialing to hanging up a phone call.
However, when a session is associated with a network protocol, it often implies two meanings: "connection-oriented" and "/" persistence.
The semantics of a session in the Web development environment has been expanded. The meaning of a session refers to a solution for maintaining the status between the client and the server. Sometimes Session refers to the storage structure of this solution.
12. session mechanism
The session mechanism is a server-side mechanism. The server uses a structure similar to a hash (or a hash) to save information.
However, when the program needs to create a session for a client request, the server first checks whether the client request contains a session id called session id, if a session id already exists, it indicates that a session has been created for this customer. Then, the server uses the session id to retrieve the session. (If NO session id is found, a new session may be created, this situation may occur when the server has deleted the session object corresponding to the user, but the user manually attaches a JSESSION parameter to the request URL ).
If the client request does not contain the session id, the client creates a session and generates a session id associated with the session. The session id will be returned to the client for saving in this response.
13. Several Methods for saving session IDs
A. The cookie can be used to save the session id. In this way, the browser can automatically send the id to the server according to the Rules during the interaction process.
B. because the cookie can be artificially disabled, there must be other mechanisms so that the session id can still be passed back to the server when the cookie is disabled. a frequently used technology is called URL rewriting, the session id is appended to the URL path. There are two additional methods, the other is appended to the URL as a query string. The network remains in the State throughout the interaction process, and the session id must be included after the path that each client may request.
C. Another technique is form hidden fields. The server automatically modifies the form and adds a hidden field so that the session id can be passed back to the server when the form is submitted.
14. When will a session be created?
A common error is that the session is created when a client accesses the session. However, the fact is that the session is created until a server program (such as Servlet) calls HttpServletRequest. A statement such as getSession (true) is created.
15. When the session will be deleted
Sessions are deleted in the following situations:
A. The program calls HttpSession. invalidate ()
B. The interval between the last session id sent by the client and the previous one exceeds the maximum validity period of the session.
C. The server process is stopped.
Once again, closing the browser will only invalidate the session cookie stored in the browser memory of the client, and will not invalidate the session object on the server.
16. What are the disadvantages of URL rewriting?
Use URL rewriting for all URLs, including hyperlinks, form actions, and redirection URLs. Add additional information for each URL that references your site and the URL returned to the user (even through indirect means, such as the Location field in server redirection.
This means that there cannot be any static HTML page on your site (at least there cannot be any link to the dynamic page of the site ). Therefore, each page must be dynamically generated using servlet or JSP. Even if all pages are dynamically generated, if the user leaves the session and returns again through bookmarks or links, the session information will be lost, because the stored Link contains the wrong identifier information-the session id after the URL has expired.
17. What are the disadvantages of using hidden form fields?
This method can be used only when forms are submitted and generated dynamically on each page. Click <a href...> hypertext links do not generate form submissions. Therefore, hidden form fields cannot support normal session tracking and can only be used in a series of specific operations, such as the checkout process of online stores.
18. basic steps of session tracking
1. Access the session object related to the current request
2. Search for session-related information
3. Store session information
4. Discard session data
19. Differences between getSession (), getSession (true), and getSession (false)
GetSession ()/getSession (true): This session is returned when the session exists. Otherwise, a new session is created and the object is returned.
GetSession (false): This session is returned when the session exists. Otherwise, no new session is created and null is returned.
20. How to associate information with sessions
SetAttribute replaces any previously set value. If you want to remove a value without providing any replacement, you should use removeAttribute. This method triggers all valueUnbound methods that implement the value of the HttpSessionBindingListener interface.
21. Are there any restrictions on the type of session attributes?
Generally, the session attribute type can be as long as it is an Object. Except null or basic types, such as int, double, and boolean.
To use a value of the basic type as an attribute, you must convert it to the corresponding encapsulation class object.
22. How to discard session data
A. Only the data created by the self-compiled servlet is removed:
Call removeAttribute ("key") to discard the value associated with the specified key
B. Delete the entire session (in the current Web application ):
Call invalidate to discard the entire session. In this way, all session data of the user will be lost, instead of session data created only by our servlet or JSP page.
C. unregister a user from the system and delete all sessions belonging to him or her
Call logOut to log out from the Web server and discard all sessions associated with the user (one Web application at most ). This operation may affect multiple different Web applications on the server.
23. Use isNew to determine whether a user is a new or old user.
Public boolean isNew () method returns true if the session has not been in contact with the client program (browser). This is generally because the session is created, it is not caused by input customer requests.
However, if isNew returns false, it means that it has previously accessed the Web application and does not mean that they have visited our servlet or JSP page.
Because the session is related to the user, a session may be created on every page accessed by the user. Therefore, if isNew is false, the user can only access the Web application before. The session can be created on the current page or on the previous page.
The correct method is to determine whether a specific key exists in a session and whether its value is correct.
24. What is the difference between Cookie expiration and Session Timeout?
Session Timeout is maintained by the server, which is different from the Cookie expiration date. First, session cookies Based on resident memory are not persistent cookies, so there is no end date. Even if the cookie is intercepted to JSESSIONID and a expiry date is set for it to be sent. Browser sessions and Server sessions are also quite different.
25. Is the life cycle of session cookies the same as that of session objects?
When the user closes the browser, although the session cookie has disappeared, the session object is still stored on the server.
26. Does the session disappear as long as the browser is closed?
Generally, a program sends a command to delete a session when the user logs off. However, the browser never proactively notifies the server that the session will be closed before it closes, therefore, the server has no chance to know that the browser is closed. The server keeps the session object until it is inactive and exceeds the specified interval.
The reason for this error is that most session mechanisms use session cookies to store session IDs. When the browser is closed, the session id disappears, the original session cannot be found when you connect to the server again.
If the cookie set by the server is saved to the hard disk, or the HTTP request header sent by the browser is rewritten by some means, the original session id is sent to the server, then you can still find the original session when you open the browser again.
It is precisely because closing the browser will not cause the session to be deleted, forcing the server to set an expiration time for the session. When the last time the client used the session exceeds this expiration time, the server considers that the client has stopped the activity before deleting the session to save storage space.
Therefore, we can draw the following conclusions:
When the browser is closed, only session cookies in the browser memory will disappear, but the session objects stored on the server will not disappear, or the persistent cookies saved on the hard disk will not disappear.
. When you open two browser windows to access the application, the same session or different session will be used.
Generally, session cookies cannot be used across windows. When you open a new browser window to enter the same page, the system will give you a new session id, in this way, we cannot achieve the purpose of information sharing.
In this case, we can first save the session id in the persistent cookie (by setting the maximum session validity period), and then read it out in the new window, you can get the session id of the previous window, so that we can achieve cross-window session tracking through the combination of session cookies and persistent cookies.
. How to Use sessions to display the number of visits per customer
Because the customer's access times are an integer variable, but the session attribute type cannot use int, double, boolean and other basic types of variables, therefore, we need to use these basic types of encapsulation type objects as the attribute values of the session object.
However, Integer is an Immutable data structure that cannot be changed after being built. This means that each request must create a new Integer object, and then use setAttribute to replace the existing attribute values. For example:
HttpSession session = request. getSession ();
SomeImmutalbeClass value = (SomeImmutableClass) session. getAttribute ("SomeIdentifier ");
If (value = null ){
Value = new SomeImmutableClass (...); // Create a new unchangeable object
} Else {
Value = new SomeImmutableClass (calculatedFrom (value); // create an object after recalculating the value
}
Session. setAttribute ("someIdentifier", value); // use the newly created object to overwrite the old one.
19th. How to Use session accumulative user data
Use variable data structures, such as arrays, lists, maps, or proprietary data structures of applications containing writable fields. In this way, you do not need to call setAttribute unless the object is assigned for the first time. For example
HttpSession session = request. getSession ();
SomeMutableClass value = (SomeMutableClass) session. getAttribute ("someIdentifier ");
If (value = null ){
Value = new SomeMutableClass (...);
Session. setAttribute ("someIdentifier", value );
} Else {
Value. updateInternalAttribute (...); // If the object already exists, update its attributes without resetting the attributes.
}
Thirty. Different Processes of unchangeable objects and changeable objects when session data is updated
The object cannot be changed because it cannot be changed once created. Therefore, you must call setAttribute ("someIdentifier", newValue) every time you want to modify the attribute value in a session) to replace the original attribute value. Otherwise, the attribute value will not be updated. You can change the object because it generally provides a method to modify its own attributes, so every time you want to modify the attribute value in a session, you only need to call the method for modifying the attributes of the object. This means that we do not need to call the setAttribute method.