Javaweb Learning Summary (11)-The application of the Listener (Listener) in the development

Source: Internet
Author: User

Listeners use more in javaweb development, and the following is a common application of the Listener (Listener) in development

I. Statistics of the current number of people online

In Javaweb application development, sometimes we need to count the number of users currently online, so we can use listener technology to implement this feature.

 PackageMe.gacl.web.listener;ImportJavax.servlet.ServletContext;Importjavax.servlet.http.HttpSessionEvent;ImportJavax.servlet.http.HttpSessionListener;/*** @ClassName: onlinecountlistener* @Description: Count the number of users currently online *@author: Aloof and Pale wolf * @date: 2014-9-10 pm 10:01:26**/  Public classOnlinecountlistenerImplementsHttpsessionlistener {@Override Public voidsessioncreated (httpsessionevent se) {servletcontext context=se.getsession (). Getservletcontext (); Integer Onlinecount= (Integer) context.getattribute ("Onlinecount"); if(onlinecount==NULL) {Context.setattribute ("Onlinecount", 1); }Else{Onlinecount++; Context.setattribute ("Onlinecount", Onlinecount); }} @Override Public voidsessiondestroyed (httpsessionevent se) {servletcontext context=se.getsession (). Getservletcontext (); Integer Onlinecount= (Integer) context.getattribute ("Onlinecount"); if(onlinecount==NULL) {Context.setattribute ("Onlinecount", 1); }Else{Onlinecount--; Context.setattribute ("Onlinecount", Onlinecount); }    }}
Second, custom session scanner

When a Web application creates a lot of sessions, in order to avoid the session taking up too much memory, we can choose to manually destroy these memory sessions, then it can also be achieved by using listener technology.

 PackageMe.gacl.web.listener;Importjava.util.Collections;Importjava.util.LinkedList;Importjava.util.List;ImportJava.util.ListIterator;ImportJava.util.Timer;ImportJava.util.TimerTask;Importjavax.servlet.ServletContextEvent;ImportJavax.servlet.ServletContextListener;Importjavax.servlet.http.HttpSession;Importjavax.servlet.http.HttpSessionEvent;ImportJavax.servlet.http.HttpSessionListener;/*** @ClassName: sessionscanerlistener* @Description: Custom session Scanner *@author: Aloof and Pale wolf * @date: 2014-9-10 pm 10:16:42**/  Public classSessionscanerlistenerImplementsHttpsessionlistener,servletcontextlistener {/*** @Field: List * Defines a collection storage server created by HttpSession * LinkedList is not a thread-safe collection*/     /*** Private list*/    //wrap LinkedList as a thread-safe collection using the Collections.synchronizedlist (list<t> List) method    PrivatelistNewLinkedlist()); //define an object that will act as a lock and use this lock to ensure that the new session added to the list collection and the session in the list collection are synchronized    PrivateObject lock =NewObject (); @Override Public voidsessioncreated (httpsessionevent se) {System.out.println ("The session was created!!"); HttpSession Session=se.getsession (); synchronized(lock) {/*** Lock the operation locks, when there is a thread-1 (thread 1) when calling this code, will first get lock the lock, and then add the session to the collection, * in the process of adding a session to assume that there is another th             Read-2 (thread 2) to access, thread-2 may be performing a timer task, * when thread-2 to call the Run method to traverse the session in the list collection, the result is found that the code traversing the session in the list set is locked, * While this lock is being occupied by the thread-1 that adds the session to the collection, thread-2 can only wait until the thread-1 operation is complete * when Thread-1 has finished adding the session, put the lock Open, at this time thread-2 get lock, you can walk through the list of the session in the collection of the code to ensure that the set to add the session and the variable set of sessions in the collection of the session can not be done at the same time, you must follow the order of first served             For */List.add (session); }} @Override Public voidsessiondestroyed (httpsessionevent se) {System.out.println ("The session was destroyed!!"); }    /*This event is triggered when the Web App starts * @see javax.servlet.servletcontextlistener#contextinitialized ( Javax.servlet.ServletContextEvent)*/@Override Public voidcontextinitialized (Servletcontextevent sce) {System.out.println ("Web App initialization"); //Creating TimersTimer timer =NewTimer (); //perform tasks on a regular schedule every 30 secondsTimer.schedule (NewMyTask (List,lock), 0, 1000*30); } @Override Public voidcontextdestroyed (Servletcontextevent sce) {System.out.println ("Web Apps Off"); }}/*** @ClassName: mytask* @Description: Tasks to be performed regularly by timers *@author: Aloof and Pale wolf * @date: 2014-9-11 a.m. 12:02:36**/ classMyTaskextendsTimerTask {//a list collection that stores HttpSession    PrivateListlist; //Store the locks passed over    PrivateObject Lock;  PublicMyTask (listList,object Lock) {         This. List =list;  This. Lock =lock; }    /*The Run method indicates what the task is going to do * @see Java.util.timertask#run ()*/@Override Public voidrun () {//Lock the operation with a lock        synchronized(lock) {System.out.println ("Timer Execution!! "); Listiterator<HttpSession> it =List.listiterator (); /*** The session in the Iteration list collection may be accessed by other users during the iteration of the session in the list collection, * The server will create a session for the user when the user accesses it, and the sess will be called.  Ioncreated adds a new session to the list collection, * However, the timer does not know when a scheduled scan iterates through a session in the list collection that the new session that is being traversed is added to the list. This causes the new session to be added to the list collection and iterates through the session in the List collection. The solution is to "list.add (session) and while (It.hasnext ()) {//)             Generation List} "These two pieces of code are synchronized, * to ensure that when one thread accesses the" List.add "code, another thread cannot access the" while (It.hasnext ()) {//Iterate list collection} "code * In order to be able to synchronize the two pieces of irrelevant code, you can define only one lock (Object lock), and then add the same lock to the two steps, * Use this lock to guarantee the new session added to the list collection and traverse the Sessi in the list collection On these two operations are synchronized * When a new session operation is added to the list collection, it must wait until the addition is complete before the list collection can be iterated, which must wait until the iteration is performed on the list collection A new session that is often added to the list collection after the operation is finished*/             while(It.hasnext ()) {HttpSession session=(HttpSession) it.next (); /*** If the current time-session last access time >1000*15 (15 seconds) * Session.getlastaccessedtime () Gets the last access of session Time*/                if(System.currenttimemillis ()-session.getlastaccessedtime () >1000*30){                    //Manually destroy sessionsession.invalidate (); //remove a session that has been destroyed in the collectionIt.remove (); }            }        }    }}

Javaweb Learning Summary (11)-The application of the Listener (Listener) in the development

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.