1. Listener Concept
1. Event Source: The event object.
2. Listener: it is an interface that listens for the action to occur on the event source.
3. event: the event object is usually used as a parameter of the listener method. It encapsulates the object in which an event occurs.
Ii. Listener provided in Servlet (8)
Eight listener types:
2.1 listener for creating and destroying ServletContext, HttpSession, and ServletRequest objects.
ServletContextListener: listens to the creation and destruction of the ServletContext object.
HttpSessionListener: listens to the creation and destruction of HttpSession objects.
Create: When request. getSession () is called for the first time.
Destroy: 1. Actively call the invalidate () method
2. Timeout
ServletRequestListener: listens to the creation and destruction of the ServletRequest object.
2.2 listen to the listener of domain changes (new, replaced, deleted) in the ServletContext, HttpSession, and ServletRequest objects.
ServletContextAttributeListener:
HttpSessionAttributeListener:
ServletRequestAttributeListener:
2.3 sensor listener: Whoever implements these interfaces can perceive what they are doing. This listener does not need to be registered.
HttpSessionActivationListener: detects when an http session object is inactivated and activated.
HttpSessionBindingListener: detects when an HttpSession object is bound (bound to a domain) and unbound.
Procedure:
1. Write a class to implement a listener Interface
2. register the listener in web. xml
<Listener>
<Listener-class> cn. usst. listener. ServletContextDemoListener </listener-class>
</Listener>
3. Design a program in the Observer Design Mode
// Event source public class Student implements Serializable {private String name; private StudentListener listener; public Student (String name) {// injection: constructor this. name = name;} public String getName () {return name;} public void eat () {if (listener! = Null) {listener. preEat (new StudentEvent (this);} System. out. println ("start to eat");} public void study () {if (listener! = Null) {listener. preStudy (new StudentEvent (this);} System. out. println (" ");}}
Public class StudentEvent {private Object source; public StudentEvent (Object source) {this. source = source;} public Object getSource () {// get the event source return source ;}}
Public interface StudentListener {void preEat (StudentEvent e); // listen to void preStudy (StudentEvent e); // listener}
Test cases:
Public static void main (String [] args) {Student s = new Student ("Ge Fu to"); // register the listener s. addStudentListener (new StudentListener () {public void preStudy (StudentEvent e) {Student ss = (Student) e. getSource (); System. out. println (ss. getName () + "Drink cup");} public void preEat (StudentEvent e) {Student ss = (Student) e. getSource (); System. out. println (ss. getName () + "Eat slowly") ;}}); s. eat (); s. study ();}