The realization of distributed session, the difference and connection between session and Cookie, and the realization principle of Session

Source: Internet
Author: User
Tags hash memcached session id sessions time interval java web

One. Several realization ways of distributed session

1. Database-based session sharing 2. Shared file system based on NFS
3. Based on the memcached session, how to ensure the high availability of the memcached itself.
4. Session replication mechanism based on the RESIN/TOMCAT Web container itself
5. Session sharing based on Tt/redis or Jbosscache.

6. Session sharing based on cookies

Or is:

First,session Replication mode management (that is, session replication)

Summary: Copy the session data broadcast from one machine to the rest of the machine in the cluster

usage Scenario : Fewer machines, less network traffic

Advantages : Simple implementation, less configuration, no impact on user access when a machine is down in the network

disadvantage : Broadcast replication to the rest of the machine when there is a certain degree, bring a certain network overhead


Second,Session Sticky mode management

Summary: the sticky session, when the user accesses a machine in the cluster, forcing all subsequent requests to fall on this machine

usage Scenario : Moderate number of machines, not very demanding stability requirements

Advantages : Easy to implement, easy to configure, no additional network overhead

disadvantage : The network has a machine down, the user session will be lost, easy to cause a single point of failure


Third, centralized cache management

Introduction: The session is stored in a distributed cache cluster on a machine, when the user access to different nodes, first take session information from the cache

usage Scenario : Multiple machines in a cluster, complex network environment

Advantages : Good reliability

Disadvantage : the implementation of complexity, stability depends on the stability of the cache, session information into the cache should have a reasonable policy to write


Two. The difference and connection between session and Cookie and the principle of session implementation

 1, session is saved on the server, the client does not know the information; the cookie is stored on the client and the server is able to know the information.   
    
  2, the object is saved in the session, and the cookie holds a string.   
    
  3, session can not distinguish between the path, the same user during a visit to a website, all sessions can be accessed in any place. In the cookie, if the path parameter is set, the cookies under different paths in the same Web site are inaccessible to each other.   
    
  4, the session needs to use a cookie to <NOBR oncontextmenu= "return false;" Onmousemove= "KwM (3);" Id= "Key3" onmouseover= "KwE (event,3, this);" style= "COLOR: #6600ff; border-bottom:0px dotted; Background-color:transparent; Text-decoration:underline "onclick=" return KwC (); "Onmouseout=" KwL (event, this); "target=" _blank "> Work </nobr >. If the client completely prohibits cookie,session, it will fail.

HTTP is a stateless protocol, every time a client reads a Web page, the server opens a new session, and the server does not automatically maintain the customer's contextual information, then how to implement the shopping cart in the online store, the session is a mechanism to save the context information, it is for each user, The value of the variable is saved on the server side, by SessionID to distinguish between different customers, session is based on cookie or URL rewriting, the default use of cookies to implement, the system will create an output cookie named Jsessionid, We call the session cookie to distinguish between persistent cookies, which we normally call cookies, which are stored in the browser memory and not on the hard disk, This is the jsessionid we have just seen, we usually do not see the jsessionid, but when we disable the browser cookie, the Web server will be URL rewrite to pass the SessionID, we can see in the Address bar A string such as sessionid=kwjhug6jjm65hs2k6.
Understanding the principle, we can easily distinguish between persistent cookies and session cookies, the online discussion on the security of the two is also clear, session cookie for a session, sessions end The cookie disappears, and the persistent cookie is just a piece of text (usually encrypted) that exists on the client's hard drive, and may be subject to cookie spoofing and cross-site scripting attacks against cookies, which are not as secure as session cookies.
Usually the session cookie is not used across windows, and when you open a new browser window into the same page, the system will give you a new SessionID, so that the purpose of our information sharing is not reached, At this point we can first save the SessionID in the persistent cookie, and then read it in a new window, we can get the previous window SessionID, so through the session cookie and persistent The combination of cookies allows us to implement a cross-window session tracking (conversation tracking).
In some Web development books, the session and cookie are often simply used as two kinds of parallel HTTP transmission information, session cookies located on the server side, the persistent cookie is located on the client, But the session is based on a cookie, understand the relationship between the two and the difference, we will not be difficult to choose the right technology to develop Web service. Anyway:

The difference between the cookie mechanism and the session mechanism specifically, the cookie mechanism uses a scheme that maintains state on the client side, while the session mechanism uses a scenario that maintains state on the server.
At the same time, we also see that the session mechanism may need to use the cookie mechanism to achieve the purpose of preserving the identity, because the scenario in which the server-side holds the state needs to be stored on the client side, but there are actually other options.
Ii. differences between session cookies and persistent cookies
If you do not set an expiration time, the cookie disappears when the browser window is closed as long as the cookie's lifetime is the browser session. This cookie, which has a lifetime of browsing session, is referred to as a session cookie. Session cookies are generally not saved on the hard disk but in memory.
If the expiration time is set, the browser will save the cookie to the hard disk, turn it off and open the browser again, and these cookies remain valid until the set expiration time expires.
Cookies stored on the hard disk can be shared between different browser processes, such as two IE windows. For cookies stored in memory, different browsers have different ways of handling them.
Third, how to use the implementation of automatic login
Once a user has registered with a website, they will receive a cookie with a unique user ID. When the customer later reconnected, the user ID is automatically returned, the server checks it, determines whether it is a registered user, and automatically logs on, so that users can access resources on the server without having to give an explicit user name and password.
Iv. How to customize the site according to the user's hobby
The website may use cookies to record users ' wishes. For simple settings, the site can store the settings of the page directly in a cookie to complete the customization. For more complex customizations, however, the site simply sends a unique identifier to the user, and the server-side database stores the page settings for each identifier.
V. Transmission of cookies
1. Create a Cookie Object
2. Set Maximum Aging
3. Placing a cookie into the HTTP response header
If you create a cookie and send it to the browser, by default it is a session-level cookie: stored in the browser's memory and deleted after the user exits the browser. If you want the browser to store the cookie on disk, you need to use maxage and give a time in seconds. Setting maximum aging to 0 is the command browser to delete the cookie.
Sending a cookie requires the use of the HttpServletResponse Addcookie method to insert the cookie into a Set-cookie HTTP request header. Since this method does not modify any of the previously specified Set-cookie headers, it creates a new header, so we refer to this method as Addcookie rather than Setcookie. Also remember that the response header must be set before any document content is sent to the client.
Vi. reading of Cookies
1. Call Request.getcookie
To obtain a cookie that is sent by the browser, call HttpServletRequest's GetCookies method, which returns an array of cookie objects corresponding to the value entered by the cookie header in the HTTP request.
2. Loop the array and invoke the GetName method of each cookie until the cookie of interest is found
The cookie is associated with your host (domain), not your servlet or JSP page. Thus, although your servlet may send only a single cookie, you may also get many unrelated cookies.
For example:
String cookiename = "UserID";
Cookie cookies[] = request.getcookies ();
if (cookies!=null) {
for (int i=0;i
Cookie cookie = cookies[i];
if (Cookiename.equals (Cookie.getname ())) {
Dosomethingwith (Cookie.getvalue ());
}
}
}
Vii. How to use cookies to detect initial visitors
A. Call Httpservletrequest.getcookies () to get an array of cookies
B. Retrieving a cookie for a specified name in a loop exists and the corresponding value is correct
C. If yes, exit the loop and set the differential ID
D. Determine whether the user is a novice and perform different operations according to the distinguishing mark
Viii. use of cookies to detect common mistakes in initial visitors
You cannot think of a user as a novice simply because the cookie array does not exist in a particular data item. If the cookie array is null, the customer may be a novice, or it may be the result of a user deleting or disabling the cookie.
However, if the array is not NULL, it simply shows that the client has been to your site or domain and does not indicate that they have visited your servlet. Other Servlets, JSP pages, and non-Java Web Apps can set cookies, depending on the path setting, where any cookie is likely to be returned to the user's browser.
The correct approach is to determine if the cookie array is empty and the specified cookie object exists and the value is correct.
Nine, the use of cookie attributes of attention issues
Properties are part of the header that is sent from the server to the browser, but they do not belong to the header returned to the server by the browser.
Therefore, in addition to the name and value, the cookie attribute applies only to cookies exported from the server to the client, and the server-side cookie from the browser does not have these attributes set.
This property is therefore not expected to be available in cookies obtained through request.getcookies. This means that you cannot simply set the cookie's maximum age, issue it, look for the appropriate cookie in the subsequent input array, read its value, modify it, and save it back to the cookie to achieve the changing cookie value.
X. How to use cookies to record access counts for individual users
1. Get the value of the cookie in the cookie array specifically used to count the number of user visits
2. Convert values to int type
3. Add a value of 1 and recreate a cookie object with the original name
4. Reset Maximum Aging
5. Export the new cookie
Xi. the different meanings of the session in different environments
Session, Chinese is often translated into a conversation, its original meaning refers to the beginning and end of a series of actions/messages, such as the call is from the pick up the phone to dial to hang up the phone in the middle of a series of processes can be called a session.
However, when the term session is associated with a network protocol, it often implies two meanings such as "connection oriented" and/or "hold State".
The semantics of the session in the Web development environment also has a new extension, meaning refers to a class of solutions to maintain state between the client and the server side. Sometimes the session is used to refer to the storage structure of this solution.
12, S-ession mechanism
The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information.
However, when a program needs to create a session for a client's request, the server first checks to see if the client's request contains a session ID-called the session ID. If it already contains a session The ID indicates that the previous session has been created for this customer, the server will follow the session ID to retrieve the session (if it is not retrieved, may create a new one, this situation may appear on the service side has deleted the user corresponding Session object, However, the user manually appends the previous jsession parameter to the requested URL.
If the customer request does not include a session ID, a session is created for the customer and a session ID associated with the session is generated, and the session ID is returned to the client in this response.
13. Several ways to save session ID
A You can save the session ID by using a cookie so that the browser can automatically send the tag to the server in the interactive process.
B Since cookies can be artificially banned, there must be other mechanisms to pass the session ID back to the server when the cookie is banned, a technique often called URL rewriting, which appends the session ID to the URL path, with two additional ways, One is additional information as a URL path, and the other is appended to the URL as a query string. The network always maintains state throughout the interaction and must include the session ID after each client may request a path.
C Another technique is called a form-hidden field. Is that the server automatically modifies the form, adding a hidden field so that the session ID can be passed back to the server when the form is submitted.
14. When was the session created?
A common mistake is that the session is created when there is client access, but the fact is that it is not created until a statement such as Httpservletrequest.getsession (true) is called by a server-side program, such as a servlet.
When the session is deleted
The session is deleted under the following circumstances:
A Program Call Httpsession.invalidate ()
B Distance from the last received client sent session ID time interval exceeds the maximum effective time of the session
C Server process is stopped
Note that closing the browser only invalidates the session cookie stored in the client browser memory and does not invalidate the session object on the server side.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.