-
Notifications
You must be signed in to change notification settings - Fork 0
plor10 edited this page Nov 14, 2018
·
2 revisions
© JOURNALDEV.COM PAGE 43 OF 55 4. Servlet Listener s In this secttion , we will look into servlet listener , benefits of listeners, some c ommon tasks that we can do with listeners, servlet API listener interfaces and Event objects. In the end we will create a simple web project to show example of commonly used Listener implementation for ServletContext , Session and ServletRequest . 1. Why do we have Servlet Listener? 2. Servlet Listener Interfaces and Event Objects 3. Servlet Listener Configuration 4. Servlet Listener Example 1. ServletContextListener implementation 2. ServletContextAttributeListener implementation 3. HttpSessionListener implementation 4. ServletRequ estListener implementation A. Why do we have Servlet Listener? We know that using ServletContext , we can create an attribute with application scope that all other servlets can access but we can initialize ServletContext init parameters as String only in d eployment descriptor (web.xml). What if our application is database oriented and we want to set an attribute in ServletContext for Database Connection. If you application has a single entry point (user login), then you can do it in the first servlet reques t but if we have multiple entry points then doing it everywhere will result in a lot of code redundancy. Also if database is down or not configured properly, we won’t know until first client request comes to server. To handle these scenario, servlet API pr ovides Listener interfaces that we can implement and configure to listen to an event and do certain operations. Event is occurrence of something, in web application world an event can be initialization of application, destroying an application, request fr om client, creating/destroying a session, attribute modification in session etc. Servlet API provides different types of Listener interfaces that we can implement and configure in web.xml to process something when a particular © JOURNALDEV.COM PAGE 44 OF 55 event occurs. For example, in above scenario we can create a Listener for the application startup event to read context init parameters and create a database connection and set it to context attribute for use by other resources. B. Servlet Listener Interfaces and Event Objects Serv let API provides different kind of listeners for different types of Events. Listener interfaces declare methods to work with a group of similar events, for example we have ServletContext Listener to listen to startup and shutdown event of context. Every me thod in listener interface takes Event object as input. Event object works as a wrapper to provide specific object to the listeners. Servlet API provides following event objects. 1. javax.servlet.AsyncEvent – Event that gets fired when the asynchronous operat ion initiated on a ServletRequest (via a call to ServletRequest#startAsync or ServletRequest#startAsync(ServletR equest, ServletResponse)) has completed, timed out, or produced an error. 2. javax.servlet.http.HttpSessionBindingEvent – Events of this type are e ither sent to an object that implements HttpSessionBindingListener when it is bound or unbound from a session, or to a HttpSessionAttributeListener that has been configured in the web.xml when any attribute is bound, unbound or replaced in a session. The s ession binds the object by a call to HttpSession.setAttribute and unbinds the object by a call to HttpSession.removeAttribute. We can use this event for cleanup activities when object is removed from session. 3. javax.servlet.http.HttpSessionEvent – This is t he class representing event notifications for changes to sessions within a web application. © JOURNALDEV.COM PAGE 45 OF 55 4. javax.servlet.ServletContextAttributeEvent – Event class for notifications about changes to the attributes of the ServletContext of a web application. 5. javax.servlet .ServletContextEvent – This is the event class for notifications about changes to the servlet context of a web application. 6. javax.servlet.ServletRequestEvent – Events of this kind indicate lifecycle events for a ServletRequest. The source of the event is t he ServletContext of this web application. 7. javax.servlet.ServletRequestAttributeEvent – This is the event class for notifications of changes to the attributes of the servlet request in an application. Servlet API provides following Listener interfaces. 1. jav ax.servlet.AsyncListener – Listener that will be notified in the event that an asynchronous operation initiated on a ServletRequest to which the listener had been added has completed, timed out, or resulted in an error. 2. javax.servlet.ServletContextListener – Interface for receiving notification events about ServletContext lifecycle changes. 3. javax.servlet.ServletContextAttributeListener – Interface for receiving notification events about ServletContext attribute changes. 4. javax.servlet.ServletRequestListener – Interface for receiving notification events about requests coming into and going out of scope of a web application. 5. javax.servlet.ServletRequestAttributeListener – Interface for receiving notification events about ServletRequest attribute changes. 6. javax. servlet.http.HttpSessionListener – Interface for receiving notification events about HttpSession lifecycle changes. 7. javax.servlet.http.HttpSessionBindingListener – Causes an object to be notified when it is bound to or unbound from a session. 8. javax.servlet .http.HttpSessionAttributeListener – Interface for receiving notification events about HttpSession attribute changes. 9. javax.servlet.http.HttpSessionActivationListener – Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated. A container that migrates session between VMs or persists sessions is required to notify all attributes bound to sessions implementing HttpSessionActivationListener. © JOURNALDEV.COM PAGE 46 OF 55 C. Servlet Listener Config uration We can use @WebListener a nnotation to declare a class as Listener, however the class should implement one or more of the Listener interfaces. We can define listener in web.xml as: <listener
class> </listene r> D. Servlet Listener Example Let’s create a simple web application to see listeners in action. We will create dynamic web project in Eclipse ServletListenerExample those project structure will look like below image. © JOURNALDEV.COM PAGE 47 OF 55 web.xml : In deployme nt descriptor, I will define some context init params and listener configuration.
app xmlns:xsi= "http://www.w3.org/2001/XMLSchema
instance" xmlns= "http://java.sun.com/xml/ns/javaee" xsi:schemaLocation= "http://ja va.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web
app_3_0.xsd" id= "WebApp_ID" version= "3.0"
param>
DBUSER pankaj DBPWD password DBURL jdbc:mysql://localhost/mysql_db com.journaldev.listener.AppContextListener com.journaldev.listener.AppContextAttributeListener com.journaldev.listener.MySessionListener com.journaldev.listener.MyServletRequestListener DBConnectionManager : This is the class for d atabase connectivity, for simplicity I am not providing code for actual database connection. We will set this object as attribute to servlet context. package com. journaldev . db ; import java.sql.Connection ; © JOURNALDEV.COM PAGE 48 OF 55 public class DBConnectionManager { priva te 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 } } MyServlet : A simple servlet class where I will work with sess ion, attributes etc . package com. journaldev . 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.h ttp.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 seri alVersionUID = 1L ; protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext ctx = request. getServletContext (); ctx. setAttribute ( "User" , "Pankaj " ); String user = (String) ctx. getAttribute ( "User" ); ctx. removeAttribute ( "User" ); © JOURNALDEV.COM PAGE 49 OF 55 HttpSession session = request. getSession (); session. invalidate (); PrintWriter out = re sponse. getWriter (); out. write ( "Hi " +user); } } Now we will implement listener classes, I am providing sample listener classes for commonly used listeners – ServletContextListener, ServletContextAttributeListener, ServletRequestListener a nd HttpSessionListener. 1. ServletContextListener implementation We will read servlet context init parameters to create the DBConnectionManager object and set it as attribute to the ServletContext object. package com. journaldev . listener ; import javax.se rvlet.ServletContext ; import javax.servlet.ServletContextEvent ; import javax.servlet.ServletContextListener ; import javax.servlet.annotation.WebListener ; import com.journaldev.db.DBConnectionManager ; @WebListener public class AppContextListener impleme nts 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); © JOURNALDEV.COM PAGE 50 OF 55 System. out . println ( "Database connection initialized for Application." ); } public void contextDestroyed (ServletContextEvent servletContextEvent) { ServletContext ctx = servletContextEve nt. getServletContext (); DBConnectionManager dbManager = (DBConnectionManager) ctx. getAttribute ( "DBManager" ); dbManager. closeConnection (); System. out . println ( "Database connection closed for Application." ); } } 2. Ser vletContextAttributeListener implementation A simple implementation to log the event when attribute is added, removed or replaced in servlet context. package com. journaldev . listener ; import javax.servlet.ServletContextAttributeEvent ; import javax.servl et.ServletContextAttributeListener ; import javax.servlet.annotation.WebListener ; @WebListener public class AppContextAttributeListener implements ServletContextAttributeListener { public void attributeAdded (ServletContextAttributeEvent servletConte xtAttributeEvent) { System. out . println ( "ServletContext attribute added::{" +servletContextAttributeEvent. getName ()+ "," +servletContextAttr ibuteEvent. getValue ()+ "}" ); } public void attributeReplaced (ServletContextAttributeEvent servletContex tAttributeEvent) { System. out . println ( "ServletContext attribute replaced::{" +servletContextAttributeEvent. getName ()+ "," +servletContextA ttributeEvent. getValue ()+ "}" ); } public void attributeRemoved (ServletContextAttributeEvent servletConte xtAttributeEvent) { System. out . println ( "ServletContext attribute removed::{" +servletContextAttributeEvent. getName ()+ "," +servletContextAt tributeEvent. getValue ()+ "}" ); © JOURNALDEV.COM PAGE 52 OF 55 ServletRequest servletRequest = servletRequestEvent. getServletRequest (); System. out . println ( "ServletRequest destroyed. Remote IP=" +servletRequest. getRemoteAddr ()); } public void requestInitialized (ServletRequestEvent servletRequestEvent) { ServletRequest servletRequest = servletRequestEvent. getServletRequest (); S ystem. out . println ( "ServletRequest initialized. Remote IP=" +servletRequest. getRemoteAddr ()); } } Now when we will deploy our application and access MyServlet in browser with URL http://localhost:8080/ServletListenerExample/MyServlet , we will see following logs in the server log file. ServletContext attribute added::{DBManager,com.journaldev.db.DBConnectionManager@4def3d1b} Database connection initialized for Application. ServletContext attribute added::{org.apache.jasper.compiler.TldLocationsCa che,org.apache.jasper. compiler.TldLocationsCache@1594df96} ServletRequest initialized. Remote IP=0:0:0:0:0:0:0:1%0 ServletContext attribute added::{User,Pankaj} ServletContext attribute removed::{User,Pankaj} Session Created:: ID=8805E7AE4CCCF98AFD60142A 6B300CD6 Session Destroyed:: ID=8805E7AE4CCCF98AFD60142A6B300CD6 ServletRequest destroyed. Remote IP=0:0:0:0:0:0:0:1%0 ServletRequest initialized. Remote IP=0:0:0:0:0:0:0:1%0 ServletContext attribute added::{User,Pankaj} ServletContext attribute remove d::{User,Pankaj} Session Created:: ID=88A7A1388AB96F611840886012A4475F Session Destroyed:: ID=88A7A1388AB96F611840886012A4475F ServletRequest destroyed. Remote IP=0:0:0:0:0:0:0:1%0 Database connection closed for Application. Notice the sequence of log s and it’s in the order of execution. The last log will appear when you will shut down the application or shutdown the container. © JOURNALDEV.COM PAGE 53 OF 55 You can download the source code of “Servlet Listener Example Project” from here.