Java Network communication: HTTP protocol sessions and cookies

Source: Internet
Author: User
Tags session id

Through the previous blog's explanation, we generally know what the HTTP protocol is, what its composition, and how it works, then in the many features of HTTP, there is a point called, stateless, HTTP is a stateless protocol, if you need the previous information to handle the request behind, In the case of HTTP, it is inconvenient to have to re-send the information in front of it, so in order to solve the problem of HTTP in the scene that needs to record the front information, two concepts, session and Cookie are presented. So let's start by knowing what the session is.

Session, as the name implies, Chinese meaning is a conversation, as described earlier, it is used to solve a class of the client and server to maintain state between the solution, in Java discussed in the session, Usually refers to the javax.servlet.http.HttpSession, you can see that the session itself is an object, then in this object is mainly composed of the following elements: 1. A property that stores the various information in the request. 2.SessionID, which is used to map the identity of the corresponding request. Maybe that's a little unclear, so we're going to do the same thing, say a Li Zilai:

Suppose our webserver is a store of stores, and every HTTP request is a visitor to the mall, then the customer needs to store the bag in the mall, the manager will put the customer's bag into the corresponding locker, and this locker is equivalent to the session, and hand over to the customer corresponding number card as the customer leave the time to take the voucher, and after a period of time this locker is only to this customer use, this number card is SessionID. So when the customer (HTTP Request) next time, only the initial corresponding number card (SessionID), storage (WEB Server) will be the customer needs of the locker (Session) to a customer to use, Customers can put things in the locker (deposit the corresponding properties, SetAttribute) and fetch things (getattribute), of course, the store can also be stored in the customer's locker to cancel, and then to other customers use. When the customer leaves the mall (when the customer becomes an HTTP Response), the store will also be friendly to the storage of the reminder locker number to tell customers (will sessionid into the Response), in case customers forget to bring the number card next time. The next time the customer comes over, they will take the same number card.

With this chestnut, we can understand the relationship between the session and the HTTP request and Web server very well. The request and Web server rely on the session to record the state, and the next time the visit, the same SessionID will be obtained to the last state, resolved the stateless problem of HTTP, So what are the cookies we mentioned in the headline? In fact, the cookie is the "number card" we mentioned in the example, this number is placed on the client (storage and browser) a customer can not go to a shopping mall for a lifetime, then this customer will have a lot of "number card", when customers want to go to one of the shopping malls, Will look in their own hands to find out if there is a store's number card (find a cookie that matches the scope) and then take this number card to the corresponding store to carry out the package and other operations.

In this case, just let us have a general understanding of the relationship between HTTP Request, WEB Server, Cookie, Session, HTTP response, and then, We started a serious introduction to the cookies and sessions in HTTP, as well as the related issues that were often encountered during the interview.

Cookie mechanism

The creation of cookies in the browser, mainly through the extension of the HTTP protocol, when the first time to access the Web server, the Web server in response to the HTTP response response header add a line of special instructions, Prompts the browser to save the appropriate cookie locally (the equivalent of the first time a customer stores something in a store, the administrator assigns a locker to the customer, and then gives the customer a number card asking the customer to hold it). The main content of this cookie mainly includes the following points:

1. Name: The name of the cookie.

2. Value: The value deposited in the cookie.

3. Expiry time: If the expiration time is not set, the cookie will disappear when the browser window is closed, as long as the cookie is in the lifetime of the browser session. This cookie, which is the lifetime of the browser session, is referred to as a session cookie. Session cookies are generally not stored on the hard disk but are kept in memory, although this behavior is not regulated. 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 the cookies remain valid until the set expiration time expires.

4. Path and domain: Specify a domain such as. Google.com, you can also specify a specific machine under a domain such as www.google.com, the path is followed by the domain name of the URL path, such as/or/foo, the path and the domain together constitute the scope of the cookie.

It is mentioned here that when a cookie with an expiration time is set, it can be shared between different browser processes. For Mozilla Firefox0.8, all processes and tabs can share the same cookie.

Seesion mechanism

  The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information. When a client initiates an HTTP request and needs to use a session, the WEB server first checks that there are no corresponding SessionID in the HTTP request. If a SessionID is already included, it indicates that the session was previously created for this client, and the server retrieves the session using the session ID (a new one may be created if it is not retrieved) if the client's HTTP The request does not contain a session ID, then a session is created for this client and a value for the session Id,session ID associated with this session should be a string that is neither duplicated nor easily found to mimic the pattern. This session ID will be returned to the client in this response HTTP response.

It is important to mention that in the previous example, it has been said that SessionID is saved with a cookie, which is of course possible, the name of the cookie is similar to Seeesionid, but when the client (browser) disables the cookie, Does that mean the SessionID can't be stored? Of course it's impossible.

Since cookies can be artificially banned, there must be other mechanisms that can still pass the session ID back to the server when the cookie is banned. Often used in a technique called URL rewriting, is to attach the session ID directly behind the URL path, there are two additional ways, one is as the URL path of additional information, the representation of Http://...../xxx;jsessionid=ByOK ... 99zwpbng!-145788764, the other is appended as a query string after the URL, the expression is Http://...../xxx?jsessionid=ByOK ... 99zwpbng!-145788764 (this jsessionid is used to store SessionID), these two ways for the user is not different, but the server in the resolution of the way the processing, the first way is also conducive to the session The ID information is distinguished from the normal program parameters. In order to maintain state throughout the interaction, the session ID must be included after each client may request a path.

After knowing the session and cookie mechanism, let's take a look at some of the dry foods in the interview.

Session FAQs

1.Session creation Time: people often misunderstand that the session is created when there is a client access, However, the fact is that a server-side program called Httpservletrequest.getsession (TRUE) is created, that is, when the browser is opened to request the JSP for the first time, The server will automatically create a session for it (JSP does not show the time to close the session), the JSP will be compiled by default into a servlet when it is automatically added such a statement HttpSession session = Httpservletrequest.getsession (true); This is also the origin of the hidden session object in JSP. If you do not need to use the session in the JSP, you need to display the declaration to close session,<% @page session= "false"%>.

Note: Access to *.html static resources is not compiled as a servlet and does not involve session issues,

2 . Session deletion time: The session will be deleted if the following three conditions are met.

1) Session timeout: Timeout refers to a time when the server does not receive the client's request for the session, and this time exceeds the maximum time that the server sets the session timeout.

2) Program call Httpsession.invalidate ()

3) The server shuts down or the service is stopped (in general, the session is not persisted.) )

In addition to the above, the session will not be deleted, such as closing the browser, will not delete sessions, only delete the conversation cookie (the cookie is not stored in the hard disk)

where 3.session is stored: in the memory of the server, you can also do special processing to persist, in the database or hard disk.

4.SessionID Generation and use: When the client requests the server for the first time. and need to be applied to the session, the server will create a session for the client, and generate a corresponding SessionID to indicate the session, when the next time the browser (session continues to be valid) request other resources, The browser automatically places the SessionID in the request header, the server receives the request SessionID, and the server finds the session of the ID to be returned to the requestor (Servlet) for use. A session can only have one session object, for the session is only recognized ID not identify.

5. The same client machine requests the same resource multiple times, whether the session is the same: for a multi-label browser (such as 360 browser), in a browser window, multiple tabs simultaneously access a page, session is a. For multiple browser windows, at the same time or a short distance to access a page, the session is multiple, and the browser process.

To summarize: The session is a container that can hold any object during the session, and the session is generated by the request object, and the session object is shared by multiple requests in the same conversation, which can be obtained directly from the request to the session object. And in fact, the creation and use of the session is always on the server, and the browser has never been a session object. However, the browser can request that the servlet (JSP is also a servlet) to get information about the session. The client browser really tightly gets the session ID, which is invisible to the browser operator, and the user does not have to care about which session they are in.

Ways to share 6.Session

1) Client cookie Save: The client cookie is saved in a cookie-encrypted manner on the client.

The advantage is to reduce the pressure on the server side, each session information is written on the customer service side. It is then submitted to the server again by the browser. Even if two requests are completed on two servers in the cluster, session sharing can also be reached.

2) inter-server session synchronization: using the inter-server session synchronization using the master-slave server architecture, when the user logs on the primary server, through a script or daemon process, the session information to the various slave servers, This allows the user to read the session information when accessing other slave servers. Disadvantages: such as slow, unstable and so on, in addition, if the session message is the main and from one-way, there will be some risks, such as the main server down, other servers can not get session information

3) use Cluster Management session (such as MSM): use the cluster management session to provide a cluster to save session sharing information. Other applications store their session information in the session Cluster Server group. When the application system needs session information, it will be read directly to the session Cluster server. Currently, most of the sessions are stored using Memcache. There are two more popular options:

A) using the filter method: This way using filters to re-HttpRequest object packaging, and join the memcached client, this way the advantages are: easy to use, the filter configuration can be, in addition to more flexible, Because it is implemented on the client side, the configuration is flexible and server-independent, and you can deploy it on any container that supports servlets.
b) using Memcached-session-manager, commonly known as MSM, is an open source solution for solving the problem of Session sharing in a distributed tomcat environment. It is implemented in the form of a Tomcat plugin deployed on the server, modifies the session-related code in the Servlet container code, makes it connect memcached, and creates and updates the session in Memcached.

4) persist the session to the database: The session is persisted to the data in such a way that the session information is stored in the database, other applications can be detected from the database session information. The current database used for this scenario is generally MySQL. The use of database sharing session of the program has some practicality, but also the following disadvantages: The first session of the concurrent read and write in the database, the performance requirements of MySQL is relatively high; second, we need to implement the session elimination (timeout) logic code, The session information is updated and deleted periodically from the database table, increasing the workload.

Java Network communication: HTTP protocol sessions and cookies

Related Article

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.