Listener Listener in Java

Source: Internet
Author: User
Tags log4j

The definition and function of listener

Listener Listener is a functional component that automatically executes code when a application,session,request three objects are created, destroyed, or added to a modified delete property.

Listener is a servlet listener that listens to client requests, service-side operations, and so on.

Classification and use of listener

There are three main categories:

ServletContext Monitoring

Servletcontextlistener: Used to listen (create, destroy) the entire context of the servlet.

// Context Initialization  Public void contextinitialized (Servletcontextevent SCE); // Context Destruction  Public void contextdestroyed (Servletcontextevent SCE); // servletcontextevent event: Get a ServletContext (application) object  Public ServletContext Getservletcontext ();

Servletcontextattributelistener: Listener for the servlet context property (the Redaction property).

//Add Property Public voidattributeadded (servletcontextattributeevent scab);//Property Delete Public voidattributeremoved (servletcontextattributeevent scab);//Property Substitution (the same property is set the second time) Public voidattributerepalced (servletcontextattributeevent scab);//servletcontextattributeevent Event: Can get the name and content of the setting property//Get Property name PublicString getName ();//gets the value of the property PublicObject GetValue ();
Session Monitoring

The session belongs to the content under the HTTP protocol, and the interface is under the javax.servlet.http.* package.

Httpsessionlistener Interface: Monitor the overall state of the session.

// Session Creation  Public void sessioncreated (httpsessionevent se); // Session Destruction  Public void  //httpsessionevent event:// Get the session public for the current operation HttpSession getsession ();

Httpsessionattributelistener interface: Listen to the session's properties.

 Public voidattributeadded (httpsessionbindingevent se);//Add Property Public voidattributeremoved (httpsessionbindingevent se);//Delete Property Public voidattributereplaced (httpsessionbindingevent se);//Replace Property//httpsessionbindingevent Event: PublicString GetName ();//gets the name of the property PublicObject GetValue ();//gets the value of the property PublicHttpSession getsession ();//get the current session

There are two situations in which the session is destroyed:

1.session timeout, Web. XML configuration:

< Session-config > < Session-timeout ></session-timeout><!--session120 minutes after time-out destruction  -</session-config>

2. Manually invalidate the session

// the method of invalidating the session. Session.invalidate ();  Public void invalidate ();
Request Monitoring

Servletrequestlistener: Used to listen for request requests (create, destroy).

 Public void requestinitialized (servletrequestevent SRE); // Request Initialization  Public void requestdestroyed (servletrequestevent SRE); //  //servletrequestevent event: public servletrequest getservletrequest (); // get a ServletRequest object  Public ServletContext Getservletcontext (); // Get a ServletContext (application) object

Servletrequestattributelistener: Listens for the request property (the Redaction property).

 Public voidattributeadded (Servletrequestattributeevent srae);//Add Property Public voidAttributeremoved (Servletrequestattributeevent srae);//Property Delete Public voidattributereplaced (Servletrequestattributeevent srae);//Property Substitution (the same property is set the second time)//servletrequestattributeevent Event: Can get the name and content of the setting property PublicString GetName ();//Get Property name PublicObject GetValue ();//gets the value of the property

configuring in Web. xml

Listener configuration information must precede the filter and servlet configuration, listener initialization (Servletcontentlistener initialization) is preferable to servlet and filter. and destruction is slower than servlet and filter.

< Listener > < Listener-class >com.listener.class</listener-class></Listener  >
Listener Application Examples use Httpsessionlistener to count the largest number of online users
ImportJava.text.DateFormat;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJavax.servlet.ServletContext;Importjavax.servlet.http.HttpSessionEvent;ImportJavax.servlet.http.HttpSessionListener; Public classHttpsessionlistenerimplImplementsHttpsessionlistener { Public voidsessioncreated (Httpsessionevent event) {ServletContext app=event.getsession (). Getservletcontext ();intCount = Integer.parseint (App.getattribute ("Onlinecount"). toString ()); Count++; App.setattribute ("Onlinecount", count);intMaxonlinecount = Integer.parseint (App.getattribute ("Maxonlinecount"). toString ());if(Count >Maxonlinecount) {//What is the maximum number of records ?App.setattribute ("Maxonlinecount", Count);D Ateformat DF=NewSimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");//record at that time to reach the upper limitApp.setattribute ("Date", Df.format (NewDate ()));}}//session logoff, timeout call, stop Tomcat does not call Public voidsessiondestroyed (Httpsessionevent event) {ServletContext app=event.getsession (). Getservletcontext ();intCount = Integer.parseint (App.getattribute ("Onlinecount"). toString ()); Count--; App.setattribute ("Onlinecount", Count); }}
Spring uses Contextloaderlistener to load ApplicationContext configuration information

The role of Contextloaderlistener is to automatically assemble ApplicationContext configuration information when the Web container is started. Because it implements the Servletcontextlistener interface, when the Web. XML configures this listener, when the container is started, it executes the method it implements by default.

Contextloaderlistener How to find the configuration location of Applicationcontext.xml and configure multiple XML: If you do not write any parameter configuration information in Web. XML, the default path is "/web-inf/ Applicationcontext.xml ", the name of the XML file created under the Web-inf directory must be applicationcontext.xml (the XML file is placed in the SRC directory in myeclipse). If you want to customize the file name, you can add contextconfiglocation to the context parameter in Web. Xml.

<Context-param><Param-name>Contextconfiglocation</Param-name><Param-value>Classpath:spring/applicationcontext-*.xml</Param-value><!--A wildcard is used to find the XML file in the Web-inf/spring directory. If there are multiple XML files, separate by ",".  -</Context-param><Listener><Listener-class>Org.springframework.web.context.ContextLoaderListener</Listener-class></Listener>
the benefits of spring using Log4jconfiglistener:Spring uses Log4jconfiglistener to configure log4j logs
    • Dynamically change record levels and policies without restarting the Web App.
    • The log file is set to/web-inf/logs/without the need to write an absolute path. Because the system presses the path of the Web directory into a system variable called Webapp.root. You do not have to write the absolute path when you write the log file path.
    • You can put log4j.properties and other properties together in/web-inf/, not class-path.
    • Set the Log4jrefreshinterval time and open a watchdog thread to scan the configuration file for changes every time.
<Context-param><Param-name>Webapprootkey</Param-name><Param-value>Project.root</Param-value><!--used to locate the log file output location under Web App root, write output location in log4j config file: Log4j.appender.file.file=${project.root}/logs/project.log -</Context-param><Context-param><Param-name>Log4jconfiglocation</Param-name><Param-value>Classpath:log4j.properties</Param-value><!--loading the log4j configuration file -</Context-param><Context-param><Param-name>Log4jrefreshinterval</Param-name><Param-value>60000</Param-value><!--Spring Refreshes the log4j configuration file at intervals of 60 seconds, in units of millisecond -</Context-param><Listener><Listener-class>Org.springframework.web.util.Log4jConfigListener</Listener-class></Listener>
Spring uses Introspectorcleanuplistener to clean up the cache

The purpose of this listener is to flush the JavaBeans introspector cache of the JDK when the Web app shuts down to ensure that the class loader for the Web application and its loaded classes are releasing resources correctly.

If JavaBeans's introspector has been used to parse the application class, the system-level Introspector cache will hold a hard reference to these classes. Therefore, the class loader for these classes and Web applications will not be reclaimed by the garbage collector when the Web application is closed! Introspectorcleanuplistener, in turn, cleans it up properly, allowing it to be recycled by the garbage collector.

The only way to clean up introspector is to flush the entire introspector cache, and there is no other way to specify exactly which classes the application refers to. This will remove all other application Introspector results on the server's cache.

There is no need to use this listener when using the bean mechanism inside spring, because spring's own introspection results cache will immediately refresh the parsed JavaBeans introspector cache. It only holds a cache in the application's own ClassLoader. Although spring itself does not produce leaks, note that even if the spring framework's class itself resides in a "common" classloader (such as the system's ClassLoader), it should still use Introspectorcleanuplistener. In this case, the Introspectorcleanuplistener will properly clean up the spring introspection cache.

Application classes, which rarely require direct use of the JavaBeans introspector, are usually not introspector resource cause memory leaks. Conversely, many libraries and frameworks do not clean up introspector, for example: struts and quartz.

It is important to note that a simple introspector leak will cause the entire Web application's ClassLoader to not be recycled! The result will be that when the Web application shuts down, all static class resources (such as single-instance objects) of the application are not freed. The root cause of the memory leaks is not the classes that are not recycled!

Note: Introspectorcleanuplistener should be registered as the first listener in Web. XML, registered before any other listener, such as before Spring's contextloaderlistener registration To ensure that introspectorcleanuplistener takes effect at the right time in the life cycle of the Web App.

< Listener > <!--  -     <listener-class> Org.springframework.web.util.IntrospectorCleanupListener</listener-class>  </listener>

Listener Listener in Java

Related Article

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.