Listeners in servlets in java

Servlet Events and Listeners

In GUI applications, once we click on a button, once we select an item in checkboxes, once we select an item within the list choice boxes, automatically the respective GUI component may raise the respective events.

In GUI applications, all the GUI components are capable of raising the events only, they’re unable of handling the events. In the above context, to handle the events all the GUI components will bypass the generated events to a separate implicit component called as Listener.

The main role of Listener in GUI applications is to concentrate an occasion from the respective GUI component, handle it by executing Listener methods, and remit the response to GUI application. The above process in GUI applications is treated as Event Handling or Event Delegation Model.

In GUI applications, all the events are represented by some predefined classes, and every one of the Listeners is represented within the sort of interface. Similarly, in web application execution, a container may generate events at the time of making a request object, adding an attribute, replacing an attribute, removing an attribute, and destroying the request object.

In this context, to concentrate the events generated by the container and to handle those events Servlet API has provided a group of interfaces called Servlet Listeners. Therefore, the most purpose of Servlet Listeners is to read all the life cycle stages of the request object, the servlet Context object, and HttpSession objects.

The servlet specification includes the potential to trace key events in your Web applications through event listeners. This functionality allows more efficient resource management and automatic processing supported event status.

Читайте также:  Conda environment change python version
Event Categories and Listener Interfaces

There are two levels of servlet events:

  1. Servlet context-level (application-level) event: It involves resources or state held at the extent of the appliance servlet context object.
  2. Session-level event: It involves resources or state related to the series of requests from one user session; that’s, related to the HTTP session object.

We can create one or more event listener classes for each of the four-event categories. One listener class can monitor multiple event categories. An occasion class is often created by implementing an interface or interfaces of the javax.servlet package or javax.servlet.http package.

Event Listener Interfaces
  1. javax.servlet.ServletContextListener: It is a Lifecycle change in event categories. It is used for servlet context creation, at which point the first request can be serviced.
  2. javax.servlet.ServletContextAttributeListener: It is attribute changes event categories. It is used for the addition, removal, and replacement of servlet context attributes.
  3. javax.servlet.http.HttpSessionListener: It is also lifecycle changes even categories. It is used for session creation, invalidation, and timeout.
  4. javax.servlet.http.HttpSessionAttributeListener: It is attributes changes event categories. It is used for the addition, removal, and replacement of session attributes.
Steps to use Listeners:

If we want to use listeners in our web applications then we have to use the following steps:

Step-1: Prepare Listener class

Here take one user-defined class, it must be an implementation class to Listener interface.

Example: public class MyListener implements Listener<…….)

Step-2: Configure Listener class in web.xml file

To configure the Listener class in the web.xml file we have to use the following XML tags:

 ……………. Fully Qualified name of Listener class  ………… 

The above listener configuration is required for all Listener except HttpSessionBindingListener and HttpSessionActivationListener.

Event Listener methods and Related Classes
ServletContextListener Methods and ServletContextEvent Class
  1. void contextInitialized(ServletContextEvent sce): This method is used to notify the listener that the servlet context has been created and the application is ready to process requests.
  2. void contextDestroyed(ServletContextEvent sce): This method is used to notify the listener that the application is about to be shut down.

The ServletContextEvent is notified when a web application is deployed on the server. It includes the following method, which your listener can call:

ServletContext getServletContext(): It is used to retrieve the servlet context object that was created or is about to be destroyed, from which you can obtain information as desired.

ServletContextAttributeListener Methods and ServletContextAttributeEvent Class
  1. void attributeAdded(ServletContextAttributeEvent scae): It is used to notify the listener that an attribute was added to the servlet context.
  2. void attributeRemoved(ServletContextAttributeEvent scae): It is used to notify the listener that an attribute was removed from the servlet context.
  3. void attributeReplaced(ServletContextAttributeEvent scae): It is used to notify the listener that an attribute was replaced in the servlet context.

ServletContextAttributeEvent is the event class for notifications about changes to the attributes of the servlet context of a web application. It includes the following methods, which your listener can call:

  1. String getName(): It is used to get the name of the attribute that was added, removed, or replaced.
  2. Object getValue(): It is used to get the value of the attribute that was added, removed, or replaced. In the case of an attribute that was replaced, this method returns the old value, not the new value.
HttpSessionListener Methods and HttpSessionEvent Class
  1. void sessionCreated(HttpSessionEvent hse): It is used to notify the listener that a session was created.
  2. void sessionDestroyed(HttpSessionEvent hse): It is used to notify the listener that a session was destroyed.
  1. HttpSession getSession(): This method is used to retrieve the session object that was created or destroyed.
HttpSessionAttributeListener Methods and HttpSessionBindingEvent Class

HttpSessionAttributeListener specifies the following methods:

  1. void attributeAdded(HttpSessionBindingEvent hsbe): It is used to notify the listener that an attribute was added to the session.
  2. void attributeRemoved(HttpSessionBindingEvent hsbe): It is used to notify the listener that an attribute was removed from the session.
  3. void attributeReplaced(HttpSessionBindingEvent hsbe): It is used to notify the listener that an attribute was replaced in the session.
  1. String getName(): It is used to get the name of the attribute that was added, removed, or replaced.
  2. Object getValue(): It is used to get the value of the attribute that was added, removed, or replaced. In the case of an attribute that was replaced, this method returns the old value, not the new value.
  3. HttpSession getSession(): It is used to retrieve the session object that had the attribute change.
Example: Servlet Listener Example

Let’s create a simple web application to see the servlet listener in action. We will create a dynamic web project in Eclipse ServletListenerExample those project structures will look like the below image.

Java Servlet Events and Listeners with Examples

Here, web.xml will define some context init params and listener configuration. DBConnectionManager is the class for database connectivity. We will set the object as an attribute to the servlet context. MyServlet is where I will work with the session, attributes, etc. AppContextListener is where we will read servlet context init parameters to create the DBConnectionManager object and set it as an attribute to the ServletContext object. ServletContextAttributeListener is a simple implementation to log the event when an attribute is added, removed, or replaced in the servlet context. HttpSessionListener is a simple implementation to log the event when the session is created or destroyed. ServletRequestListener is to log the servletRequest IP address when the request is initialized and destroyed.

web.xml
  ServletListenerExample DBUSER manisha  DBPWD password  DBURL jdbc:mysql://localhost/mysql_db  com.listener.AppContextListener  com.listener.AppContextAttributeListener  com.listener.MySessionListener  com.listener.MyServletRequestListener   
DBConnectionManager.java
package com.db; import java.sql.Connection; public class DBConnectionManager < private String dbURL; private String user; private String password; private Connection con; public DBConnectionManager(String url, String u, String p)< this.dbURL=url; this.user=u; this.password=p; //create db connection now >public Connection getConnection() < return this.con; >public void closeConnection() < //close DB connection here >>
AppContextAttributeListener.java
package com.listener; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.annotation.WebListener; @WebListener public class AppContextAttributeListener implements ServletContextAttributeListener < public void attributeAdded(ServletContextAttributeEvent servletContextAttributeEvent) < System.out.println("ServletContext attribute added::"); > public void attributeReplaced(ServletContextAttributeEvent servletContextAttributeEvent) < System.out.println("ServletContext attribute replaced::"); > public void attributeRemoved(ServletContextAttributeEvent servletContextAttributeEvent) < System.out.println("ServletContext attribute removed::"); > >
AppContextListener.java
package com.listener; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.annotation.WebListener; import com.db.DBConnectionManager; @WebListener public class AppContextListener implements ServletContextListener < public void contextInitialized(ServletContextEvent servletContextEvent) < ServletContext ctx = servletContextEvent.getServletContext(); String url = ctx.getInitParameter("DBURL"); String u = ctx.getInitParameter("DBUSER"); String p = ctx.getInitParameter("DBPWD"); //create database connection from init parameters and set it to context DBConnectionManager dbManager = new DBConnectionManager(url, u, p); ctx.setAttribute("DBManager", dbManager); System.out.println("Database connection initialized for Application."); >public void contextDestroyed(ServletContextEvent servletContextEvent) < ServletContext ctx = servletContextEvent.getServletContext(); DBConnectionManager dbManager = (DBConnectionManager) ctx.getAttribute("DBManager"); dbManager.closeConnection(); System.out.println("Database connection closed for Application."); >>
MyServletRequestListener.java
package com.listener; import javax.servlet.ServletRequest; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.annotation.WebListener; @WebListener public class MyServletRequestListener 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()); >>
MySessionListener.java
package com.listener; import javax.servlet.annotation.WebListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; @WebListener public class MySessionListener implements HttpSessionListener < public void sessionCreated(HttpSessionEvent sessionEvent) < System.out.println("Session Created:: >public void sessionDestroyed(HttpSessionEvent sessionEvent) < System.out.println("Session Destroyed:: >>
MyServlet.java
package com.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 MyServlet extends HttpServlet < private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException < ServletContext ctx = request.getServletContext(); ctx.setAttribute("User", "Manisha"); String user = (String) ctx.getAttribute("User"); ctx.removeAttribute("User"); HttpSession session = request.getSession(); session.invalidate(); PrintWriter out = response.getWriter(); out.write("Hi "+user); >>
Output

When we will deploy our application and access MyServlet, we will see the following logs in the server log file.

Event and Listener in Servlet

And we will get the below output in the browser.

Event and Listener in Java Servlet

In the next article, I am going to discuss Servlet Wrappers. Here, in this article, I try to explain Event and Listener in Servlet with Examples. I hope you enjoy this Event and Listener in Java Servlet article.

Источник

Оцените статью