Servlet SESSION Management

xiaoxiao2021-03-06  146

I. Session management mechanism for servlet

According to the design, HTTP is a stateless protocol. It means that the web application does not understand the information about the same user's previous request. One way to maintain session status information is to use the session tracking function provided by the Servlet or JSP container. The Servlet API specification defines a simple HttpSession interface, which we can easily implement session tracking.

The HTTPSession interface provides a method of storing and returning a standard session attribute. Standard session properties such as session identifiers, application data, etc., are saved in the form of "Name-Value" pair. Briefly, the HTTPSession interface provides a standard approach to save objects to memory, extracting these objects in subsequent requests for the same user. The method of saving data in a session is SetAttribute (String S, Object O), and the method of extracting the original saved object from the session is GetAttribute (String S).

Whenever a new user requests a JSP page that uses the HttpSession object, the JSP container has to send a special number to the browser in addition to the response page. This special number is called "session identifier", which is a unique user identifier. Thereafter, the httpsession object resides in memory, waiting for the same user to call its method again.

On the client, the browser saves the session identifier and sends this session identifier to the server in each subsequent request. The session identifier tells the JSP container that the current request is not the first request issued by the user. The server has previously created an HttpSession object for the user. At this point, the JSP container no longer creates a new HttpSession object for the user, but looking for an HttpSession object with the same session identifier and then built the HTTPSession object and the current request.

The session identifier is transmitted between the server and the browser in the form of cookie. If the client does not support cookies, use the URL rewriting mechanism to ensure session identifiers back the server.

Second, session event listens

HttpSessionBindingEvent Class / Definition / Public Class HttpSessionBindingEvent Extends EventObject This event is incorporated in HttpSessionBindingListener when listening to the httpsession binding and cancel binding. This may be a result of session being terminated or identified. The event source is httpsession.putValue or httpsession.removevalue. Constructor PUBLIC HTTPSESSIONBINGEVENT (httpsession session, string name); constructs a new HttpSessionBindingEvent by causing Session of this event and a binding or unbound object name. Method 1, getName public string getName (); returns the name of the object that occurs and unbinds the bound. 2, getsession public httpsession getsession (); returns the name of the Session that occurs and cancels the bound. HTTPSESSIONBINDINGLISTENER Interface Definition / Public Interface HttpSessionBindingListener This object is added to the HTTP SESSION, and the execution of this interface will not be notified to this http session or from this HTTP session to cancel the binding. Method 1, ValueBound Public Void ValueBound (httpsessionBindingEvent Event); This method is called when an object is bound to the session. When the HttpSession.putValue method is called, the servlet engine should call this method. 2, valueunbound public void valueunbound (httpsessionBindingEvent Event); This method is called when an object is unbinded from the session. When the HttpSession.RemoveValue method is called, the Servlet engine should call this method. Session's event handling mechanism is different from the SWING event handling mechanism. Swing uses a registration mechanism, while the session is not; when a session occurs or other events, httpsessionBindingEvent is triggered. If there is an HTTPSessionBindingListener's implementation class in the Servlet container, the event is transmitted to the session listener to the session listener. . In httpsessionBindingEvent, you can get the name of the SESSION that occurs and unbinded through GetSession, and the listener can do more processing accordingly.

Therefore, for the session event listens, simply httpsessionBindingListener.

Added from servlet2.3

HTTPSESSIONEVENT (this is the class representing Event Notifications for Changes To sessions within a web application)

HttpSessionActivationListener (Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated.) HttpSessionAttributeListener (This listener interface can be implemented in order to get notifications of changes to the attribute lists of sessions WITHIN THIS Web Application.)

Different tasks are performed, and the processing is basically the same.

Three, examples (zz)

The meaning of capturing the session event: 1. Record the customer's customer login log (login, exit information, etc.) 2, statistics online number 3, etc. There are still many, huh, huh, you think it is important. Session represents a customer's session process, when you log in, you will pass an object to the Session to track the customer's session. In Servlet, the object that is incompanded if it is an object that implements the HttpSessionBindingListener interface (convenient, this object is called a listener), then when it is incorporated (ie, when calling the setattribute method of the httpsession object) and removed The session object will automatically call the listener valueBound and ValueunBound method (this is the method of the HttpSessionBindingListener interface). It can be seen that the login log is not difficult to achieve. Another problem is how to count online, this problem is a bit different from the login log, statistics online number (and its information), is the statistics now how many session instances exist, we can add a counter (if you want to store more Information, you can use an object to do a counter. In the example, simply play, use an integer variable as a counter, by adding 1, the counter is added to the counter in the valueunbound method, you can implement online Statistics of the number. Of course, this should be used to use the global feature of servletContext. (Refer to the Servlet specification for the narrative of ServletContext), create a new listener and store it into the properties of servletContext to ensure that this listener instance is unique, when the customer logs in, first determined whether the attribute of servletContext is Empty, if not empty, demonstrate that you have created, remove this property into the session, the counter plus 1; if you are empty, create a new listener and store the properties of ServletContext. For example: implement a listener:

// sessionListener.java

Import java.io. *;

Import java.util. *;

Import javax.servlet.http. *;

// Merry the entire process of login Public Class SessionListener Implements httpsessionBindingListener

{

Public String PrivateInfo = ""; // Generate the initialization parameter string of the listener

Private string logstring = ""; // logging string

Private int count = 0; // login number counter

Public sessionListener (String info) {

THIS.PRIVATEINFO = INFO;

}

Public int getCount () {

Return count;

}

Public void valuebound (httpsessionBindingEvent evenet)

{

COUNT ;

IF (PrivateInfo.equals ("count"))

{

Return;

}

Try {

Calendar Calendar = New Gregoriancalendar ();

System.out.println ("Login:" PrivateInfo "Time:" Calendar.getTime ());

Logstring = "/ nlogin:" PrivateInfo "Time:" Calendar.gettime () "/ n";

For (INT i = 1; i <1000; i ) {

File File = New File ("Yeeyoo.log" i);

IF (! (file.exiss ())))

File.createNewFile (); // If the file does not exist, create this file

IF (file.Length ()> 1048576) // If the file is greater than 1M, recreate a file

CONTINUE;

FileOutputStream Foo = New FileoutputStream ("Yeeyoo.log" i, true);

// Open the creation file in Append mode

foo.write (logstring.getbytes (), 0, logstring.length ()); // Write log string

FOO.CLOSE ();

Break; // exit

}

} catch (filenotfoundexception e) {}

Catch (IOException E) {}

}

Public void valueunbound (httpsessionBindingEvent evenet)

{

count -;

IF (PrivateInfo.equals ("count"))

{

Return;

}

Try {

Calendar Calendar = New Gregoriancalendar ();

System.out.println ("Logout:" PrivateInfo "Time:" Calendar.getTime ());

Logstring = "/ nlogout:" PrivateInfo "Time:" Calendar.gettime () "/ n";

For (INT i = 1; i <1000; i ) {

File File = New File ("Yeeyoo.log" i);

IF (! (file.exiss ())))

File.createNewFile (); // If the file does not exist, create this file if (file.Length ()> 1048576) // If the file is greater than 1M, recreate a file

CONTINUE;

FileOutputStream Foo = New FileoutputStream ("Yeeyoo.log" i, true);

// Open the creation file in Append mode

foo.write (logstring.getbytes (), 0, logstring.length ()); // Write log string

FOO.CLOSE ();

Break; // exit

}

} catch (filenotfoundexception e) {}

Catch (IOException E) {}

}

}

Realization of login log: Let's take a look at some of our source code for this listener in our login servlet:

......

HttpSession session = req.getations (TRUE);

......

//

SessionListener sessionListener =

New sessionListener ("IP:" Req.getRemoteAddr ());

// Start a listener for each session

Session.SetaTRibute ("Listener", sessionListener;

// Implant the monitor to httpsession, which will stimulate the listener to call the valuebound method.

/ / Thus log file.

//

When the system exits login, simply call session.removeattribute ("Listener"); you can automatically call the listener's valueunBound method. Or, this method will also be called when session time out is. Statistics of the number of logins:

ServletContext session1 = getServletConfig (). GetServletContext ();

/ / Get a servletContext object instance

IF (sessionListener) session1.getattribute ("Listener1") == NULL)

{

SessionListener sessionListener1 = New sessionListener ("count");

// Only one time, different from the record of the above log file is set each session.

// Launched a global variable when the first client is connected to the server.

// All customers will use the same context.

Session1.setttribute ("Listener1", SessionListener1);

// Take the monitor object to servletContext properties, with global validity,

// All customers can get its instance.

}

Session.setttribute ("Listener1", (SessionListener) Session1.

GetaTtribute ("Listener1"));

/ / Remove this global object and bind this object into a session,

// This will cause the listener to call ValueBound, the counter plus one.

You can use the following code to get the current number of logins at any time in the program:

(SessionListener) Session.getaTribute ("Listener1")). Getcount ()

getCount () is a method of the listener, that is, the value of the current counter is also the number of logins.

转载请注明原文地址:https://www.9cbs.com/read-127899.html

New Post(0)