Updated March 28, 2023
Definition of Servlet Listener
- A Servlet listener is a servlet method or function that awaits the occurrence of an event.
- Servlet Listeners are classes that monitor a specific type of event and activate functionality when that event happens.
- Servlet Listener works for listening to events in web containers like a session is created, an attribute is inserted into a session, or a container is activated.
What is servlet listener?
Servlet Listener is used for listening to events in web containers, such as when you create a session, insert an attribute, passivate and activate in another container. The servlet container generates events that trigger the action of event listener classes. To subscribe to these events, you configure listeners in web.xml, such as HttpSessionListener.
In other words, the servlet container invokes the event listener class’s functions. Following is a summary of this procedure: The user creates an event listener class that implements one of the listener interfaces.
Steps for Using servlet listener
If you want to use listener listeners in our web applications, we must do the following steps:
Step 1: Prepare the Listener class.
Take one user-defined class, which must implement the Listener interface. Consider, for example, that the public class Listener is implemented by MyListener.
public class MyListenerdemo implements ServletContextListener{
public void contextInitializes(ServletContextEvent event) {
write code here!
}
}
Step 2: Use the Listener tag and classes in the web.xml file.
To configure the servlet listener tag and class in the XML file. The web.xml file must have the following XML tags:
<web-app>
……
<listener>
<listener-class>
Name of the class Listener/listener-class>
</listener>
……
</web-app>
Except for HttpSessionBindingListener and HttpSessionActivationListener, all Listeners require the setup described above.
Event Servlet Listener
Servlet API offers many types of listeners for various types of Events. Listener interfaces describe methods for interacting with a group of related events; for instance, the ServletContext Listener interface listens for context startup and shutdown events.
Each method in the listener interface accepts an Event object as an argument. Event object functions as a container to deliver specified objects to listeners.
The Servlet API provides the subsequent event objects:
- servlet.AsyncEvent
The event is triggered when an asynchronous action is launched on a ServletRequest. The events call to the “ServletRequest.startAsync” event which are ServletRequest, ServletResponse. The servlet request can complete, failed, or timeout.
- servlet.http.HttpSessionBindingEvent
The object’s event implements the servlet HttpSessionBindingListener interface when the event attribute is bound or unbound from a session. When an attribute is attached, unbounded, and updated from a session, the event object implements the servlet SessionAttributeListener interface.
A call to HttpSession.setAttribute attaches the object, and a call to HttpSession.removeAttribute unbinds the item.
This event can be used for cleanup after an item is withdrawn from the session.
- servlet.http.HttpSessionEvent
The servlet event class uses to notify session modifications in the web application.
- servlet.ServletContextAttributeEvent
The servlet event class uses to notify listeners of modifications to the ServletContext attributes in the web application.
- servlet.ServletContextEvent
The servlet event class uses to notify a web application of changes to the servlet context.
- servlet.ServletRequestEvent
The servlet event class represents ServletRequest lifecycle events. The origin of the event is the web application’s ServletContext.
- servlet.ServletRequestAttributeEvent
The servlet event class uses to notify an application of changes to the servlet request’s characteristics.
Servlet Listener Parameters
Servlet Listener interfaces are offered by the Servlet API.
- servlet.AsyncListener interface
A listener interface uses to alert if an asynchronous action is launched on a ServletRequest. The servlet actions are completed, occur error, timed out, or failed.
- servlet.ServletContextListener interface
The interface uses to receive notification events regarding changes to the ServletContext lifecycle.
- servlet.ServletContextAttributeListener interface
The interface uses to receive the attribute change notification events from ServletContext.
- servlet.ServletRequestListener interface
The interface uses to receive notifications of requests entering and leaving the scope of a web application.
- servlet.ServletRequestAttributeListener interface
Interface for getting event notifications regarding attribute changes on ServletRequest objects.
- servlet.http.HttpSessionListener interface
Interface for receiving HttpSession lifecycle change notice events. The listener notifies an item when the attribute is bound or released in a session.
- servlet.http.HttpSessionAttributeListener interface
The interface uses to receive event notifications on attribute changes in HttpSession.
- servlet.http.HttpSessionActivationListener interface
The object is associated with a session that listens to events and informs them that sessions will be deactivated. After, the session in question is going to be activated. When a session begins, a container migrates across persists in sessions and notifies all associated characteristics. This session must implement HttpSessionActivationListener interface with class.
Example
Below is the example:
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>ServletListenersEducba</display-name>
<context-param>
<param-name>DBUSER</param-name>
<param-value>name</param-value>
</context-param>
<context-param>
<param-name>DBPWD</param-name>
<param-value>password</param-value>
</context-param>
<context-param>
<param-name>DBURL</param-name>
<param-value>jdbc:mysql://localhost/mysql_db</param-value>
</context-param>
<listener>
<listener-class>com.educba.listener.AppContextListeners</listener-class>
</listener>
<listener>
<listener-class>com.educba.listener.AppContextAttributeListeners</listener-class>
</listener>
<listener>
<listener-class>com.educba.listener.MySessionListeners</listener-class>
</listener>
<listener>
<listener-class>com.educba.listener.MyServletRequestListeners </listener-class>
</listener>
</web-app>
DatabaseManagers.java
package com.educba.db;
import java.sql.Connection;
public class DatabaseManagers {
private String databaseURL;
private String databaseuser;
private String databasepassword;
private Connection databasecon;
public DatabaseManager(String databaseurl, String databaseu, String databasep)
{
this. databaseURL = databaseurl;
this. databaseuser = databaseu;
this. databasepassword = databasep;
// create database connection here!
}
public Connection getConnection() { return this. databasecon; }
public void closeConnection()
{
// close database connection here!
}
}
AppContextAttributeListeners.java
package com.educba.listener;
import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AppContextAttributeListeners implements
ServletContextAttributeListener {
public void
attributeAdded(ServletContextAttributeEvent servletContxtAttribtEvnt)
{
System.out.println( "ServletContext attribute added::{"
+ servletContxtAttribtEvnt.getName() + ","
+ servletContxtAttribtEvnt.getValue()
+ "}");
}
public void
attributeReplaced(ServletContextAttributeEvent
servletContxtAttribtEvnt)
{
System.out.println(
"ServletContext attribute replaced::{"
+ servletContxtAttribtEvnt.getName() + ","
+ servletContxtAttribtEvnt.getValue()
+ "}");
}
public void
attributeRemoved(ServletContextAttributeEvent
servletContxtAttribtEvnt)
{
System.out.println(
"ServletContext attribute removed::{"
+ servletContxtAttribtEvnt.getName() + ","
+ servletContxtAttribtEvnt.getValue()
+ "}");
}
}
AppContextListeners.java
package com.educba.listener;
import com.educba.db.*;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class AppContextListeners implements
ServletContextListener {
public void contextInitialized(
ServletContextEvent servletContextEvent)
{
ServletContext srvlctx = servletContextEvent.getServletContext();
String databaseurl = srvlctx.getInitParameter("DBURL");
String databaseu = srvlctx.getInitParameter("DBUSER");
String databasep = srvlctx.getInitParameter("DBPWD");
DatabaseManager databaseManager = new DatabaseManager(databaseurl, databaseu, databasep);
srvlctx.setAttribute("DBManager", databaseManager);
System.out.println(
"Database connection initialized.");
}
public void contextDestroyed(
ServletContextEvent servletContextEvent)
{
ServletContext srvlctx = servletContextEvent.getServletContext();
DatabaseManager databaseManager = (DatabaseManager)srvlctx.getAttribute(
"DBManager");
databaseManager.closeConnection();
System.out.println(
"Database connection closed.");
}
}
MyServletRequestListeners.java
package com.educba.listener;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class MyServletRequestListeners
implements ServletRequestListener {
public void requestDestroyed(
ServletRequestEvent servletRequestEvent)
{
ServletRequest servletRequest
= servletRequestEvent.getServletRequest();
System.out.println(
"ServletRequest destroyed. Remote IP="
+ servletRequest.getRemoteAddr());
}
public void requestInitialized(
ServletRequestEvent servletRequestEvent)
{
ServletRequest servletRequest
= servletRequestEvent.getServletRequest();
System.out.println(
"ServletRequest initialized. Remote IP="
+ servletRequest.getRemoteAddr());
}
}
MySessionListeners.java
package com.educba.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class MySessionListeners
implements HttpSessionListener {
public void
sessionCreated(HttpSessionEvent sessionEvent)
{
System.out.println(
"Session Created:: ID="
+ sessionEvent.getSession().getId());
}
public void
sessionDestroyed(HttpSessionEvent sessionEvent)
{
System.out.println(
"Session Destroyed:: ID="
+ sessionEvent.getSession().getId());
}
}
MyServletFinal.java
package com.educba.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/MyServlet")
public class MyServletFinal extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
ServletContext srvlctx = request.getServletContext();
srvlctx.setAttribute("User", "Educba Tutor");
String users = (String)srvlctx.getAttribute("User");
srvlctx.removeAttribute("User");
HttpSession session = request.getSession();
session.invalidate();
PrintWriter out = response.getWriter();
out.write("Hello " + users);
}
}
Output
Conclusion
The servlet listener is an essential part of the application. It creates the required event with the database and displays the needed value. It works for large size applications with complicated databases.
Recommended Articles
This is a guide to Servlet Listener. Here we discuss the Definition, What is a servlet listener, Steps for Using servlet listener and examples with code implementation respectively. You may also have a look at the following articles to learn more –