Using Httpsessionlistener and Httpsessionbindinglistener to achieve online demographics

Source: Internet
Author: User

Online statistics of the realization, initially my idea is that the management session, if the session is destroyed on the reduction, if the user has added a new, but if the user illegal exit, such as: not log off, close the browser, etc., this user's session is not managed, Finally decided to use Httpsessionlistener interface or Httpsessionbindinglistener interface to achieve, through the monitoring session of the new and destroyed to control, detailed as follows.

First add the landing page index.jsp

<%@ page contenttype= "Text/html;charset=utf-8"%>    User name:<input type= "text "Name=" username "/>    <br/>    <input type=" Submit "value=" Login "/></form></body></ Html>

Click to jump after landing login.jsp (for convenience, use JSP to do servlet, everyone use when remember to change)

<%@ page contenttype= "text/html;charset=utf-8"%><%@ pageImport= "Java.util.*"%><%request.setcharacterencoding ("UTF-8"); //user name to get logged inString username = request.getparameter ("username"); //Save the user name in the sessionSession.setattribute ("username", username); //put the username into the online listList onlineuserlist = (list) application.getattribute ("Onlineuserlist"); //before first use, you need to initialize    if(Onlineuserlist = =NULL) {onlineuserlist=NewArrayList (); Application.setattribute ("Onlineuserlist", onlineuserlist);    } onlineuserlist.add (username); //SuccessResponse.sendredirect ("result.jsp");%>

login successfully jump to display page result.jsp

 <%@ page contenttype= "text/html;charset=utf-8"%><%@ page iselignored= "false"%><% @page import  = "java.util.List"%> current online User:  <table><%  list onlineuserlist  = (list) application.getattribute ("Onlineuserlist"  for  (int  i = 0; i < Onlineuserlist.size (); I++ = (String) Onlineuserlist.get (i);  %> <tr> <td><%=onlineUsername%></td> </tr><% } %></table> 

Click the Logout page logout.jsp page

 <%@ page contenttype= "text/html;charset=utf-8"%><%@ page import  =    "Java.util.*"%><% //  Get logged in User name     String username = (string) session.getattribute ("username"  //  destroy session      Session.invalidate ();  //  Remove the user name from the online list  list onlineuserlist    = (List) application.getattribute ("Onlineuserlist"  //  successful  Response.sendredirect (" index.jsp " %> 

OK, login, view, logout page all have, below start new listener

1, Httpsessionlistener

Add Class Onlineuserlistener, inherit Httpsessionlistener,httpsessionlistener with two methods sessioncreated (Httpsessionevent event) With sessiondestroyed (Httpsessionevent event), the former is the new listener session, the latter is the destruction of the monitoring session.

The Onlineuserlistener code is as follows:

1  Packagecom.test;2  3 Importjava.util.List;4 ImportJavax.servlet.ServletContext;5 Importjavax.servlet.http.HttpSession;6 Importjavax.servlet.http.HttpSessionEvent;7 ImportJavax.servlet.http.HttpSessionListener;8 /**9  * @authorversionTen  */ One  Public classOnlineuserlistenerImplementsHttpsessionlistener { A   -      Public voidsessioncreated (Httpsessionevent event) { -SYSTEM.OUT.PRINTLN ("New session:" +event.getsession (). GetId ()); the     } -      Public voidsessiondestroyed (Httpsessionevent event) { -HttpSession session =event.getsession (); -ServletContext application =Session.getservletcontext (); +         //user name to get logged in -String username = (string) session.getattribute ("username"); +         //Remove a user name from the online list AList onlineuserlist = (list) application.getattribute ("Onlineuserlist"); at Onlineuserlist.remove (username); -System.out.println (username+ "has quit! "); -     } -}

Web. XML configuration:

<listener>  <listener-class>com.test.onlineuserlistener</listener-class ></listener>

Once the listener discovers that the sessiondestoryed method is called, it will delete its users from the online population, and in the following two cases the Sessiondestoryed event will occur.

A. When executing the Session.invalidate () method

The Session.invalidate () method is called in logout.jsp

B.session Session Timeout

The default timeout event for the session is 30 minutes and the session is automatically destroyed after 30 minutes

2, Httpsessionbindinglistener

Although Httpsessionbindinglistener is called a listener, the method of use is completely different from Httpsessionlistener. Let's actually look at how it's used.

Create a new class Onlineuserbindinglistener, implement the Httpsessionbindinglistener interface, construct the method to pass in the username parameter, There are two methods in the Httpsessionbindinglistener Valuebound (Httpsessionbindingevent event) and Valueunbound (httpsessionbindingevent Event), the former is data binding, the latter is unbound

The so-called data binding session, is called Session.setattribute () to save the Httpsessionbindinglistener into the session.

Take this step in login.jsp:

 <% @page import  = "Com.test.OnlineUserBindingListener"%><%@ page Contenttype= "text/html;charset=utf-8"%><%@ page import  = "java.util.*"% ><% request.setcharacterencoding ( "UTF-8"     );  //  Gets the login user name  String username =       Request.getparameter ("username"  //  Put the username in the online list  Session.setattribute ("Onlineuserbindinglistener", new      Onlineuserbindinglistener (username));  //  successful  Response.sendredirect (" result.jsp " %> 

This is the biggest difference between Httpsessionbindinglistener and Httpsessionlistener: Httpsessionlistener only needs to be set to Web. XML to listen to all sessions in the entire application. Httpsessionbindinglistener must be instantiated and placed in a session before it can be monitored.

From the listening range, the Httpsessionlistener is set to listen to all session,httpsessionbindinglistener at once.

It is this difference that makes the Httpsessionbindinglistener advantage, we can make each listener corresponding to a username, so that does not need to go to the session every time to read username, Further, you can move the code for all the online listings into listener, which is easier to maintain.

The Httpsessionbindinglistener code is as follows:

1  Packagecom.test;2  3 Importjava.util.ArrayList;4 Importjava.util.List;5 ImportJavax.servlet.ServletContext;6 Importjavax.servlet.http.HttpSession;7 Importjavax.servlet.http.HttpSessionBindingEvent;8 ImportJavax.servlet.http.HttpSessionBindingListener;9  Ten  Public classOnlineuserbindinglistenerImplementsHttpsessionbindinglistener { One String username; A       -      PublicOnlineuserbindinglistener (String username) { -          This. username=username; the     } -      Public voidValuebound (Httpsessionbindingevent event) { -HttpSession session =event.getsession (); -ServletContext application =Session.getservletcontext (); +         //put the username into the online list -List onlineuserlist = (list) application.getattribute ("Onlineuserlist"); +         //before first use, you need to initialize A         if(Onlineuserlist = =NULL) { atOnlineuserlist =NewArrayList (); -Application.setattribute ("Onlineuserlist", onlineuserlist); -         } -Onlineuserlist.add ( This. username); -     } -   in      Public voidValueunbound (Httpsessionbindingevent event) { -HttpSession session =event.getsession (); toServletContext application =Session.getservletcontext (); +   -         //Remove a user name from the online list theList onlineuserlist = (list) application.getattribute ("Onlineuserlist"); *Onlineuserlist.remove ( This. username); $System.out.println ( This. Username + "exit. ");Panax Notoginseng   -     } the   +}

Here you can use Listener's username to operate the online list without worrying about the presence of username in the session.

The trigger conditions for Valueunbound are the following three scenarios:

A. When executing session.invalidate ().

B.session times out, automatically when destroyed.

C. Implementation of Session.setattribute ("Onlineuserlistener", "other objects") or Session.removeattribute ("Onlineuserlistener"); When the listener is removed from the session.

Therefore, as long as you do not remove listener from the session, you can listen to the session's destruction.

Achieve online demographics with Httpsessionlistener and Httpsessionbindinglistener

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.