Use the httpsessionlistener interface to listen for session creation and Invalidation

Source: Internet
Author: User

Httpsessionlistener:
A session creation event occurs every time a new session is created. Similarly, a session failure event occurs when a session fails.
This interface also contains only two methods, corresponding to session creation and invalidation: # public void sessioncreated (httpsessionevent SE); # public void sessiondestroyed (httpsessionevent SE );

 

How many users are using my web application?

 

Statistics on the number of online users are often required on websites. In the past, the usual practice was to combine the login and exit functions, that is, when the user enters the user name and password for login, the counter is added with 1, and then when the user clicks the exit button to exit the system, the counter is reduced by 1. This processing method has some disadvantages. For example, after a user logs on normally, the user may forget to click the exit button and directly close the browser. As a result, the operations on the counter minus 1 are not performed in time; the website often has some content that can be accessed without logon. In this case, the above method cannot be used for online statistics. We can use the event listener defined in the servlet specification to solve this problem and achieve more accurate online count statistics. For each user being accessed, the J2EE Application Server creates an httpsession object for the user. When a browser accesses a website for the first time, the J2EE Application Server creates an httpsession object and triggers an httpsession creation event. If an httpsessionlistener event listener is registered, the sessioncreated method of the httpsessionlistener event listener is called. On the contrary, when the browser access ends, the J2EE application server will destroy the corresponding httpsession object, trigger the httpsession destruction event, and call the sessiondestroyed method of the registered httpsessionlistener event listener.

 

Java code
  1. Import javax. servlet. http. httpsessionlistener;
  2. Import javax. servlet. http. httpsessionevent;
  3. Public class sessioncounter implements httpsessionlistener {
  4. Private Static int activesessions = 0;
  5. /* Session creation event */
  6. Public void sessioncreated (httpsessionevent SE ){
  7. Servletcontext CTX = event. getsession (). getservletcontext ();
  8. Integer numsessions = (integer) CTX. getattribute ("numsessions ");
  9. If (numsessions = NULL ){
  10. Numsessions = new INTEGER (1 );
  11. }
  12. Else {
  13. Int COUNT = numsessions. intvalue ();
  14. Numsessions = new INTEGER (count + 1 );
  15. }
  16. CTX. setattribute ("numsessions", numsessions );
  17. }
  18. /* Session failure event */
  19. Public void sessiondestroyed (httpsessionevent SE ){
  20. Servletcontext CTX = Se. getsession (). getservletcontext ();
  21. Integer numsessions = (integer) CTX. getattribute ("numsessions ");
  22. <SPAN class = "oblog_text"> If (numsessions = NULL)
  23. Numsessions = new INTEGER (0 );
  24. }
  25. Else {
  26. Int COUNT = numsessions. intvalue ();
  27. Numsessions = new INTEGER (count-1 );
  28. }
  29. CTX. setattribute ("numsessions", numsessions); </span>
  30. }
  31. }
Import javax. servlet. HTTP. httpsessionlistener; import javax. servlet. HTTP. httpsessionevent; public class sessioncounter implements httpsessionlistener {Private Static int activesessions = 0;/* session creation event */Public void sessioncreated (httpsessionevent SE) {servletcontext CTX = event. getsession (). getservletcontext (); integer numsessions = (integer) CTX. getattribute ("numsessions"); If (numsessions = NULL) {numsessions = new INTEGER (1);} else {int COUNT = numsessions. intvalue (); numsessions = new INTEGER (count + 1);} CTX. setattribute ("numsessions", numsessions);}/* session failure event */Public void sessiondestroyed (httpsessionevent SE) {servletcontext CTX = Se. getsession (). getservletcontext (); integer numsessions = (integer) CTX. getattribute ("numsessions"); If (numsessions = NULL) numsessions = new INTEGER (0);} else {int COUNT = numsessions. intvalue (); numsessions = new INTEGER (count-1);} CTX. setattribute ("numsessions", numsessions );}}

In this solution, the sessioncounter class will be notified when any session is created or destroyed. Of course, the reason for the notification is that related configuration work must be performed in the web. xml file. The configuration code is as follows:

Java code
  1. <Listener>
  2. <Listener-class> demo. listener. sessioncounter </listener-class>
  3. </Listener>
  <listener>      <listener-class>demo.listener.SessionCounter</listener-class>  </listener>

In the following two cases, the sessiondestoryed (Session destruction) event occurs: 1. When the session. invalidate () method is executed. Since logoutservlet. execute session in Java. during invalidate (), sessiondestory () is triggered to clear the current user from the online user list. the online list is operated in Java, so logoutservlet. the Java content is now like this.

Java code
  1. Public void doget (httpservletrequest request, httpservletresponse response)
  2. Throws servletexception, ioexception {
  3. // Destroy the session
  4. Request. getsession (). invalidate ();
  5. // Succeeded
  6. Response. sendredirect ("index. jsp ");
  7. }
Public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {// destroy Session Request. getsession (). invalidate (); // response. sendredirect ("index. JSP ");}

 

2. If the user does not access the server for a long time and exceeds the maximum Session Timeout time, the server will automatically destroy the timeout session. You can set the Session Timeout value in Web. xml. To make it easy to see the timeout effect, we set the timeout value to the minimum value.

Java code
  1. <Session-config>
  2. <Session-Timeout> 1 </session-Timeout>
  3. </Session-config>
      <session-config>          <session-timeout>1</session-timeout>      </session-config>

 

The unit of time is one minute and can only be an integer. If it is zero or negative, the session will never time out.

 

2. httpsessionevent

This is a notification of session change events in a web application.

 

Java code
  1. Public class shopsessionlistener implements httpsessionlistener {
  2. Public void sessioncreated (httpsessionevent SE ){
  3. }
  4. Public void sessiondestroyed (httpsessionevent SE ){
  5. String sessionid = Se. getsession (). GETID ();
  6. Eopsite site = (eopsite) threadcontextholder. getsessioncontext (). getattribute ("site_key ");
  7. If (site! = NULL ){
  8. Icartmanager cartmanager = springcontextholder. getbean ("cartmanager ");
  9. Cartmanager. Clean (sessionid, site. getuserid (), site. GETID ());
  10. }
  11. }
  12. }
public class ShopSessionListener implements HttpSessionListener {public void sessionCreated(HttpSessionEvent se) {}public void sessionDestroyed(HttpSessionEvent se) {String sessionid = se.getSession().getId();EopSite site  =(EopSite)ThreadContextHolder.getSessionContext().getAttribute("site_key");if(site!=null){ICartManager cartManager = SpringContextHolder.getBean("cartManager");cartManager.clean(sessionid,site.getUserid(),site.getId());}}}

 

Se. getsession (). GETID ();

GETID () in the httpsession interface ():

Returns a string containing the unique identifier assigned to this session.

Returns a string that contains a unique identifier allocated to this session.

 

 


 

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.