Javax.servlet.http.HttpSession Session Usage Detailed

Source: Internet
Author: User
Tags session id object serialization sessions time interval tomcat

Javax.servlet.http.HttpSession Session Usage Detailed

HttpSession class It provides the SetAttribute () and GetAttribute () methods to store and retrieve objects.

HttpSession provides a session ID keyword, where a client participating in a session behavior is stored in a request for the same session

and return it. The servlet engine looks for the appropriate session object and makes it available to the current request. HttpServletRequest

Interface provides the following methods to obtain the HttpSession instance.

Public HttpSession getsession (): This method obtains the session where the request resides.

Public HttpSession getsession (Boolean Create): Returns the session of the current request. If the current request does not

belongs to any session, and the Create parameter is true, a session is created, or null is returned. Thereafter all from the same

A request belongs to this session, and the current session is returned through its getsession.


Method
Introduced

public void setattribute (String name,object value)
Bind a value object to a session with a name name

public Object GetAttribute (String name)
Gets the property value of name and returns NULL if the property does not exist

public void RemoveAttribute (String name)
Removes the Name property from the session and does not throw an error if it does not exist.

Public enumeration Getattributenames ()
Returns the and session-related enumeration values

public void Invalidate ()
Invalidates the session while deleting the Property object

Public Boolean isnew ()
Used to detect whether the current customer is a new session

Public long GetCreationTime ()
return session creation Time

Public long Getlastaccessedtime ()
Returns the time that the Web container received the last request from the customer during session time

public int Getmaxinactiveinterval ()
Returns the maximum time that a customer requests during a session. seconds

public void Setmasinactiveinterval (int seconds)
Maximum time allowed for customer requests

ServletContext Getservletcontext ()
Returns the context of the current session in which the ServletContext object enables the servlet to communicate with the Web container

Public String getId ()
Returns the identification number during a session


HttpSession is the Java Platform implementation of the session mechanism specification, because it is only an interface, specific to each

Web application server providers, in addition to the specification support, there will still be some specifications are not defined in the subtle differences.

Here we demonstrate it as an example of Bea's WebLogic Server8.1.

First, Weblogic server provides a series of parameters to control its HttpSession implementation, including the use of

Cookie switch option, use URL rewrite switch option, session persistence setting, session Expiration time

Settings, and various settings for cookies, such as setting the name of the cookie, the path, the domain, and the lifetime of the cookie

Wait

In general, sessions are stored in memory, and when the server process is stopped or restarted, the memory

Session is also emptied, and if the persistence feature is set, the server will save the session to a hard

Disk, when the server process restarts or this information will be able to be used again, the persistence of Weblogic server support

Methods include file, database tutorial, client cookie Save and copy.

Replication is strictly not a persistent save because the session is actually stored in memory, but the same information

is replicated to the server process within each cluster, so that even if a server process stops working, it can still be removed from its

He made a session in the process.

The cookie lifetime setting affects whether the browser-generated cookie is a session cookie. The default is to make

With the session cookie. Interested can use it to test the misunderstanding we mentioned in the fourth quarter.

The path to the cookie is a very important option for the Web application, Weblogic server

The default handling of an item makes it significantly different from other servers. We'll have a discussion later.

About setting the session reference [5] http://e-

docs.bea.com/wls/docs70/webapp/weblogic_xml.html#1036869

Vi. httpsession FAQ

(The meaning of the session in this section is the blending of ⑤ and ⑥)

1, when the session was created

A common misconception is that the session is created when there is client access, but the fact is that until the server side

When a program calls a statement such as Httpservletrequest.getsession (true), note that if the JSP does not

The display uses <% @page session= "false"%> closes the session, and the JSP file is translated into a servlet

Automatically add such a statement httpsession session = Httpservletrequest.getsession (true);

JSP is also implied in the history of the session object.

Because session consumes memory resources, if you do not intend to use sessions, you should close them in all JSPs

It.

2, when the session was deleted

To synthesize the previous discussion, the session is deleted under the following circumstances a. Program calls Httpsession.invalidate ();

or B. Distance last received the session ID time interval sent by the client exceeds the timeout setting for sessions, or C. Services

The process of the device is stopped (non persistent session)

3, how to do when the browser is closed to delete session

Strictly speaking, this is not to be done. The best way to do this is to use it on all client pages.

Web page effects code window.onclose to monitor the browser's shutdown action, and then send a request to the server to delete

except session. But there is still nothing to do about the browser crashing or the forced killing of the process by unconventional means.

4, what's going on with a httpsessionlistener?

You can create such listener to monitor session creation and destruction events so that when such events occur

You can do some work accordingly. Note that the creation and destruction actions of the session trigger the listener, not the other way around.

Similar to the httpsession-related listener and Httpsessionbindinglistener,

Httpsessionactivationlistener and Httpsessionattributelistener.

5, the object stored in the session must be serializable?

are not required. Object serialization is required only for session to be replicated in the cluster or to be persisted

Or, if necessary, the server can swap session memory temporarily. Place in session of WebLogic Server

An object that is not serializable receives a warning on the console. One of the iplanet versions that I've used if

There is an object in the session that is not serializable, and it is strange to have a exception when it is destroyed.

6, how to correctly deal with the possibility of the client to prohibit cookies

Use URL overrides for all URLs, including hyperlinks, form actions, and redirected URLs, as described in

[6]
http://e-docs.bea.com/wls/docs70/webapp/sessions.html#100770

7, open two browser window to access the application will use the same session or different sessions

See the third section of the discussion of cookies, for the session is only ID not identify, so different browsers, not

The same way windows are opened and how different cookies are stored will have an impact on the answer to this question.

8, how to prevent users to open two browser window operation caused by session confusion

This problem is similar to preventing the form from being submitted multiple times, and can be resolved by setting the client's token. It's in the costume.

Each time a different ID is generated, it is returned to the client and stored in the session, and the client submits the form must

This ID is also returned to the server, the program first compares the returned ID and saved in the session value is consistent, if not

It is stated that this operation has been submitted. You can see the section on the presentation layer pattern in the Java EE core model. Need

Note that for Windows that are open using JavaScript window.open, this ID is not normally set, or the single

Single ID, in case the main window cannot operate, we recommend that you do not window.open open window to do the modification, so

Can not be set.

9, why change the value of the session in WebLogic server to call again Session.setvalue
This action is done primarily to prompt for a change in the value of the WebLogic Server session in a clustered environment, requiring

Copy the new session value to the other server process.

10, why the session disappeared

Excluding the normal failure of the session, the possibility of the server itself should be negligible, although the author in

IPLANET6SP1 has also been encountered with a number of patches on the Solaris version, the possibility of browser Plug-ins is the second, the author also met

Problems caused by the 3721 plug-ins; Theoretically, the firewall or proxy server may also appear in the cookie processing to ask

Problem.

Most of the reasons for this problem are program errors, most often in one application to access the other

An external application. We'll discuss the issue in the next section.

Seven, cross-application session sharing

It is often the case that a large project is segmented into several small projects, in order to be able to interfere with each other, requiring each

Small project as a separate Web application development, but at the end suddenly found a few small projects between the need

Share some information, or want to use the session to implement SSO (Single Sign On), and save the login's

The most natural requirement for user information is access to each other's sessions between applications.

However, according to the servlet specification, the scope of the session should be limited to the current application, with different applications

Programs are not able to access each other's session. Each application server has actually complied with this

Specification, but the details of the implementation may vary, so there are different ways to resolve shared sessions across applications

Let's start by looking at how Tomcat implements session isolation between Web applications, from Tomcat settings

Cookie path, it is different for the cookie path for different application settings, so that different applications

The session ID used is different, so even if you are accessing a different application in the same browser window, send it to the service

The session ID of the service can also be different.

Session Detailed session detailed

Based on this feature, we can speculate that the memory structure of the session in Tomcat is roughly as follows.

Session detailed

The author used the iplanet also used the same way, estimated SunOne and iplanet will not be too big

The difference. For this kind of server, the solution of the idea is very simple, the actual implementation is not difficult. or let all the

The application shares a session ID or allows the application to obtain the session ID of another application.

There is a very simple way to implement sharing a session ID in iplanet, which is to put the individual application

The cookie path is set to/(in fact,/nasapp, which acts as the root for the application).

<session-info>
<path>/NASApp</path>
</session-info>

It should be noted that the session of the operation share should follow some programming conventions, such as in the session attribute

The prefix of the first name with the application, making setattribute ("name", "Neo") into setattribute

("App1.name", "Neo") to prevent namespace collisions, resulting in overwriting each other.


In Tomcat, there is no such a convenient choice. On Tomcat version 3, we can also have some means to share

Session For Tomcat above version 4, the author has not yet found a simple solution. Can only use the force of a third party

, such as using files, databases, JMS, or client cookie,url parameters or hidden fields.

Let's take a look at how WebLogic server handles sessions.

Session detailed

Session detailed

You can see from the screen screen that the WebLogic server has a path to all cookies that are set by the application.

Does this mean that you can share the session by default in WebLogic server? However, a small experiment can

Prove that even if different applications are using the same session, each application can still only access its own set

Of those attributes. This indicates that the memory structure of the session in WebLogic server may be as follows

Session detailed

For such a structure, it should be impossible to solve the session sharing problem in the session mechanism itself.

。 In addition to relying on third-party power, such as using files, databases, JMS, or client cookie,url parameters or

Hidden fields and other means, there is a more convenient way to put an application session to

ServletContext so that another application can get the previous application from the ServletContext

The reference. The 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 usage is not portable, because according to ServletContext's Javadoc, the application server can

For security reasons for Context.getcontext ("/appa"); return null value, the above practice is in WebLogic Server

8.1 In the passage.

So why would WebLogic server set all the cookie paths for all applications to/? It turns out to be

SSO, any application that shares this session can share authenticated information. A simple experiment will prove

This, modify the descriptor Weblogic.xml of the application that first logs in, and modify the cookie path to/appa

Accessing another application will require a login again, even if it is the reverse, access the application with the cookie path.

Access to this modified path, although no longer prompt for login, but logged in user information will also be lost. Pay attention to this.

The authentication method should use form when the experiment, because the browser and Web server have other ways to deal with the Basic authentication method

, the second request authentication is not implemented through session. Please refer to [7] secion 14.8 for details.

Authorization, you can modify the attached sample program to do these experiments.

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.