Java Web Development--servlet Listener

Source: Internet
Author: User

A servlet listener is a special class defined in the servlet specification that listens to the creation and destruction events of domain objects such as ServletContext, HttpSession, and ServletRequest, and listens to events in which properties have been modified in these domain objects.

Listener object:

1, servletcontext:application, the entire application exists only one

2, httpsession:session, for each dialogue

3, Servletrequest:request, for each customer request

Listener content: Create, destroy, attribute change events

Monitoring role: Can be in the event before, after the occurrence of some processing, generally can be used to count the number of online and online users, statistics website visits, system startup initialization information.

Second, the basic use of the listener

To create a step:

1. Create a class that implements the Listener interface

2. Configure Web. xml file, Register Listener

<listener>    <listener-class> Full class name </listener-class>  </listener>          

Boot order of the Listener : start in the configuration order of Web. XML

Load Order: Listener > Filter >servlet

Iii. Classification of listeners

3.1 According to the listener's object division

1. Event listener for monitoring Application Environment object (ServletContext), implement Servletcontextlistener, Servletcontextattributelistener interface

2, for listening to the user session object (httpseesion) event listener, implementation of Httpsessionlistener, httpsessionattributelistener interface

3, for listening to the request message object (ServletRequest) event Listener, implement Servletrequestlistener, Servletrequestattributelistener interface

3.2 According to the Listening events Division

1. Listen for event listeners that are created and destroyed by the domain object itself

The servletcontextlistener, Httpsessionlistenerand Servletrequestlistener interfaces are implemented according to the different listener objects.

Creation and destruction of ①servletcontext:contextinitialized method and contextdestroyed method

void contextinitialized (Servletcontextevent SCE)//ServletContext is created with a call to void contextdestroyed ( Servletcontextevent SCE)//ServletContext called when destroying    

Main applications: As timers, load global property objects, create global database connections, load cache information, etc.

Instance:

Project initialization information can be configured in Web. XML and started in the Contextinitialized method

<context-param>    <param-name> property name </param-name<  Param-value> property values </param-value></context-param>  

Custom Listener

Implements servletcontextlistener{    void// Gets the property configured in Web. String value=sce.getservletcontext () . Getinitparameter ("Property name"void// Close Action }}       

Creation and destruction of ②httpsession:sessioncreated and sessiondestroyed methods

void sessioncreated (httpsessionevent se)//session creation call void sessiondestroyed (httpsessionevent se)// called when the session is destroyed    

Main uses: Statistics online people, record access logs, etc.

Note

Web. XML config Session timeout parameter, unit: minutes, Session timeout time is not accurate

<session-config>    <session-timeout>10</session-timeout> </session-config>          

Creation and destruction of ③servletrequest:requestinitialized and requestdestroyed methods

void requestinitialized (Servletrequestevent sre)//When request is created, call void requestdestroyed ( Servletrequestevent SRE)//call when request is destroyed    

Main purpose: Read request parameter, record access history

Instance:

Implements sevletrequestlistener{    void requestinitialized (servletrequestevent SRE) {String value= Sre.getservletrequest (). GetParameter ("key"); // Gets the parameter in request void requestdestroyed (servletrequestevent SRE) {System.out.println ("request Destroyed "        

2. Listener for adding and deleting attributes in the domain object

According to the listener different implementation Servletcontextattributelistener,Httpsessionattributelistener, Servletrequestattributelistener interface.

Implementation methods:attributeadded, attributeremoved, attributereplaced

3. Listen for event listeners bound to the state of an object in the Httpseesion domain (create a normal JavaBean)

Object state in HttpSession: Binding → unbind; Passivation → activation

Implement interfaces and methods:Httpsessionbindinglistener Interfaces (Valuebound and valueunbound methods), Httpsessionactivationlistener interface (sessionwillpassivate and sessiondidactivate methods)

"Note 1" ① the Serializable interface must be implemented to achieve passivation and activation

② does not need to be registered in Web. xml

"Note 2"

Binding: Saved to Session object via SetAttribute

Unbind: Remove by Removeattribue

Passivation: Persisting session objects to a storage device

Activation: Restores the session object from the storage device

Session passivation Mechanism:

① the server infrequently used session object is temporarily serialized to the system file or database, when used to deserialize into memory, the whole process is automatically completed by the server;

②session's passivation mechanism is managed by SessionManager, creating a common JavaBean binding and contact needs to implement the Httpsessionbindinglistener interface

Iv. use of listeners under Servlet3.0

4.1 Conditions of Use

1. Using the servlet3.0 new standard jar Package

2, JDK in more than 1.6 version

3, compiler compiler level is 6.0

4. In the Web. xml file, use the 3.0 specification

5. Use a web container that supports servlet3.0 features, such as Tomcat7

4.2 servlet3.0 The usage of the listener

You can use annotations @WebListener to define the order of listeners

Common Properties for @WebListener
Property name Type is optional Describe
Value String Is Description information for this listener
@WebListener ("This is a listener")class Firstlistener impliements servletrequestlistener{} 

This annotation is used to declare a class as a listener, and the class that is @WebListener labeled must implement at least one of the following interfaces:

Servletcontextlistener

Servletcontextattributelistener

Servletrequestlistener

Servletrequestattributelistener

Httpsessionlistener

Httpsessionattributelistener

Java Web Development--servlet Listener

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.