Javax. servlet. http. HttpSession session usage

Source: Internet
Author: User

Javax. servlet. http. HttpSession session usage

The HttpSession class provides the setAttribute () and getAttribute () Methods to store and retrieve objects.

HttpSession provides a session ID keyword. A client participating in session behavior is stored in the same session request.

And return it. The servlet engine searches for appropriate session objects and makes them available to the current request. HttpServletRequest

The interface provides the following methods to obtain an HttpSession instance.

Public HttpSession getSession (): This method gets the Session of the request.

Public HttpSession getSession (Boolean create): returns the Session of the current request. If the current request is not

If it belongs to any session and the create parameter is true, a session is created. Otherwise, null is returned. All

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


Method
Introduction
 
Public void setAttribute (String name, Object value)
Bind the value object to the session with the name
 
Public object getAttribute (String name)
Obtains the property value of name. If the property does not exist, null is returned.
 
Public void removeAttribute (String name)
Delete the name attribute from the session. If the attribute does not exist, it will not be executed or thrown an error.
 
Public Enumeration getAttributeNames ()
Returns the enumerated values related to the session.
 
Public void invalidate ()
Invalidates sessions and deletes attribute objects.
 
Public Boolean isNew ()
Used to check whether the current customer is a new session
 
Public long getCreationTime ()
Returns the session creation time.
 
Public long getLastAccessedTime ()
Returns the time when the web Container receives the client's final request within the session time.
 
Public int getMaxInactiveInterval ()
Returns the maximum time (in seconds) requested by the customer during the session.
 
Public void setMasInactiveInterval (int seconds)
Maximum time allowed for client requests
 
ServletContext getServletContext ()
Returns the context of the current session. The ServletContext object allows the Servlet to communicate with the web container.
 
Public String getId ()
Returns the identification number during the session.
 


HttpSession is the Java platform's Implementation specification for the session mechanism, because it is only an interface, specific to each

In addition to standard support, web application server providers still have minor differences that are not specified in some specifications.

Here we use the Weblogic Server8.1 of BEA as an example.

Weblogic Server provides a series of parameters to control the implementation of its HttpSession, including

Cookie switch option, use the URL rewrite switch option, session persistence settings, session expiration time

Settings, as well as various settings for cookies, such as setting the cookie name, path, domain, and cookie survival time

.

Generally, sessions are stored in the memory. When the server process is stopped or restarted

The session will also be cleared. If the session persistence feature is set, the server will save the session to hard

On the disk, when the Server process is restarted or the information can be used again, the persistence supported by Weblogic Server

Methods include file, database tutorial, saving and copying client cookies.

Replication is not stored persistently, because the session is actually stored in the memory, but the same information

Copied to the server processes in each cluster, so that even if a server process stops working

The session is obtained in the process.

The cookie survival time setting affects whether the cookie generated by the browser is a session cookie. By default

Use session cookies. If you are interested, you can use it to test the misunderstanding we mentioned in section 4.

The cookie Path is a very important option for web applications.

The default Processing Method of items makes it significantly different from other servers. We will discuss this topic later.

For more information about session settings, see [5] http: // e-

Docs.bea.com/wls/docs70/webapp/weblogic_xml.html?10=69

Vi. HttpSession FAQs

(In this section, the session meaning is a mixture of 5 and 6)

1. When the session is created

A common misunderstanding is that the session is created when a client accesses it. However, the fact is that the session is created until a server

The program is created only when it calls a statement such as HttpServletRequest. getSession (true). Note that if the JSP does not

When the displayed session is closed using <% @ page session = "false" %>, the JSP file will be

Automatically add such a statement HttpSession session = HttpServletRequest. getSession (true );

It is also the source of the implicit session Object in JSP.

Because the session will consume memory resources, if you do not plan to use the session, you should disable it in all JSPs.

It.

2. When the session is deleted

Based on the previous discussion, the session is deleted in the following cases. a. program calls HttpSession. invalidate ();

Or B. The interval between the last session id sent by the client and the previous session id exceeds the session Timeout setting; or c. Service

The process is stopped (non-persistent session)

3. How to delete a session when the browser is closed

Strictly speaking, this cannot be done. You can try to use it on all client pages.

The special effect code window. onclose of the webpage monitors the closing action of the browser, and then sends a request to the server to delete

Except session. However, there is no way to break down the browser or forcibly kill the process.

4. Why is there an HttpSessionListener?

You can create listener to monitor the creation and destruction events of sessions, so that when such events occur

You can do some corresponding work. Note that the listener action is triggered by the session creation and destruction, rather than the opposite.

Similar listener related to HttpSession and HttpSessionBindingListener,

HttpSessionActivationListener and HttpSessionAttributeListener.

5. Must the objects stored in the session be serializable?

Not required. Object serialization is required only for the session to be copied in the cluster or saved permanently.

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

A non-serializable object will receive a warning on the console. If one of the iPlanet versions I have used

The session contains non-serializable objects. An Exception occurs when the session is destroyed, which is strange.

6. How can I properly handle the possibility of disabling cookies on the client?

Use URL rewriting for all URLs, including hyperlinks, form actions, and redirection URLs. For more information, see

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

7. Opening two browser windows to access the application will use the same session or different sessions

For more information about cookie, see section 3. For session, only id is not recognized. Therefore, different browsers do not

The same window opening method and different cookie storage methods will affect the answer to this question.

8. How to Prevent session confusion caused by opening two browser windows?

This problem is similar to preventing forms from being submitted multiple times. It can be solved by setting the token of the client. Is in the server

Each time the server generates a different id and returns it to the client and saves it in the session, the client must submit the form

Returns this id to the server. The program first checks whether the returned id is consistent with the value saved in the session.

Therefore, this operation has been submitted. See the section on presentation layer in J2EE Core mode. Yes

Note that this id is not set for the window opened by using javascript window. open, or

Unique id, in case the main window cannot be operated, it is recommended that you do not modify the window opened by window. open, so that

You do not need to set it.

9. Why do I need to call session. setValue again after changing the session value in Weblogic Server?
The main purpose of this operation is to prompt that the Weblogic Server session value has changed in the cluster environment.

Copy a new session value to another server process.

10. Why does the session disappear?

In addition to excluding the normal failure of the session, the server itself may be very unlikely.

IPlanet6SP1 has also been used in Solaris versions with several patches; browser plug-ins are more likely, and I have also met

Problems caused by over 3721 plug-ins; theoretically, the firewall or proxy server may also ask questions about cookie processing.

Question.

Most of the reasons for this problem are program errors. The most common reason is to access another

Another application. We will discuss this issue in the next section.

7. Cross-Application session sharing

In this case, a large project is divided into several small projects for development.

A small project is developed as a separate web application, but in the end, it suddenly finds that a few small projects need

Share some information, or use session to implement SSO (single sign on ).

The most natural requirement of user information is that applications can access each other's sessions.

However, according to the Servlet specification, the scope of the session should be limited to different applications under the current application.

Programs cannot access each other's sessions. Each application server follows this principle in terms of actual results.

Specification, but the implementation details may vary. Therefore, the methods for cross-application session sharing are also different.

.

First, let's take a look at how Tomcat isolates sessions between web applications.

The cookie Path is different for different applications.

The session IDs are different, so even if you access different applications in the same browser window

The session IDs of the server can also be different.

Session details

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

Session details

I used iPlanet in the past in the same way. It is estimated that SunONE and iPlanet will not be too large.

. For servers in this way, the solution is simple and practical. Either let all

The application shares a session id, or allows the application to obtain the session id of other applications.

IPlanet has a very simple way to share a session id, that is,

The cookie Path is set to/(in fact, it should be/NASApp, which serves as the root for the application ).

<Session-info>
<Path>/NASApp </path>
</Session-info>

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

Add the application prefix before the name, so that setAttribute ("name", "neo") becomes setAttribute

("App1.name", "neo") to prevent namespace conflicts and overwrite each other.


In Tomcat, there is no such convenient choice. In Tomcat version 3, we can also share some methods.

Session. For Tomcat Versions later than version 4, I have not found a simple method. Only by third parties

Volume, such as using files, databases, JMS or client cookies, URL parameters, hidden fields, and other hand segments.

Let's take a look at how Weblogic Server Processes sessions.

Session details

Session details

From the screenshot, we can see that the Weblogic Server sets the/cookie Path for all applications /,

Does this mean that the session can be shared by default on Weblogic Server? However, a small experiment is enough.

It is proved that even if different applications use the same session, each application can only access its own settings.

. This indicates that the memory structure of the session in Weblogic Server may be as follows:

Session details

For such a structure, it is impossible to solve the session Sharing Problem in the session mechanism itself.

. In addition to the power of third parties, such as using files, databases, JMS or client cookies, URL parameters, or

Another convenient way is to put the session of an application

In ServletContext, another application can obtain the previous application from ServletContext.

. The sample code is as follows,

Application

Context. setAttribute ("appA", session );

Application B

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

It is worth noting that this usage cannot be transplanted, because according to the JavaDoc of ServletContext, the application server can

For security reasons, context. getContext ("/appA"); returns a null value.

8.1.

So why does Weblogic Server set the cookie Path of all applications? Originally

SSO: any application that shares this session can share the authentication information. A simple experiment proves

Modify the weblogic. xml descriptor of the application that is logged on first, and change the cookie Path to/appA.

When you access another application, you are requested to log on again. In turn, you can first access the application whose cookie Path is,

If you attempt to access the modified path, you will not be prompted to log on again, but the user information will be lost. Pay attention to this

In the experiment, the authentication method should use FORM, because browsers and web servers have other processing methods for basic authentication.

The authentication for the second request is not implemented through the session. For details, see [7] secion 14.8

Authorization, you can modify the attached sample program to perform 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.