Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to analyze the Servlet Session Mechanism

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shows you how to analyze the Servlet Session mechanism, the content is concise and easy to understand, it will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

I. session management mechanism of Servlet

The HttpSession interface provides a way to store and return standard session properties. Standard session attributes, such as session identifiers, application data, and so on, are saved in the form of name-value pairs. In short, the HttpSession interface provides a standard way to save objects to memory and extract them from subsequent requests from the same user. The method to save data in a session is setAttribute (String s, Object o), and the method to extract the originally saved object from the session is getAttribute (String s).

Every time a new user requests a JSP page that uses a HttpSession object, the JSP container sends a special number to the browser in addition to sending a response page. This special number is called the session identifier, which is a * * user identifier. After that, the HttpSession object resides in memory and its methods are called again when the same user returns.

On the client side, the browser saves the session identifier and sends the session identifier to the server in each subsequent request. The session identifier tells the JSP container that the current request is not a * request from a user for whom the server has previously created a HttpSession object. At this point, instead of creating a new HttpSession object for the user, the JSP container looks for a HttpSession object with the same session identifier and then associates the HttpSession object with the current request.

The session identifier is passed between the server and the browser in the form of Cookie. If the client does not support cookie, the url rewriting mechanism is used to ensure that the session identifier is passed back to the server.

II. Servlet Session event listening

HttpSessionBindingEvent class\

Definition\

Public class HttpSessionBindingEvent extends EventObject

This event connects to HttpSession when it is heard that binding and unbinding occurs in HttpSessionBindingListener. This may be the result of a session being terminated or found to be invalid.

The event source is HttpSession.putValue or HttpSession.removeValue.

Constructor function

Public HttpSessionBindingEvent (HttpSession session, String name)

Construct a new HttpSessionBindingEvent from the Session that caused the event and the name of the object that was bound or unbound.

Method

1 、 getName

Public String getName ()

Returns the name of the object on which binding and unbinding occurred.

2 、 getSession

Public HttpSession getSession ()

Returns the name of the session where binding and unbinding occurred.

HttpSessionBindingListener interface

Definition\

Public interface HttpSessionBindingListener

This object is added to the session of the HTTP, and executing this interface will inform you whether any objects have been bound to or unbound from the HTTP session.

Method

1 、 valueBound

Public void valueBound (HttpSessionBindingEvent event)

This method is called when an object is bound to session. The Servlet engine should call the HttpSession.putValue method when it is called.

2 、 valueUnbound

Public void valueUnbound (HttpSessionBindingEvent event)

This method is called when an object is unbound from the session. The Servlet engine should call the HttpSession.removeValue method when it is called.

The event handling mechanism of Session is different from that of swing. Swing uses the registration mechanism, but session does not; when binding or other events occur in any session, HttpSessionBindingEvent will be triggered. If there is an implementation class of HttpSessionBindingListener in the servlet container, the event will be passed as a parameter to the implementation class of the session listener. In HttpSessionBindingEvent, you can get the name of the session that binds and unbinds through getsession, and listeners can do more processing accordingly.

Therefore, to listen for session events, you only need to implement HttpSessionBindingListener.

Increased 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.)

Perform different tasks and deal with basically the same.

3. Example (zz)

The meaning of capturing Servlet Session events:

1. Record the customer login log of the website (login, exit information, etc.)

2. Count the number of people online

3. Wait, there are many more, hehe, think for yourself. Anyway, it's important.

Session represents the customer's session process. When the customer logs in, an object is passed into the Session to track the customer's session. In Servlet, if the object passed in Session is an object that implements the HttpSessionBindingListener interface (for convenience, this object is called a listener), then when it is passed in (that is, when the setAttribute method of the HttpSession object is called) and when it is removed (that is, when the removeAttribute method of the HttpSession object is called or Session Time out is called), the Session object will automatically call the listener's valueBound and valueUnbound methods (which are the methods in the HttpSessionBindingListener interface). From this, the login log is not difficult to implement.

Another problem is how to count the number of people online, which is slightly different from implementing the login log, counting the number of people online (and its information), that is, counting how many Session instances exist now, we can add a counter (if you want to store more information, you can use an object as a counter, and in the example given later, use an integer variable as a counter) The statistics of the number of people online can be realized by adding a counter minus 1 in the valueBound method. Of course, this takes advantage of the global features of ServletContext. (for the description of ServletContext, please refer to the Servlet specification), create a new listener and store its instance in the property of ServletContext to ensure the * nature of the listener instance. When the customer logs in, first determine whether this property of ServletContext is empty. If not, prove that it has been created, directly take this property out and put it in Session, and add 1 to the counter. If it is empty, create a new listener and store it in the attribute of ServletContext.

Examples are as follows:

Implement a listener:

/ / SessionListener.java

Import java.io.*

Import java.util.*

Import javax.servlet.http.*

/ / listen to the whole process of login

Public class SessionListener implements HttpSessionBindingListener

{

Public String privateInfo= ""; / / generate the initialization parameter string for the listener

Private String logString= ""; / / logging string

Private int count=0; / / logon count

Public SessionListener (String info) {

This.privateInfo=info

}

Public int getCount () {

Return count

}

Public void valueBound (HttpSessionBindingEvent event)

{

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 iaccoun1telli1048576) / / if the file is larger than 1m, recreate a file

Continue

FileOutputStream foo=new FileOutputStream ("yeeyoo.log" + iJing true)

/ / Open the creation file in append mode

Foo.write (logString.getBytes (), 0PowerLog String.length ()); / / write log string

Foo.close ()

Break;// exit

}

} catch (FileNotFoundException e) {}

Catch (IOException e) {}

}

Public void valueUnbound (HttpSessionBindingEvent event)

{

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 iaccoun1telli1048576) / / if the file is larger than 1m, recreate a file

Continue

FileOutputStream foo=new FileOutputStream ("yeeyoo.log" + iJing true)

/ / Open the creation file in append mode

Foo.write (logString.getBytes (), 0PowerLog String.length ()); / / write log string

Foo.close ()

Break;// exit

}

} catch (FileNotFoundException e) {}

Catch (IOException e) {}

}

}

Implementation of login log:

Let's take a look at some of the source code for using this listener in our login Servlet:

……

HttpSession session = req.getSession (true)

……

/

SessionListener sessionListener=

New SessionListener ("IP:" + req.getRemoteAddr ())

/ / start a listener for each session

Session.setAttribute ("listener", sessionListener)

/ / implant the listener into the HttpSession, which will trigger the listener to call the valueBound method

/ / to record the log file.

/

When the system logs out, simply call session.removeAttribute ("listener")

The valueUnbound method of the listener can be called automatically. Or, this method is also called when Session Time Out.

Statistics on the number of logins:

ServletContext session1=getServletConfig () .getServletContext ()

/ / get ServletContext object instance

If ((SessionListener) session1.getAttribute ("listener1") = = null)

{

SessionListener sessionListener1=new SessionListener ("count")

/ / set it only once, which is different from the record of the log file above, which is set for each session.

/ / that is, start a global variable when * clients connect to the server

/ / all customers will use the same context thereafter.

Session1.setAttribute ("listener1", sessionListener1)

/ / set the listener object to the property of ServletContext, which has global scope validity.

/ / that is, all customers can obtain its example.

}

Session.setAttribute ("listener1", (SessionListener) session1.

GetAttribute ("listener1"))

/ / take out this global object and bind it to a session

/ / this will prompt the listener to call valueBound and increment the counter by one.

The current number of logins can be obtained at any time in subsequent programs with the following code:

((SessionListener) session.getAttribute ("listener1")) .getCount ()

GetCount () in Servlet Session is a way for listeners to get the value of the current counter, which is the number of logins.

The above is how to analyze the Servlet Session mechanism. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report