Servletcontextlistener, Httpsessionlistener, and Servletrequestlistener in Java use grooming

Source: Internet
Author: User

In a Java Web application, the listener listener appears to be indispensable. Often used to monitor ServletContext, HttpSession, ServletRequest and other domain object creation, destruction and property changes, etc., can be in these events before and after a certain logical processing.


The more frequently used scenarios are the use of listeners to initialize some data, to count the number of people online, to count Web application views, and so on.


The listener described here is actually a special class defined in the servlet specification that requires the implementation of a specific interface.
And I'm going to say that three of them are used to listen for domain objects, each of which is Servletcontextlistener, Httpsessionlistener, Servletrequestlistener.
These three interfaces are practically identical in their notation. There are two different methods that represent the invocation and destruction of the domain object when it is created. As far as I understand it, the biggest difference between these three objects should be the different scopes.

The


ServletContext takes effect at the end of the entire app launch. This object is created when the system is started, and this object is unique throughout the process. The
HttpSession takes effect during a session, and it works when a session is created until it expires, except that there are multiple HttpSession objects in a startup application, such as two browsers on the same computer. A two HttpSession object is created.
While ServletRequest is in effect when a request is created and destroyed, a new ServletRequest object is created for each request, such as refreshing the browser page, clicking on the app's inner chain, and so on.
These three listeners are basically written as seen by the following pseudocode:
First create a listener class to implement the corresponding interface and method:

package packageName;publicclass ListenerName implements *Listener {    @Override    publicvoid 对象创建时被调用的方法(对应的事件 arg0) {    }    @Override    publicvoid 对象销毁时被调用的方法(对应的事件 arg0) {    }}

Then register in Web. xml:

<listener>    <listener-class>packageName.ListenerName</listener-class>  </listener>

Here, basically, this listener will run normally after starting the Web server, but sometimes we'll just configure some of the others when we register the listener.
For example, when you configure Servletcontextlistener, you may add Context-param parameters:

<context-param>     <param-name>paramName</param-name>     <param-value>paramValue</param-value></context-param>

When configuring Httpsessionlistener, the session timeout may be added:

<session-config>     <session-timeout>1</session-timeout></session-config>

I feel that after this sort of arrangement, I find that the starting listener is very easy to write. So the simulation simple implementation of online user statistics and application access, the basic code such as the following:
The first is the realization of ServletContext

 PackageWebTest;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;ImportJava.util.Date;ImportJavax.servlet.ServletContextEvent;ImportJavax.servlet.ServletContextListener; Public  class ListenerTest1 implements Servletcontextlistener {    @Override     Public void contextdestroyed(Servletcontextevent arg0) {System.out.println ("Contextdestroyed"+","+NewDate ()); Object count = Arg0.getservletcontext (). getattribute ("Count"); File File =NewFile ("Count.txt");Try{FileOutputStream FileOutputStream =NewFileOutputStream (file); OutputStreamWriter OutputStreamWriter =NewOutputStreamWriter (FileOutputStream,"Utf-8"); BufferedWriter BufferedWriter =NewBufferedWriter (OutputStreamWriter);            Bufferedwriter.write (Count.tostring ());        Bufferedwriter.close (); }Catch(IOException e)        {E.printstacktrace (); }    }@Override     Public void contextinitialized(Servletcontextevent arg0) {System.out.println ("Contextinitialized"+","+NewDate ()); File File =NewFile ("Count.txt");if(File.exists ()) {Try{FileInputStream FileInputStream =NewFileInputStream (file); InputStreamReader InputStreamReader =NewInputStreamReader (FileInputStream,"Utf-8"); BufferedReader Breader =NewBufferedReader (InputStreamReader);                String count = Breader.readline (); System.out.println ("History visits:"+ count); Arg0.getservletcontext (). SetAttribute ("Count", count);            Breader.close (); }Catch(IOException e)            {E.printstacktrace (); }        }    }}

Here I have the number of visits in a TXT file. So that you can persist the save. When the project starts. That is, the load method is called when the ServletContext object is created. Read the historical interview amount from the TXT file and then use the SetAttribute method to store the data in memory.
After the application is closed, the ServletContext object is destroyed and the new access data in memory is overwritten to the TXT file. To continue reading the amount of access before the next time you start the app.
Then use Servletrequestlistener to realize the change of web browsing volume, of course. Here is just a simple implementation, assuming that the same user refresh the page does not add the ability to browse, but also need to do a lot of other processing.

 PackageWebTest;ImportJava.util.Date;ImportJavax.servlet.ServletRequestEvent;ImportJavax.servlet.ServletRequestListener; Public  class ListenerTest3 implements Servletrequestlistener {    @Override     Public void requestdestroyed(Servletrequestevent arg0) {System.out.println ("Requestdestroyed"+","+NewDate ()); System.out.println ("Current number of visits:"+ Arg0.getservletcontext (). getattribute ("Count")); }@Override     Public void requestinitialized(Servletrequestevent arg0) {System.out.println ("Requestinitialized"+","+NewDate ()); Object count = Arg0.getservletcontext (). getattribute ("Count"); Integer Cinteger =0;if(Count! =NULL) {Cinteger = Integer.valueof (count.tostring ()); } System.out.println ("History Visits::"+ count);        cinteger++; Arg0.getservletcontext (). SetAttribute ("Count", Cinteger); }}

Here the same is the two method that is called when the ServletRequest object is built. Reads the Count property of the ServletContext object from memory, and then outputs the historical number of visits.


At the same time, the contents of the Count property of the ServletContext object are set once and again on this basis. When the ServletRequest object is destroyed, the method of destroying is called to print out the current view amount. This simply implements the cumulative count of the amount of web browsing.
And then we use Httpsessionlistener to count the number of people who are now online:

 PackageWebTest;ImportJava.util.Date;ImportJavax.servlet.http.HttpSessionEvent;ImportJavax.servlet.http.HttpSessionListener; Public  class ListenerTest2 implements Httpsessionlistener {    @Override     Public void sessioncreated(Httpsessionevent arg0) {System.out.println ("sessioncreated"+","+NewDate ()); Object LineCount = Arg0.getsession (). Getservletcontext (). getattribute ("LineCount"); Integer count =0;if(LineCount = =NULL) {LineCount ="0";        } count = Integer.valueof (linecount.tostring ());        count++; System.out.println ("New on-line one, history online number:"+ LineCount +"A, the current number of online people are:"+ Count +"a"); Arg0.getsession (). Getservletcontext (). SetAttribute ("LineCount", count); }@Override     Public void sessiondestroyed(Httpsessionevent arg0) {System.out.println ("Sessiondestroyed"+","+NewDate ()); Object LineCount = Arg0.getsession (). Getservletcontext (). getattribute ("LineCount");        Integer count = integer.valueof (linecount.tostring ());        count--; System.out.println ("One person downline, history online Number:"+ LineCount +"A. Current number of people online: "+ Count +"a"); Arg0.getsession (). Getservletcontext (). SetAttribute ("LineCount", count); }}

The code here is very easy. I think there is not much to be explained, but it is necessary to explain. I'm not the only way to store linecount in ServletContext objects, and interested friends can try other ways. For example, use class properties.


The demo sample is also packaged and uploaded here. The required friends can download the execution on their own.


Links: http://pan.baidu.com/s/1bZ2vx0
Password:ekb9

CSDN Download: http://download.csdn.net/detail/tuzongxun/9761166

Using Servletcontextlistener, Httpsessionlistener, and Servletrequestlistener in Java

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.