JavaWeb learning notes (Servlet event listener)

Posted by reckdan on Wed, 02 Mar 2022 11:08:04 +0100

Overview of Servlet event listener

In the development of relationship, it is often necessary to monitor some events, such as mouse click events and key press events. At this time, you need to use event listener.
There are several important components in the listener:
(1) Event: a user action
(2) Event source: the object that generated the event
(3) Event listener: responsible for listening for events that occur on the event source
(4) Event handler: the member method of the listener. When an event occurs, the method of the corresponding handler will be triggered.
The event listener is working in the following steps:
(1) Bind the listener to the event source, that is, register the listener
(2) Event occurrence is the member method that will trigger the listener, that is, the event handler, to pass the event object
(3) The event processor obtains the event source through the event object and processes the event source.
Type of event listener
(1) A time listener (ServletContextListener interface, httpsessionlister interface, ServletRequestListener interface) used to listen to domain object creation and session.
(2) Time listeners (ServletContextAttributeListener interface, HttpSessionAttributeListener interface, ServletRequestAttributeListener interface) used to listen for the addition and deletion of domain object attributes.
(3) A time listener (HttpSessionBindingListener interface, HttpSessionActivationListener interface) used to listen to the state bound to an object in the HTTPSession domain.

Listen to the lifecycle of domain objects

During the running of the Web application, the Web container will create and destroy three important objects ServletContext, HttpSession and ServletRequest, which are called domain objects.

ServletContextListener interface

ServletContextListener is used to listen to the life cycle of the ServletContext object. The ServletContext object is used to listen to the creation and destruction process of the object. The ServletContextListener interface defines two event handling methods.
(1) Contextlntialized() method
Syntax definition:

public void contextInitialized(servletContextEvent sce)

When the ServletContext object is created, the Web container will call the contextInitialized() method. The contextInitialized() method receives a parameter of ServletContextEvent type, and the contextInitialized() method creates the ServletContext object through the parameter.
(2) contextDestroyed() method
The syntax is defined as:

public void contextDestroyed(servletContextEvent sce)

When the ServletContext object is about to be destroyed, the Web container callback uses the contextDestroy() method.

HttpSessionListener interface

HttpSession is used to complete the session operation. In order to listen to the creation and destruction of HttpSession objects, the servlet API provides an httpsessionlister interface. When the Web application registers one or more event listeners that implement the httpsessionlister interface, the Web container will generate an HttpSessionEvent event object when creating or destroying each HttpSession object, Then call the corresponding methods of the HttpSession event listener in turn, and pass the HttpSessionEvent event object to these methods.
(1) sessionCreated() method
Syntax definition:

public void sessionCreated(HttpSessionEvent se)

Whenever an HttpSession object is created, the Web container will call the sessionCreated() method. The sessionCreated() method receives a parameter of HttpSessionEvent type. The sessionCreated() method can internally obtain the currently created HttpSession object through this parameter.
(2) sessionDestroy() method
Syntax definition:

public void sessionDestroyed(HttpSessionEvent se)

Whenever an HttpSession object is about to be destroyed, the Web container will call the sessionDestroyed() method and pass the HttpSessionEvent event object to this method.

ServletRequestListener interface

The ServletRequest object is used to obtain the request data sent by the client. In order to listen to the creation and destruction process of the ServletRequest object, the Servlet API provides the ServletRequestListener interface. When one or more event listeners that implement the ServletRequestListener interface are registered in the Web application, When creating or destroying each ServletRequest object, the Web container will generate a ServletRequestEvent event event object, and then call the corresponding processing relationship in each ServletRequest event listener in turn.
(1) RequestInitialized() method

public void requestInitialized(servletRequestEvent sre)

Whenever a ServletRequest object is created, the Web container will call the requestInitialized() method, and the requestInitialized() method will receive a parameter of ServletRequestEvent type. This parameter can be used inside the requestInitialized() method to obtain the currently created ServletRequest object.
(2) requestDestroyed() method
Syntax definition:

pubic voidrequestDestroyed(ServletRequestEvent sre)

Whenever a ServletRequest object is destroyed, the Web container will call the requestDestroyed() method and pass the ServletRequestEvent object to this method.

Example:
Listen to the lifecycle of domain objects
(1) Create a project and create a CN in the project itcast. chapter05. Listener package, in which a MyListener class is written. This class implements three listener interfaces: ServletContextListener, HttpSessionListener and ServletRequestListener.

  package cn.itcast.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class MyListener implements ServletRequestListener, HttpSessionListener, ServletContextListener {
    public void contextInitialized(ServletContextEvent arg0)  { 
    	System.out.println("ServletContext Object was created");
    }
    public void contextDestroyed(ServletContextEvent arg0)  { 
    	System.out.println("ServletContext The object was destroyed");
    }
    public void sessionCreated(HttpSessionEvent arg0)  { 
    	System.out.println("HttpSession Object was created");
    }
    public void sessionDestroyed(HttpSessionEvent arg0)  { 
    	System.out.println("HttpSession The object was destroyed");
    }    
    public void requestInitialized(ServletRequestEvent arg0)  { 
    	System.out.println("ServletRequest Object was created");
    }
    public void requestDestroyed(ServletRequestEvent arg0)  { 
    	System.out.println("ServletRequest The object was destroyed");
    }
}

(2) On the web Configure the MyListener event listener in the XML file

<listener>
  	<listener-class>cn.itcast.listener.MyListener</listener-class>
</listener>

Start the tomcat server.

(3) Write a simple myjsp JSP file to view the operation of httpsessionlister and ServletRequestListener listeners.

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
	first.jsp
</body>
</html>


(4) In order to find out the destruction process of HttpSession object as soon as possible, on the web Set the timeout time of session under XML file to 2min. The specific code is as follows:

<session-config>
		<session-timeout>2</session-timeout>
</session-config>

Restart the Web server and run myjsp JSP file, close access to myjsp The browsing window of JSP page or the browser window will not be refreshed, and the corresponding HttpSession object will be destroyed after 2min.

Listening for attribute changes of domain objects

ServletContext, HttpSession and ServletRequest objects can be created, deleted and modified to listen for changes in the properties of these three objects. ServletContextAttributeListener, HttpSessionAttributeListener, and ServletRequestAttributeListener interfaces.

Interface for monitoring object attribute changes

1.attributeAdded() method
When adding an attribute to the monitored domain object, the Web container will call the attributeAdded method of the event listener to respond. This method receives a time type parameter. The listener can use this parameter to obtain the domain object adding the attribute and the attribute object saved in the domain. The syntax is defined as:

public void attributeAdded(ServletContextAtttributeEvent scab)

The above is the method defined in the ServletContextAttributeListener interface. When an attribute is added to the ServletContext, the Web will call this method and pass a ServletContextEvent type parameter.

public void attributeAdded(HttpSessionBindEvent se)

The above is the method defined by the ServletRequestAttributeListener interface. When an attribute is added to the HttpSession object, the Web container will call this method and pass a parameter of HttpSessionBindingEvent type.

public void attributeAdded(ServletRequestAttributeEvent sare)

The above is the method defined by the ServletRequestAttributeListener interface. When an attribute is added to ServletRequest, the Web container will call this method and pass a parameter of ServletRequestAttributeEvent type.

2.attributeRemoved() method
When deleting an attribute in the monitored object, the Web container calls the attributeRemoved() method of the event listener to respond. The syntax is defined as:

public void attributeRemove(ServletContextAttributeEvent scab)
public void attributeRemove(HttpSessionBindEvent se)
public void attributeRemove(ServletRequestAttributeEvent sare)

3.attributeReplace() method
When an attribute in the listener's domain object is replaced, the Web container will call the attributeReplaced() method of the event listener to respond. The syntax is defined as follows:

public void attributeReplaced(ServletContextAttributeEvent scab)
public void attributeReplaced(HttpSessionBindEvent se)
public void attributeReplaced(ServletRequestAttributeEvent sare)

Listening for attribute changes of domain objects

(1) Write a testattribute JSP page, which is used to observe the function of each domain object attribute event listener.

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h3>This is a test interface</h3>
<%
	getServletContext().setAttribute("username", "itcast");
	getServletContext().setAttribute("username", "itheima");
	getServletContext().removeAttribute("username");
	session.setAttribute("username", "itcast");
	session.setAttribute("username", "itheima");
	session.removeAttribute("username");
	request.setAttribute("username", "itcast");
	request.setAttribute("username", "itcast");
	request.removeAttribute("username");
%>
</body>
</html>

(2) Write a MyAttributeListener class that implements the interfaces of ServletContextAttributeListener, HttpSessionAttributeListener and ServletRequestAttributeListener.

package cn.itcast.listener;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

public class MyAttributeListener implements ServletContextAttributeListener, HttpSessionAttributeListener, ServletRequestAttributeListener {
    public MyAttributeListener() {
    }

    public void attributeAdded(ServletContextAttributeEvent scae)  { 
    	String name=scae.getName();
    	System.out.println("ServletContext Add attribute:"+name+"="+scae.getServletContext().getAttribute(name));
    }

    public void attributeRemoved(ServletContextAttributeEvent scae)  { 
        String name=scae.getName();
        System.out.println("ServletContext The deleted attribute is:"+name+"="+scae.getServletContext().getAttribute(name));
    }

	
    public void attributeRemoved(ServletRequestAttributeEvent srae)  { 
         String name=srae.getName();
         System.out.println("ServletRequest Remove attribute:"+name+"="+srae.getServletRequest().getAttribute(name));
    }

    public void attributeAdded(ServletRequestAttributeEvent srae)  { 
    	String name=srae.getName();
        System.out.println("ServletRequest Add attribute:"+name+"="+srae.getServletRequest().getAttribute(name));
    }

	
    public void attributeReplaced(ServletRequestAttributeEvent srae)  { 
    	String name=srae.getName();
        System.out.println("ServletRequest Replace attribute:"+name+"="+srae.getServletRequest().getAttribute(name));
    }

	
    public void attributeAdded(HttpSessionBindingEvent se)  { 
        String name=se.getName();
        System.out.println("HttpSession Add attribute:"+name+"="+se.getSession().getAttribute(name));
    }

	
    public void attributeRemoved(HttpSessionBindingEvent se)  { 
    	 String name=se.getName();
         System.out.println("HttpSession Remove attribute:"+name+"="+se.getSession().getAttribute(name)); 
    }
    public void attributeReplaced(HttpSessionBindingEvent se)  { 
    	 String name=se.getName();
         System.out.println("HttpSession Replace attribute:"+name+"="+se.getSession().getAttribute(name)); 
    }

	
    public void attributeReplaced(ServletContextAttributeEvent scae)  { 
        String name=scae.getName();
        System.out.println("ServletContext Replace attribute:"+name+"="+scae.getServletContext().getAttribute(name));
    }
	
}

(3) Modify web XML file,

 <listener>
  	<listener-class>cn.itcast.listener.MyAttributeListener</listener-class>
  </listener>

(4) Start the Web server and enter in the address bar http://localhost:9090/Listener/testattribute.jsp

Sense the time listener bound by HttpSession

In program development, the Session domain is often used to store objects. No object has various states in this domain. If it is saved to the Session, unbind it from the Session, persist it to a storage device with the Session object, and recover it from a storage device with the Session object.

HttpSessionBindingListener interface

When using a JavaBean object, you often judge whether the object is bound to the HttpSessionBindingListener interface, which is used to listen for events when the JavaBean object is bound to and unbound from the HttpSession object. The HttpSessionBindingListener interface defines two methods:
1.valueBound() method
Syntax is defined as

public void valueBound(HttpSessionBindingEvent event)

When the object is kidnapped into the HttpSession object, the Web container will call the valueBound() method of the object and pass an event object of HttpSessionBindingEvent type. The program can obtain the HttpSession object to be bound through this event object.
2.valueUnbound() method
Syntax is defined as

public void valueUnbound(HttpSessionBindingEvent event)

When the object is unbound from the HttpSession object, the Web container will also call the valueUnbound() method and pass an event object of type HttpSessionBindingEvent.
Example:
Write a mybean java

package cn.itcast.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;


public class Mybean implements HttpSessionBindingListener {

    
    public Mybean() {
    }

	
    public void valueBound(HttpSessionBindingEvent event)  { 
        System.out.println("Mybean Object is added to Session field..."+this);
    }

	
    public void valueUnbound(HttpSessionBindingEvent event)  { 
         System.out.println("MyBean Object from Session Removed from..."+this);
    }
	
}

Write testbinding jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" import="cn.itcast.listener.Mybean"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
	<%
		session.setAttribute("MyBean",new Mybean());
	%>
</body>
</html>

Start the Web server and open the browser for input http://localhost:9090/Listener/testbinding.jsp

Click refresh

HttpSessionActivationListener interface

In some special cases, the Servlet container will transfer these Http objects from memory to hard disk. This process is called persistence (passivation). When persisting a session, the Servlet container will not only persist the HttpSession object, but also persist all its serializable attributes, so as to ensure that the shared data stored in the session range will not be lost. When a session changes from a persistent state to a running state, it is called activation.
In order to listen to the process of object activation and passivation in HttpSession, the Servlet API specifically provides the HttpSessionActivationListener interface, which defines two methods.
1. Sessionwillactivate() method
Syntax definition:

public void sessionWillPassivate(HttpSessionEvent se)

Before the object bound to the HttpSession object will be passivated with the HttpSession object, the Web container will call this method and pass an event object of HttpSessionEvent type. The program can obtain the previously passivated HttpSession object through this event object.
2.sessionDidActivate() method
Syntax definition:

public void sessionDidActivate(HttpSessionEvent se)

After binding to the HttpSession object to be activated, the Web container calls this method and passes an event object of type HttpSessionEvent.
Example:
Open < Tomcat installation directory > \ conf \ context XML file, add the following information to the < context > element.

<Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
	<Store className="org.apache.catalina.session.FileStore" directory="root"/>
</Manager>

The < manager > element is specifically used to configure the Session manager, and its className attribute is used to specify that it is responsible for creating, destroying and persisting sessions.
The maxIdleSwap property is used to specify the idle time interval during which the Session is deleted.
The < store > element is a class that is responsible for completing specific persistence tasks.
The directory property specifies the directory where the persistent files are saved.
(2) Write a mybean2 Java class, which implements the HttpSessionActivationListener interface and all methods in this interface.

package cn.itcast.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionEvent;


public class MyBean2 implements HttpSessionActivationListener {
	private String name;
	private int age;
	public String getName(){
		return name;
	}
	public void setName(String name){
		this.name=name;
	}
	public void setAge(int age){
		this.age=age;
	}
	public int getAge(){
		return age;
	}
    public void sessionDidActivate(HttpSessionEvent se)  { 
         System.out.println("MyBean The object is activated");
    }
    public void sessionWillPassivate(HttpSessionEvent se)  { 
        System.out.println("MyBean The object is passivated");
    }
	
}

(3) Write a write JSP page. On this page, the MyBean2 object is saved to the Session object. The Session binding event that MyBean2 perceives has been viewed.

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" import="cn.itcast.listener.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
	<h1>towards Session Data stored in</h1>
	<%
		MyBean2 myBean=new MyBean2();
	myBean.setName("TOM");
	myBean.setAge(20);
		session.setAttribute("myBean",myBean);
	%>
</body>
</html>

(4) Write a read JSP page, which reads the objects in the Session field

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="cn.itcast.listener.MyBean2"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>from Session Read data from domain</h1>
full name: ${sessionScope.myBean.name}
Age: ${sessionScope.myBean.age}
</body>
</html>

Start the server and enter the address in the address bar http://localhost:9090/Listener/write.jsp

Start the server and enter the address in the address bar http://localhost:9090/Listener/read.jsp


Visit again http://localhost:9090/Listener/read.jsp

Topics: Java Database SQL