I. Basic CONCEPTS
The listener inside the Javaweb is implemented through the observer design pattern. For the observer model, here is not to do too much introduction, probably say what meaning.
The observer mode is also called the Publish subscription mode or the Listener mode. There are two roles in this pattern: the Observer and the observed (usually also called the subject). The observer registers an event of interest in the subject, and when the event occurs, the subject notifies the observer through the callback interface.
Take a life example: subscribe to a newspaper. Any family or individual can subscribe to a newspaper. The newspaper is the subject, and the family is the observer. For example, families need to subscribe to tomorrow morning's newspaper, this is the "event". By the next morning, the paper was produced, and this was the "incident". When the incident occurred, the newspaper sent the paper to the family's mailbox, where the mailbox is the "callback interface."
For listeners inside the Javaweb, the servlet specification defines the column's listener interface classes, exposing events to the application through an interface class, and if the application wants to monitor events of interest, it does not have to register the corresponding event directly. Instead, write your own listener implement the appropriate interface classes and register your listener with the servlet container. When the event that the program cares about occurs, the servlet container notifies the listener and recalls the method inside the listener. The custom listener here is the observer, and the Servlet container is the subject.
Second, sample analysis
It says that the servlet container exposes events to the application through the Listener interface class. So instead of registering for events, we're registering listeners. Corresponding to the programming step is: 1. Write your own listener to implement a specific listener interface. 2. Register your listener inside the web.xml. Here is an example of the simplest listener interface Servletcontextlistener:
1.testlistener.java
public class Testlistener implements Servletcontextlistener {public
Testlistener () {} public
void Contextinitialized (Servletcontextevent SCE) {
System.out.println ("servletcontextlistener.contextinitialized" );
}
public void contextdestroyed (Servletcontextevent sce) {
System.out.println (" Servletcontextlistener.contextdestroyed ");
}
}
2.web.xml
<listener>
<listener-class>com.nantang.listener.TestListener</listener-class>
< /listener>
When the container is started, the "servletcontextlistener.contextinitialized" is output to the log, and "servletcontextlistener.contextdestroyed" is output when the container closes. A detailed explanation will be further analyzed later.
The note here is that if you demonstrate the above example in the IDE (Eclipse, STS, etc.), when you start the server, you can see "servletcontextlistener.contextinitialized" in the console, and when you shut down the server, you can't see " Servletcontextlistener.contextdestroyed ". It's not that the Contextdestroyed method is not implemented, but the IDE does not do it perfectly. To verify that the contextdestroyed is actually invoked, you can write a piece of code in the contextdestroyed to the output of the file rather than to the console.
Third, the source code analysis
Now we analyze what events the Servlet specification defines for us. More precisely, which listener interfaces are defined. The following descriptions are based on the servlet3.0 specification.
SERVLET3.0 provides us with 8 listener interfaces that can be grouped into three categories according to their scope:
1.servlet context-sensitive listening interface, including: Servletcontextlistener and Servletcontextattributelistener.
2.http session related listening interface, including: Httpsessionlistener, Httpsessionactivationlistener, Httpsessionattributelistener and Httpsessionbindinglistener.
3.servlet request related listening interface, including: Servletrequestlistener and Servletrequestattributelistener.
In fact, from the name of the interface, you reader should be able to guess its basic function. Here we will explain by category.
1.servlet context-Sensitive listening interface
Before introducing the servlet, we explained that a Web application corresponds to a servlet context. So the life span of the events that Servletcontextlistener and Servletcontextattributelistener monitor is throughout the Web application. The following is a class diagram hierarchy relationship between the two interfaces.
1.1 EventListener
EventListener is a markup interface, all event listeners must inherit this interface, this is the servlet specification, there is no good explanation.
1.2 EventObject
Like EventListener, EventObject is an event top-level class, and all concrete event classes must inherit EventObject.
public class EventObject implements java.io.Serializable {
protected transient Object source;
Public EventObject (Object source) {
if (Source = null)
throw new IllegalArgumentException ("null source");
This.source = source;
}
Public Object GetSource () {return
source;
}
Public String toString () {return
getclass () getName () + "[source=" + source + "]";
}
}
This class is very simple, its essence is one thing: source. By using the class name EventObject and the property name source, you can see that this class does one thing and holds the event source object.
1.3 servletcontextevent
public class Servletcontextevent extends Java.util.EventObject {public
servletcontextevent (ServletContext source ) {
super (source);
}
Public ServletContext Getservletcontext () {return
(ServletContext) Super.getsource ();
}
Servlet context event, this event class is a simple inheritance of eventobject. The ServletContext instance is provided as an event source in the constructor method. Because the event source is a servlet context, a getservletcontext is provided to obtain the ServletContext instance.
When we follow up on other event classes, it's a mold, and each event class provides the appropriate construction method, passes in the appropriate event source object, and provides an additional way to get the event source. So EventObject is the base class for an event source, and the nature of all the event subclasses does one thing to determine the specific event source object.
So we have to explain the incident in the back of the area.
1.4 Servletcontextlistener
Public interface Servletcontextlistener extends EventListener {public
void contextinitialized ( Servletcontextevent SCE);
public void contextdestroyed (Servletcontextevent sce);
}
The servlet context listener interface, which corresponds to two events: the servlet context initialization event and the servlet context impending shutdown event.
When the Web application initializes, the servlet container constructs the Servletcontexteven instance and recalls the Contextinitialize method.
When the servlet context is about to close, the servlet container constructs the Servletcontexteven instance and recalls the Contextdestroyed method before the server is generally shut down. It should be noted here that the execution of the Contextdestroyed method is followed by the completion of the Destroy method by all servlet and filter.
So if we want to do something when the application starts or shuts down, write our own listener to implement the interface.
All event listeners are also a mold, the corresponding event callback interface method is defined according to the servlet specification, and the method's entry is the corresponding event source instance. So we've been in the area behind the listener.
1.5 servletcontextattributeevent
public class Servletcontextattributeevent extends Servletcontextevent {
private String name;
private Object value;
Public Servletcontextattributeevent (ServletContext source, String name, Object value) {
super (source);
this.name = name;
This.value = value;
}
Public String GetName () {return
this.name;
}
Public Object GetValue () {return
this.value
}}
Servletcontextattributeevent represents the servlet context attribute-related event, which is typically triggered when a property changes. This class inherits Servletcontexteven, and the event source is also an ServletContext instance. Provides additional methods of obtaining property names and property values.
1.6 Servletcontextattributelistener
Public interface Servletcontextattributelistener extends EventListener {public
void attributeadded ( Servletcontextattributeevent scab);
public void attributeremoved (Servletcontextattributeevent scab);
public void attributereplaced (Servletcontextattributeevent scab);
}
When the servlet above attributes increase, delete, change, the servlet container constructs the Servletcontextattributeevent event object, respectively, callback attributeadded, attributeremoved, Attributereplaced method.
Note Here is the attributereplaced method, which is invoked when the value of the property is replaced. This time, if the call to the Servletcontextattributeevent.getvalue () method returns the value of the property before the substitution.
2 HTTP session-related listening interface
2.1 Httpsessionevent
public class Httpsessionevent extends Java.util.EventObject {public
httpsessionevent (HttpSession source) {
Super (source);
Public HttpSession getsession () {return
(HttpSession) Super.getsource ();
}
An HTTP session-related event that triggers the event when it is changed. The event source is an HttpSession instance and provides an additional httpsession fetch method.
2.2 Httpsessionlistener
Public interface Httpsessionlistener extends EventListener {public
void sessioncreated (httpsessionevent se);
public void sessiondestroyed (httpsessionevent se);
}
When the session is created and destroyed, the servlet container constructs the Httpsessionevent event object and recalls the Sessioncreated and sessiondestroyed methods.
2.3 Httpsessionactivationlistener
Public interface Httpsessionactivationlistener extends EventListener {public
void Sessionwillpassivate ( Httpsessionevent se);
public void sessiondidactivate (httpsessionevent se);
}
When the session is about to be deactivated or activated, the servlet container constructs the Httpsessionevent event object and recalls the Sessionwillpassivate and Sessiondidactivate methods.
This explains the passivation and activation: passivation means that the server is running out of memory or that the session's activity timeout is over, serializing the most recent inactive session to disk. Activation refers to the session of a passivation that is accessed again, deserializing the session from disk to memory.
Here you can see that in order to deactivate and activate, the session can be serialized and deserialized first. At the same time, we in the programming process, the session as far as possible with string, integer and other simple objects, as far as possible not to use the list, map and other sets.
2.4 httpsessionbindingevent
public class Httpsessionbindingevent extends Httpsessionevent {
private String name;
private Object value;
Public Httpsessionbindingevent (HttpSession sessions, String name) {
Super (session);
this.name = name;
Public Httpsessionbindingevent (HttpSession sessions, String name, Object value) {
super (session);
this.name = name;
This.value = value;
}
Public HttpSession getsession () {return
super.getsession ();
}
Public String GetName () {return
name;
}
Public Object GetValue () {return
this.value
}}
The attribute-related event of the HTTP session, which is triggered when a change is taken to the sessions property. The event source is an HttpSession instance and provides additional methods for obtaining httpsession, property names, and property values.
2.5 Httpsessionattributelistener
Public interface Httpsessionattributelistener extends EventListener {public
void attributeadded ( Httpsessionbindingevent se);
public void attributeremoved (httpsessionbindingevent se);
public void attributereplaced (httpsessionbindingevent se);
}
When the session attribute is increased, deleted, and changed, the servlet container constructs the Httpsessionbindingevent event object, which is recalled respectively to attributeadded, attributeremoved, Attributereplaced method.
Note Here is the attributereplaced method, which is invoked when the value of the property is replaced. This time, if the call to the Servletcontextattributeevent.getvalue () method returns the value of the property before the substitution.
When the Invalidate method of the session is invoked or the session fails, the Attributeremoved method is also recalled.
2.6 Httpsessionbindinglistener
Public interface Httpsessionbindinglistener extends EventListener {public
void Valuebound ( Httpsessionbindingevent event);
public void Valueunbound (Httpsessionbindingevent event);
}
This listener is also a property change that listens for session. When the session attribute is increased and deleted, that is, the attribute value binding and the attribute value is unbound, the servlet container constructs the Httpsessionbindingevent event object, which recalls the Valuebound, Valueunbound method respectively.
Such a look and Httpsessionattributelistener no difference, in fact, it is not so. The essential difference between the two is the condition that triggers the event.
When the properties of the session change, the servlet container notifies the Httpsessionattributelistener. However, for Httpsessionbindinglistener, the servlet container is notified only if the bound or unbound property value is an instance of the listener. For example:
The public class Testlistener implements httpsessionbindinglistener{@Override the public
void Valuebound ( Httpsessionbindingevent event) {
System.out.println ("Httpsessionbindinglistener.valuebound");
}
@Override public
void Valueunbound (Httpsessionbindingevent event) {
System.out.println (" Httpsessionbindinglistener.valueunbound ");
}
}
Our custom listener Testlistener implementation Httpsessionbindinglistener, we set the following session property in code:
HttpSession session = Request.getsession ();
Testlistener testlistener=new Testlistener ();
Session.setattribute ("Listener", Testlistener);
Session.removeattribute ("Listener");
The attribute value for the session here is our listener Testlistener instance. So when this code executes, the servlet container notifies the Testlistener and recalls the Valuebound and Valueunbound methods.
It should be noted here that the Valueunbound method is also recalled when the Invalidate method for the session is invoked or the session fails.
3 servlet request Related listening interface
3.1 servletrequestevent
public class Servletrequestevent extends Java.util.EventObject {
private servletrequest request;
Public Servletrequestevent (ServletContext SC, servletrequest request) {
Super (SC);
This.request = Request;
}
Public ServletRequest Getservletrequest () {return
this.request;
}
Public ServletContext Getservletcontext () {return
(ServletContext) Super.getsource ();
}
The related event requested by the servlet that triggers the event when the request changes. The event source is an ServletContext instance and provides additional access to ServletContext and ServletRequest methods.
3.2 Servletrequestlistener
Public interface Servletrequestlistener extends EventListener {public
void requestdestroyed (servletrequestevent SRE);
public void requestinitialized (Servletrequestevent sre);
}
When the request is initialized or destroyed, the client requests to enter the Web application (into the servlet or the first filter) or the Web application returns the response to the client (exit servlet or first filter). The servlet container constructs the Servletrequestevent instance and recalls the Requestinitialized and requestdestroyed methods.
3.3 Servletrequestattributeevent
public class Servletrequestattributeevent extends Servletrequestevent {
private String name;
private Object value;
Public Servletrequestattributeevent (ServletContext SC, servletrequest request, String name, Object value) {
super ( SC, request);
this.name = name;
This.value = value;
}
Public String GetName () {return
this.name;
}
Public Object GetValue () {return
this.value
}}
The Servlet requests a property-related event that is triggered when the request property is changed. The event source is an ServletContext instance and provides additional methods for obtaining property names and property values.
3.4 Servletrequestattributelistener
Public interface Servletrequestattributelistener extends EventListener {public
void attributeadded ( Servletrequestattributeevent srae);
public void attributeremoved (Servletrequestattributeevent srae);
public void attributereplaced (Servletrequestattributeevent srae);
}
When the requested attribute is increased, deleted, and changed, the servlet container constructs the Servletrequestattributeevent event object, which is called back to attributeadded, attributeremoved, Attributereplaced method.
Note Here is the attributereplaced method, which is invoked when the value of the property is replaced. This time, if the call to the Servletrequestattributeevent.getvalue () method returns the value of the property before the substitution.
Iv. Summary
At this point, listener finished speaking. We can see that the listener and the servlet and the filter have one thing in common, all of which are scheduled by the container. We just need to write our own listener to implement the listener interface we care about and register, and the rest of the work is to write business logic in our own listener.
This article introduces the listener is the SERVLET3.0 standard formulation. 3.1 has added some event listener interfaces, and the truth is similar, and readers can understand them on their own.