Sprint Listener Listener

Source: Internet
Author: User
Tags dateformat

Listener Listener

Preface: wrote an article about filter: http://tianweili.github.io/blog/2015/01/26/java-filter/, now another listener, Filter and listener are often used in projects, and clever use can achieve a multiplier effect. So summarize the usage of the two.

Original link: http://tianweili.github.io/blog/2015/01/27/java-listener/

1. 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.

2, the classification and use of listener

There are three main categories:

1, ServletContext monitoring

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

public void contextinitialized (Servletcontextevent SCE);//context initialization public
void contextdestroyed ( Servletcontextevent SCE);//context Destroy public

ServletContext getservletcontext ();// Servletcontextevent event: Get a ServletContext (application) object

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

public void attributeadded (servletcontextattributeevent scab);//Add Property public
void Attributeremoved ( Servletcontextattributeevent scab);//property Delete public
void attributerepalced (servletcontextattributeevent scab);// Property substitution (Set the same property for the second time)

//servletcontextattributeevent event: Can get the name of the setting property and the content public
String getName ();//Get the property name
Public Object getValue ();//Gets the value of the property

2. 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.

public void sessioncreated (httpsessionevent se);//session create public
void sessiondestroyed (httpsessionevent se);// Session Destruction

//httpsessionevent event: Public
HttpSession getsession ();//session with current operation

Httpsessionattributelistener interface: Listen to the session's properties.

public void attributeadded (httpsessionbindingevent se);//Add Property public
void Attributeremoved ( Httpsessionbindingevent se);//Delete the property public
void attributereplaced (httpsessionbindingevent se);/

/replace attribute// Httpsessionbindingevent event: Public
String getName ();//Gets the name of the property public
Object GetValue ();//Gets the value of the property public
HttpSession 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>120</session-timeout><!--session120 minutes after the timeout is destroyed--
</session-config>

2, manual to invalidate the session

public void invalidate ();//The session invalidation method. Session.invalidate ();

3. Request Monitoring

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

public void requestinitialized (Servletrequestevent SRE);//request initialize public
void requestdestroyed ( Servletrequestevent SRE);//request destroy

//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 void attributeadded (Servletrequestattributeevent srae);//Add Property public
void Attributeremoved ( Servletrequestattributeevent srae);//property Delete public
void attributereplaced (servletrequestattributeevent srae);// Property substitution (Set the same property for the second time)

//servletrequestattributeevent event: Can get the name of the setting property and the content public
String getName ();//Get the property name
Public Object getValue ();//Gets the value of the property

4. 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>

3. Listener Application Example

1. Use Httpsessionlistener to count the maximum number of online users

Import Java.text.DateFormat;
Import Java.text.SimpleDateFormat;
Import Java.util.Date;
Import Javax.servlet.ServletContext;
Import javax.servlet.http.HttpSessionEvent;

Import Javax.servlet.http.HttpSessionListener; public class Httpsessionlistenerimpl implements Httpsessionlistener {public void sessioncreated (Httpsessionevent eve
        NT) {ServletContext app = Event.getsession (). Getservletcontext ();
        int count = Integer.parseint (App.getattribute ("Onlinecount"). toString ());
        count++;
        App.setattribute ("Onlinecount", count);
        int maxonlinecount = Integer.parseint (App.getattribute ("Maxonlinecount"). toString ());
            if (Count > Maxonlinecount) {//record the maximum number of people is how many App.setattribute ("Maxonlinecount", count);
            DateFormat df = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss");
        Record at that time reached the upper limit App.setattribute ("date", Df.format (new Date ())); }}//session logoff, timeout call, stop Tomcat does not call public voiD sessiondestroyed (Httpsessionevent event) {ServletContext app = Event.getsession (). Getservletcontext ();
        int count = Integer.parseint (App.getattribute ("Onlinecount"). toString ());
        count--;    
        
    App.setattribute ("Onlinecount", count); }
}

2. 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><!--uses a wildcard method to find the XML file in the Web-inf/spring directory. If there are multiple XML files, separate by ",". -
</

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.