Session What is this?

2010-03-23  来源:本站原创  分类:Java  人气:411 

[size = x-large] [size = large] 1, the term session
In my experience, where, session this term is probably second only to the extent of abuse of transaction, even more interesting is the transaction with the session under the meaning in some contexts is the same.

session, the Chinese often translated into the session, its original meaning refers to the beginnings and ends of a series of actions / messages, such as dial-up phone calls from the pick up the phone to hang up the middle of a series of processes that can be called one session. Sometimes we can see that the words "in a browser during the session ,...", use of the word of the conversation here is its original meaning, refers to from a browser window opens to a close this period ①. The most confusing is the "user (client) in a session during the" That one word, it might refer to the user's range of action (generally with a specific purpose related to a series of actions, such as log on to the purchase of goods from the to sign out of such an online shopping checkout process, sometimes referred to as a transaction), but sometimes they may simply refer to a connection, may also refer to the meaning of ①, the difference can only rely on context to infer ②.

However, when the term session is associated with the network protocol when it often implies a "connection-oriented" and / or "keep state" the meaning of this two, "connection-oriented" refers to the two communicating parties in the communication prior to first establish a communication channel, such as phone calls, until the other party received a telephone communication can begin, with this relative is to write the letter you sent out, when you can not confirm each other's address is correct channels of communication are not necessarily can be established, but the sender, the communication has already begun. "Maintain state" refers to a party to be able to communicate a series of messages associated with them, making the message dependency among each other, such as an attendant can recognize old customers to visit again, and remember the last time the customer still owes money to a shop . Examples in this category as "a TCP session" or "a POP3 session" ③.

And by the booming era of web servers, session in the Context of the Semantic web developer has a new expansion of its meaning refers to a type used between the client and server solution for the state of ④. Session is also sometimes used to refer to the solution of the storage structure, such as "to save the session where xxx" ⑤. A variety of languages used in web development to a certain extent, have provided support for this solution, so in the Context of a particular language, session is also used to refer to the language of solutions, such as regular to Java, provides javax.servlet.http.HttpSession referred to as the session ⑥.

In view of this confusion has been changed, the use of the term session in this article may have different meanings depending on the context, please note that resolution.
In this article, the use of Chinese "during the browser session" to express the meaning of ①, the use of "session mechanism" to express the meaning of ④, the use of "session" to express the meaning of ⑤, the use of specific "HttpSession" to express the meaning of ⑥

2, HTTP protocol and the state to maintain
HTTP protocol itself is stateless, which is the purpose of the original HTTP protocol is in line with the client requires only a simple request to the server to download certain files, either the client or the server is not necessary to record each other's past behavior, and each time between the request are independent, like a customer and a vending machine or an ordinary (non-member system) the same as the relationship between supermarkets.

However, smart (or greedy?) People soon discovered that if they can provide some on-demand dynamic information generated by web will become more useful, like add-on-demand capabilities to the same cable. This demand forced the one hand, and gradually add HTML form, script, DOM and other client-side behavior, the other on the server side appeared in the CGI specification to respond to the dynamics of the client request, the HTTP protocol as a transport carrier has also added a file upload , cookie these characteristics. In which the role cookie is to solve the shortcomings of stateless HTTP protocol efforts. As for the subsequent emergence of the session is yet another mechanism for the client and the server to maintain state solution.

Let us use some examples to describe the cookie and the session the difference between the mechanisms and linkages. I once frequented a coffee shop to drink five cups of coffee a cup of coffee for free gift offers, however, consumption of five cups of coffee a one-time little chance this time will need some way to record a customer's consumption. Imagine several in fact nothing less than the following programs:
1, the store clerk is very powerful, can remember every customer's consumption, as long as customers walked into a coffee shop, shop assistants will know how to treat a. This approach is the agreement itself to support the state.
2, issue customers a card above the number of recorded consumption in general there is still valid. For each consumer, if the client to produce this card, then the consumer will be with before or after the consumption linked together. This approach is to keep the client state.
3, a membership card issued to customers, in addition to what information card number is not outside the record, every consumer, if the client to produce the card, then the clerk in the store's record book and find the card number corresponds to the record to add some consumer information. This approach is to keep the state on the server side.

As the HTTP protocol is stateless, but due to various considerations do not want to become a state, therefore, the last two programs on a realistic option. Specifically, uses a cookie mechanism to maintain state of the client program, while the session mechanism is used to maintain the state of the server-side program. Meanwhile, we can see that there used to maintain the status of the server-side program on the client also needs to save a logo, so session mechanisms may require the help save the cookie mechanism to achieve the purpose of identification, but in fact it also has other options.

Third, understanding the mechanism cookie
cookie mechanism as the basic principle is as simple as the above example, but there are several problems to be solved: "membership card" how to distribute; "membership card" content; and clients how to use the "Member Card."

Orthodox cookie distribution is achieved by extending the HTTP protocol, the server through the HTTP response headers to add a line of special instructions to prompt the browser follow the instructions for generating the appropriate cookie. However, a purely client-side scripting such as JavaScript or VBScript can also be generated cookie.

The use of the cookie by the browser in accordance with certain principles in the background automatically sent to the server. Check all stored in the browser cookie, if a cookie scope of the declaration to be greater than or equal to the location of the resources requested, put the cookie is attached to the request of the resources of the heads of HTTP requests sent to the server. Means that McDonald's membership card can only be produced in the McDonald's store, if a store has also released its own membership card, then enter the store when the show in addition to McDonald's membership card, but also to show members of the store card.

cookie contents include: name, value, expiration time, path and domain.
You can specify the domain in which a certain domain such as., the equivalent of main store signs, such as Procter & Gamble, you can also specify a domain under a specific machine such as or one, can drift to do more than soft.
Path is with the domain name behind the URL path, like / or / foo, etc., can be used to do more than a counter Rejoice.
Path and the domain together constitute the scope of the role cookie.
If you do not set the expiration time, then the lifetime of this cookie to the browser during the session, simply close the browser window, cookie disappears. This life cycle phase for the browser session cookie is called a session cookie. Session cookie is generally not stored on the hard disk but kept in memory, of course, such behavior is not a standard requirement. If you set an expiration time, the browser the cookie will be saved to the hard drive, shut down again, open your browser, the cookie is still valid until the expiration time exceeds a set.

Stored in a cookie on your hard disk in a different browser, you can be shared between processes, such as the two IE windows. For stored in memory of the cookie, different browsers have different approach. For IE, open the window in a press Ctrl-N (or from the File menu) to open the window can be shared with the original window, while the use of other forms and new processes can not open IE window already open shared memory cookie; for Mozilla Firefox0.8, all of the process and the tab can share the same cookie. Generally speaking, is javascript's to open the window with the original window, shared-memory cookie. Browser, this cookie for the session cookie only to identify the treatment of people do not recognize the frequent use of session mechanism, web application development has caused great troubles.

Here is a goolge set the first example of the response cookie
HTTP/1.1 302 Found
Set-Cookie: PREF = ID = 0565f77e132de138: NW = 1: TM = 1098082649: LM = 1098082649: S = KaeaCFPo49RiA_d8; expires = Sun, 17-Jan-2038 19:14:07 GMT; path = /; domain =. google . com
Content-Type: text / html

This is the use of HTTPLook this HTTP Sniffer software to capture part of the HTTP communication records

Goolge browser to access the resource again automatically when you send out a cookie

The use of Firefox can be easily observed using the existing cookie value HTTPLook with Firefox can be easily understood cookie works.

IE can be set to accept cookie before the inquiry

This is a question to accept cookie dialog box.

Fourth, understanding the mechanism session
session mechanism is a server-side mechanism, the server uses a hash table is similar to the structure (and probably is to use a hash table) to store information.

When the program needs for a client's request to create a session when the server first checks the client's request where it already contains a session ID - known as the session id, if you have contains a session id is illustrated previously for this client Create off session, the server according to retrieve the session id out of the use of this session (if not retrieved, may be a new one), if the client request does not contain a session id, then create a session for this client, and generates a session with this associated with the session id, session id value should be neither a repeat, not easy to find patterns in order to fake a string, the session id will be returned in this response to the client to save.

Way to preserve the session id can be used cookie, so that interaction in the browser can automatically according to the rules to play this identity to the server. The name of this cookie are generally similar to SEEESIONID, and. For example, web application, weblogic generated cookie, JSESSIONID = ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng! -145788764, Its name is JSESSIONID.

As the cookie can be artificially prohibited, there must be other mechanisms in order to be prohibited when the cookie will still be able to pass back to the server session id. Is often used a technique called URL rewriting, that is, the session id appended to the URL path directly behind, there are two additional ways, one is the URL path as additional information, showing the form of http:// ... .. / xxx; jsessionid = ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng! -145788764
The other is as a URL query string appended to the back, showing the form of http://...../xxx?jsessionid=ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764
Of these two methods is no difference for users, only resolved when the server handled in different ways, using the first approach is also conducive to the session id information and distinguish between normal process parameters.
Throughout the interactive process in order to always maintain the state, it must be possible for each client request contains the path to the back of this session id.

Another technique known as hidden form fields. Is that the server will automatically modify the form, add a hidden field in order to be able to form submission when the session id passed back to the server. For example the following form
<form name="testform" action="/xxx">
<input type="text">
</ form>
Being passed to the client before being rewritten into
<form name="testform" action="/xxx">
<input type="hidden" name="jsessionid" value="ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764">
<input type="text">
</ form>
This technology is now relatively small application, I have been in contact very old iPlanet6 (SunONE Application Server's predecessor) on the use of this technology.
In fact this technology can be a simple action with the right application of URL rewriting instead.

Talking about the session when these mechanisms are often heard of such a misunderstanding, "as long as the browser is closed, session disappears." In fact, examples of membership cards can imagine, unless the customers take the initiative to raise sales store card, otherwise stores would not easily delete the customer information. The same is true for the right session, unless the procedure to inform the server to delete a session, otherwise the server will always be retained procedures are generally done in the user log off when issued a command to delete session. However, the browser will never take the initiative to notify the server that it will shut down to close, so the server will not have the opportunity to know the browser is closed, the reason why there is such a misconception that most of the session mechanism to use a session cookie to store the session id and close your browser the session id will disappear again when you connect to the server will not be able to find the original session. If the server cookie settings are saved to the hard disk, or the use of a means to rewrite the browser sends HTTP request header to the original session id sent to the server, then re-open the browser can still find the original session.

It is precisely because of the closure does not cause the browser session is deleted, forcing the server to set up a seesion failure time, when the distance from the client using the session last longer than the time of this failure, the server that the client has ceased its activities, before the session to delete in order to save storage space.

5, understanding javax.servlet.http.HttpSession
HttpSession is a Java platform session mechanism to achieve the norm, because it is just the interface, specific to each web application server providers, in addition to standard support, but there will still be a number of specification does not stipulate where the nuances. Here we are with BEA's Weblogic Server8.1 as an example to demonstrate.

First of all, Weblogic Server provides a number of parameters to control its HttpSession implementation, including the use of cookie-switch option, the use of URL rewriting switch options, session persistence settings, session time-lapse settings, as well as for the cookie a variety of settings, such as setting cookie name, path, domain, cookie survival time.

Under normal circumstances, session are stored in memory, when the process is to stop or restart the server when the memory of the session will also be empty, if you set the session persistence feature, the server will be the session to save to your hard drive , when the server process is restarted or the information will be able to be re-used, Weblogic Server supports persistent manner including documents, databases, client-side cookie to save and copy.

Strictly speaking not a persistent copy saved, because the session is actually stored in memory, but the same information is replicated to each server process within a cluster, so that even if a server process to stop working they can still get from other processes to obtain session.

cookie settings will affect the survival time of the browser generates a session cookie whether a cookie. The default is to use a session cookie. Who are interested can use it to test us in the fourth quarter, as mentioned in that misconception.

cookie path for the web application is a very important option, Weblogic Server on the default handling of this option makes it significantly different from other servers. Later we will discuss this issue.

On the session setting reference [5] # 1036869

6, HttpSession Frequently Asked Questions (in this subsection the meaning of the session mixed ⑤ and ⑥)

1, session is created when a common misconception that session in a client visit, was created, but the fact is that until a server-side program called HttpServletRequest.getSession (true) when such a statement is created, note that if the JSP does not show the use of <% @ page session = "false"%> closed session, the JSP files will be automatically compiled into a Servlet when the inclusion of such a statement HttpSession session = HttpServletRequest.getSession (true); This is also the implicit JSP the origins of the object containing the session.

As the session will consume memory resources, so if you do not intend to use the session, should be all of the JSP in turn it off.

2, session is deleted when the integrated preceding discussion, session in the following cases been removed a. procedure call HttpSession.invalidate (); or b. from the last time before the client sends the session id of the session interval of more than super - Set; or c. server process is stopped (non-persistent session)

3, how to do in the browser is closed delete the session
Strictly speaking, can not do this. Can do a little effort to approach clients in all the pages use javascript code to the browser window.oncolose to monitor the closure of action, and then sends a request to the server to delete the session. But the browser crashes, or forcing them to kill the process is still powerless to unconventional means.

4, there's HttpSessionListener how the matter you can create such a listener to monitor the session creation and destruction events, makes such an incident took place when you can do some corresponding work. Note the session creation and destruction of actions trigger listener, rather than the reverse. Similar to the listener with the HttpSession there HttpSessionBindingListener, HttpSessionActivationListener and HttpSessionAttributeListener.

5, stored in session objects must be serializable do is not necessary. Require an object to be serialized session only to be able to be replicated in the cluster can be sustained or preserved, or, where necessary, to exchange server can be temporarily session out of memory. In the Weblogic Server's session can not be serialized in placing an object on the console will receive a warning. I have used a version of iPlanet, if there can not be serialized session objects in the session when there will be a destruction of Exception, very strange.

6, how can the right to meet the client the possibility of cookie ban on all URL to use URL rewriting, including hyperlinks, form of action, and the redirected URL, the specific approach see [6] # 100770

7, open two browser windows to access the application will use the same session or a different session
See the third section of the cookie discussions on the session is to identify only the id does not recognize, so the different browsers, different methods and different windows open the cookie is stored will affect the right answer to this question.

8, how to prevent a user opens two browser windows operating session due to confusion between this issue and to prevent repeated submission of form is similar, you can set the client's token to resolve. Is in the server generates a different id each time returned to the client, while preserving in the session, the client-side form must be submitted to this id also returned to the server, the program first comparison returns id and stored in the session where the values are consistent , and if not then the description of this operation has been submitted before. Can be found in "J2EE Core Model" on the part of the layer model. Should be noted that the use of javascript to open the window, generally do not set the id, or use a separate id, in case the main window, not operational, it is recommended not to open the window operation making changes so that you can do not set up.

9, why Weblogic Server to change the value of the session to re-call after the first session.setValue
This action is mainly done in order to prompt the cluster environment, the value of the Weblogic Server session changed, the need to copy to other server processes the value of the new session.

10, why rule out session gone invalid factors, a normal session, the server will be very little likelihood of its own, although I iPlanet6SP1 plus a number of patches in the Solaris version of the idea is met; the possibility of browser plug-ins followed by , I also encountered the problems caused by plug-ins 3721; theory, a firewall or proxy server in cookie handling could also be a problem.
This problem occurs mostly because of the errors are of a process, the most common is an application to access another application. We discuss this issue in the next section.

7, cross-application sharing session

Often such a situation, a large project divided into a number of small project development, in order to be able to interference from each other, requires that each small project as a separate web application development, but at the end of a sudden they discover a number of small projects is needed between to share some information, or want to use the session to achieve SSO (single sign on), saved in the session the user login information, the most natural requirement is that between applications can access each other's session.

But according to the Servlet specification, session scope should be limited to the role of the current application, different applications can not be exchange of visits between the other's session of the. Each application server, both from a practical effect of compliance with this specification, but the details of implementation might vary, so to resolve cross-application session sharing approach also varies.

First, look at the Tomcat is a web application, how to implement the isolation between the session, from setting the cookie path to run Tomcat, it set a different cookie path for the application is different, so different applications used by the session id are different, so even in the same browser window to access different applications, sent to the server's session id can also be different.

Based on this characteristic, we can speculate Tomcat in the session memory structure as follows.

I previously used iPlanet also used the same way, it is estimated between SunONE and iPlanet will not be much difference. For this type of server to address the idea is very simple, practical implementation of them is not difficult. Either allow all applications to share a session id, or let the application access to other applications of the session id.

iPlanet there is a very simple way to achieve the sharing of a session id, that is, the individual applications of the cookie path is set to / (in fact should be / NASApp, for the application and its role in terms of the equivalent of root).
<path> / NASApp </ path>
</ session-info>

Note that the operation of a shared session should follow the conventions of some programming, such as session attribute name preceded by the prefix of the application, making setAttribute ( "name", "neo") into a setAttribute ( "", "neo"), in order to prevent namespace conflict, leading to another coverage.

In the Tomcat in is not so convenient choice. In the Tomcat version 3, we can also have some means to share the session. Version 4 or above for the Tomcat, now I have not yet found a simple way. With only the strength of a third party, such as the use of documents, databases, JMS, or client-side cookie, URL parameter or hidden field and other means.

Let's look at Weblogic Server is how to handle session of the.

From the screenshot you can see on the screen Weblogic Server applications for all the path set cookie is /, this mean that in the Weblogic Server can share the default session out? However, a small experiment can be demonstrated that even different applications using the same session, individual applications and can only access his own set those attributes. This shows that the Weblogic Server in the session of the memory structure may be as follows

For such a structure, in the session to be solved by the mechanism itself session sharing issue should be impossible. In addition to the strength of the help of a third party, such as the use of documents, databases, JMS, or client-side cookie, URL parameter or hidden fields and other means, there is a more convenient approach is to bring an application's session into the ServletContext, so that Another application can be obtained from the ServletContext reference to the previous application. Sample code is as follows,

Application A
context.setAttribute ( "appA", session);

Application B
contextA = context.getContext ( "/ appA");
HttpSession sessionA = (HttpSession) contextA.getAttribute ( "appA");

It is noteworthy that this use can not be transplanted because under the ServletContext the JavaDoc, application server, for security reasons can be in the context.getContext ( "/ appA"); return null values, the above practice in Weblogic Server 8.1 through.

So why should all of the Weblogic Server applications cookie path is set to / do? The original is to SSO, those who shared in this session of the application programs can share authentication information. A simple experiment you can prove it, modify the first log that the application descriptor weblogic.xml, the cookie path to revised / appA access to another application will be re-required to log on, even if, in turn, first visit the cookie path to as / applications, and then modified the path to visit this, though no longer prompted to log on, but the login user information is lost. Note that this experiment should be used when the authentication FORM, because the browser and web server basic authentication method there are other approaches, the second request for authentication is not achieved through the session. Specifically see [7] secion 14.8 Authorization, you can modify the attached sample programs to do these tests.

8, sum up
session mechanism itself is not complicated, but its implementation and configuration flexibility on the specific situation is made complex. It also requires that we can not just a one time experience or a browser, the server's experience as the experience of universal application, but will always require specific conditions.

This article comes from CSDN blog, reproduced please indicate source: [/ size] [/ size]

  • Rails caused by the speed of Session storage problem 2009-03-19

    At. / Config / environment.rb to remove the following Note: config.action_controller.session_store = :active_record_store Session storage allows the use of active_record_store way to test a very simple request: class QuickReController < ApplicationCont

  • Hibernate Session Introduction 2009-04-13

    First, session interface Session interface hibernate are provided to the application's main interface to manipulate the database, it provides the basic preservation, update, delete, query methods. Two, Session cache Session with a cache, the cache is

  • Hibernate matters submitted - session Affairs. Flush mechanism doubts 2009-04-16


  • Open Session In View 2009-05-04

    In the absence of using Spring to provide the Open Session In View circumstances, because of the need for service (or Dao) layer in the session closed, so lazy loading for true words, it is necessary to put in the application layer of the relationshi

  • Hibernate first 03 classes: Session life-cycle test 2009-05-20

    Since SessionFactory is a heavyweight object, it is better to create only once, therefore, will make a package SessionFactory first type of instrument set up a package to put it. Instrument class name is set to HibernateUtils package net.knight.hiber

  • Session Management in Hibernate 2009-05-22

    Session Management in Hibernate Session management in a variety of programs, ThreadLocal model has been widely used. ThreadLocal in Java are a more specific mechanism for thread binding. ThreadLocal access through the data, is always associated with

  • Hibernate session description of the methods 2009-06-09

    Frequent use of Hibernate will certainly use the session, following session will often use some method to explain the case-by-case Transaction beginTransaction () A working unit and start back a Transaction object associated with the most affairs sta

  • session bean 2009-06-17

    Session bean 1.1 for at least one rule must have a 1.2 session bean business interface type must be concrete, not abstract or final is the 1.3 must have a constructor without parameters in the bean type 1.4 or type in the definition of his father and

  • Hibernate Session to be a stumbling 2009-07-11

    The reasons for writing this blog is for questions and answers yesterday, I channel a problem, the problem is as follows: When the servlet to call the save method of DAO and submitted to the Panel, the console shows the implementation of the sql stat

  • No Hibernate Session bound to thread 2009-07-19

    No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here spring + hibernate insert data, the above error occurred. Solution: join the transaction processing (Declarative Transaction Processing), Co

  • Struts and Hibernate Integration Session and Transaction will be placed in Filter 2009-08-02

    HibernateSessionFactory modify file (this file is from the Hibernate help complete the move of our own): Add the following: private static final ThreadLocal trthreadLocal = new ThreadLocal ();// Services thread / ** * Open Services * / public static

  • JS get session value in the mass of the object from 2009-08-20

    For an object placed in the session scope, and in the JSP pages to extract into the session to the target in the process of development I want to do J2EE programmers are familiar with should be very simple for example: Servlet code: List <String> li

  • Spring + Hibernate in (the owning Session was closed error) 2009-08-23

    Spring control of Hibernate as a result of the life cycle of only data layer and service layer, while the performance of management layers, so there will be the owning Session was closed phenomenon. Needle This point, I passed the hibernate filter to

  • EXT combined with ajax solution acegi failure to submit the question of when the session 2009-08-25

    EXT combined with ajax solution acegi failure to submit the question of when the session

  • DWR call session 2009-09-01

    public Boolean memberExsit(HttpSession session ) { Boolean bool = true; Member member = (Member) session.getAttribute("member"); if (member == null) { // To administrators member = (Member) session.getAttribute("adminaccount"); } if (m

  • DWR obtain information session 2009-09-26

    Recently, we decided to adopt the project features Ajax technology, and finally adopted the DWR. In the use of the DWR, the face of the need to preserve access to the user session information. Internet search of some information, a simple record of t

  • learning hibernate Notes 5 - session.flush () 2009-10-08

    We know that by default hibernate implementation of CRUD in accordance with the save, update, delete the order, why was it so? Because in the call () when, hibernate at the same time the implementation of the session.flush (), this metho

  • Session Xiangjie 2010-03-29

    Source: Internet 1, the term session In my experience, where, session this term is probably second only to the extent of abuse of transaction, even more interesting is the transaction with the session under the meaning in some contexts is the same. s

  • Session Xiangjie (change) 2010-03-29

    Session Xiangjie (change) Abstract: Although the session mechanism in the web application has been adopted for a long time, but there are still a lot of people do not know the nature of session mechanism, as well as the application of this technology

  • Session Session 2010-03-29

    February 24, 2009 Tuesday 18:04 session Session: in the computer, especially in network applications, referred to as "conversation." Session directly translated into Chinese is difficult, generally translated into time domain. In computer scienc