Listener listener in Java Web

Listener in servlet
Listeners in servlet s are used to listen to common web objects HttpServletRequest, httpsession, and ServletContext. It mainly has the following three functions:

  1. Listen for web object creation and destruction.
  2. Listen for changes in the properties of web objects and add, delete and modify them.
  3. Listen for session binding javaBean operations, activation (read from hard disk to memory) and passivation (persist from memory to hard disk).

When the listener finds that the monitored object has changed, it can do some operations.

There are 8 listeners in the servlet. They are classified as follows according to their functions:

  • A listener that listens to the creation and destruction of web objects
    • ServletContextListener
    • HttpSessionListener
    • ServletRequestListener
  • A listener that listens for changes in web object properties
    • ServletContextAttributeListener
    • HttpSessionAttributeListener
    • ServletRequestAttributeListener
  • Listener that listens for session bound javaBean operations
    • HttpSessionBindingListener
    • HttpSessionActivationListener
      Creation and use of listeners
      Steps to create a listener for javaweb:

Create a class that implements the specified listener interface
Override methods in interfaces
Configuring listeners in the web.xml file
Creation and destruction of listening objects
The following is a demonstration of listening to the destruction and creation of the HttpServletRequest object.

1. Create a class to implement ServletRequestListener interface:

package com.monkey1024.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

public class MyRequestListener implements ServletRequestListener {

}

2. Rewrite the methods in the interface:

package com.monkey1024.listener;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;

public class MyRequestListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        System.out.println("request Object destroyed");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        System.out.println("request Created");
    }


}

3. Configure the listener in the web.xml file

<listener>
      <listener-class>com.monkey1024.listener.MyRequestListener</listener-class>
</listener>

When the client sends a request, you can see the "request object destroyed" and "request created" printed out by the console.

Similarly, when listening to the creation and destruction of httpsession objects, you need to create a class to implement the HttpSessionListener interface and override the methods in it.
Under what circumstances will the session be destroyed:

The default timeout is 30 minutes
Shut down the server
invalidate() method
Setmaxinactivitinterval (int interval) you can set the timeout
When listening for the creation and destruction of ServletContext objects, create a class to implement the ServletContextListener interface and override the methods inside.

Changes in listening properties
Take listening to add, modify and delete attributes in HttpServletRequest object as an example:

1. Create a class to implement ServletRequestAttributeListener interface:

package com.monkey1024.listener;

import javax.servlet.ServletRequestAttributeListener;

public class MyRequestAttributeListener implements ServletRequestAttributeListener {


}

2. Rewrite the methods in the interface:

package com.monkey1024.listener;

import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;

public class MyRequestAttributeListener implements ServletRequestAttributeListener {

    @Override
    public void attributeAdded(ServletRequestAttributeEvent srae) {
        System.out.println("towards request Added a property to");
        System.out.println("Property name:"+srae.getName());
        System.out.println("Attribute value:"+srae.getValue());
    }

    @Override
    public void attributeRemoved(ServletRequestAttributeEvent srae) {
        System.out.println("from request A property was deleted in");
        System.out.println("Property name:"+srae.getName());
        System.out.println("Attribute value:"+srae.getValue());
    }

    @Override
    public void attributeReplaced(ServletRequestAttributeEvent srae) {
        System.out.println("Modified request A property in");
        System.out.println("Property name:"+srae.getName());
        System.out.println("Attribute value:"+srae.getValue());
    }


}

3. Register the listener in the web.xml file:

<listener>
      <listener-class>com.monkey1024.listener.MyRequestAttributeListener</listener-class>
</listener>

4. Create index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        request.setAttribute("name", "monkey1024");
        request.setAttribute("name", "admin");
        request.removeAttribute("name");
    %>
</body>
</html>

When the client accesses index.jsp, you can see the following on the console:

towards request Added a property to
 Property name: name
 Attribute value: monkey1024
 Modified request A property in
 Property name: name
 Attribute value: monkey1024
 from request A property was deleted in
 Property name: name
 Attribute value: admin

The operation of listening for attribute changes in ServletContext and HttpSession is the same as above.

Listening session binding javabean
The HttpSessionBindingListener listener enables a javaBean object to be notified when it is bound to or unbound from a session. The listener is implemented by an entity class. It should be noted that the implementation class of the listener does not need to be configured in the web.xml file.

1. Create a Student class to implement the HttpSessionBindingListener interface:

package com.monkey1024.listener;

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

public class Student implements HttpSessionBindingListener {

    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }


}

2. Rewrite the methods in the interface:

package com.monkey1024.listener;

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

public class Student implements HttpSessionBindingListener {

    private String name;
    private int age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public void valueBound(HttpSessionBindingEvent event) {
        System.out.println("Student Object is added to session in");
    }
    @Override
    public void valueUnbound(HttpSessionBindingEvent event) {
        System.out.println("Student Object from session Deleted in");
    }


}

3. Add the following code in index.jsp:

Student s = new Student();
session.setAttribute("student", s);
session.removeAttribute("student");

When the client accesses index.jsp, you will see the following information in the console:

The Student object is added to the session
The Student object was deleted from the session
Listen for passivation and activation of objects of specified type stored in Session (understand)
HttpSessionActivationListener this listener is used to listen for the passivation and activation of objects of the specified type stored in the Session.
Passivation refers to writing the data in memory to the hard disk, while activation refers to restoring the data in the hard disk to memory. When used
The application that the user is accessing or the server where the application is located is stopped for various reasons, and then restarted in a short time. At this time, the data in the Session cannot be lost when the user accesses. Before the application is closed, the data needs to be persisted to the hard disk,
The data in the Session can be recovered immediately after restart. This is called Session passivation and activation.
What data in the Session can be passivated? Only those stored in the JVM heap memory implement Serializable
Class can be passivated. That is, string constants and basic data type constants are stored in JVM methods
Constants in the constant pool in the region cannot be passivated.
For passivation and activation of object data in listening Session, the following points should be noted:

  • In addition to the HttpSessionActivationListener interface, the entity class also needs to implement the Serializable interface.
  • Passivation refers to the passivation of object data in a Session, not a Session. So Session
    Passivation occurs several times when there are several objects that can be passivated.
  • The HttpSessionActivationListener listener does not need to be registered in web.xml.

1. Create a Person class to implement HttpSessionActivationListener and Serializable interfaces:

package com.monkey1024.listener;

import java.io.Serializable;

import javax.servlet.http.HttpSessionActivationListener;

public class Person implements HttpSessionActivationListener, Serializable {


    private String name;
    private int age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }


}

2. Override the method in the HttpSessionActivationListener interface:

package com.monkey1024.listener;

import java.io.Serializable;

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

public class Person implements HttpSessionActivationListener, Serializable {


    private String name;
    private int age;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public void sessionWillPassivate(HttpSessionEvent se) {
        System.out.println("passivation"+se.getSession().getId());
    }
    @Override
    public void sessionDidActivate(HttpSessionEvent se) {
        System.out.println("activation"+se.getSession().getId());
    }



}

3. Write the following in index.jsp:

<%
    Person p = new Person();
    session.setAttribute("person", p);
%>

4. Create a content.xml file in the META-INF directory of the project, and write the following contents in it:

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
    <Store className="org.apache.catalina.session.FileStore" directory="monkey1024"/>
    </Manager>
</Context>

Through the above settings, session can be passivated and activated.
Start tomcat to access the index.jsp file. After closing tomcat normally, you can see the console output "passivation". Start tomcat again and you can see the console output "activation".

Tags: Java Back-end

Posted on Wed, 03 Nov 2021 15:37:40 -0400 by benyboi