by R4R Team

Event and Listener in Servlet:

 In this topic we discuss Servlet event listeners. In many situations it is desirable to be notified of container-managed life cycle events. An easy example to think of is knowing when the container initializes a Web Application and when a Web Application is removed from use. Knowing this information is helpful because you may have code that relies on it, perhaps a database that needs to be loaded at startup and saved at shutdown. Another good example is keeping track of the number of concurrent clients using a Web Application. This functionality can be done with what you currently know of Servlets; however, it can much more easily be done using a listener that waits for a client to start a new session. The greater point being presented here is that a container can be used to notify a Web Application of important events, and Servlet event listeners are the mechanism.

All of the Servlet event listeners are defined by interfaces. There are event listener interfaces for all of the important events related to a Web Application and Servlets. In order to be notified of events, a custom class, which implements the correct listener interface, needs to be coded and the listener class needs to be deployed via web.xml. All of the Servlet event listeners will be mentioned now; however, a few of the event listeners will not make complete sense until the later chapters of the book. In general, all of the event listeners work the same way so this fact is fine as long as at least one good example is provided here.

The interfaces for event listeners correspond to request life cycle events, request attribute binding, Web Application life cycle events, Web Application attribute binding, session36 life cycle events, session attribute binding, and session serialization, and appear, respectively, as follows:

Event interfaces:

The event interfaces are as follows:

ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener



ServletContextEvent and ServletContextListener:


The ServletContextEvent is notified when web application is deployed on the server.

If you want to perform some action at the time of deploying the web application such as creating database connection, creating all the tables of the project etc, you need to implement ServletContextListener interface and provide the implementation of its methods.

Constructor of ServletContextEvent class:

There is only one constructor defined in the ServletContextEvent class. The web container creates the instance of ServletContextEvent after the ServletContext instance.

ServletContextEvent(ServletContext e)

Method of ServletContextEvent class

There is only one method defined in the ServletContextEvent class:

public ServletContext getServletContext():
returns the instance of ServletContext.
Methods of ServletContextListener interface

There are two methods declared in the ServletContextListener interface which must be implemented by the servlet programmer to perform some action such as creating database connection etc.

public void contextInitialized(ServletContextEvent e):
is invoked when application is deployed on the server.
public void contextDestroyed(ServletContextEvent e): is invoked when application is undeployed from the server.

Example of ServletContextEvent and ServletContextListener:


In this example, we are retrieving the data from the emp37table. To serve this, we have created the connection object in the listener class and used the connection object in the servlet.

index.html
<a href="servlet1">fetch records</a>

MyListener.java

import javax.servlet.*;

import java.sql.*;

public class MyListener implements ServletContextListener{

public void contextInitialized(ServletContextEvent event) {

try{

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection con=DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//storing connection object as an attribute in ServletContext

ServletContext ctx=event.getServletContext();

ctx.setAttribute("mycon", con);

}catch(Exception e){e.printStackTrace();}

}

public void contextDestroyed(ServletContextEvent arg0) {}

}

 

MyListener.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

public class FetchData extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

try{

//Retrieving connection object from ServletContext object

ServletContext ctx=getServletContext();

Connection con=(Connection)ctx.getAttribute("mycon");

//retieving data from emp32 table

PreparedStatement ps=con.prepareStatement("select * from emp37",

ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

ResultSet rs=ps.executeQuery();

while(rs.next()){

out.print("<br>"+rs.getString(1)+" "+rs.getString(2));

}

con.close();

}catch(Exception e){e.printStackTrace();}

out.close();

}

}


HttpSessionEvent and HttpSessionListener:

The HttpSessionEvent is notified when session object is changed. The corresponding Listener interface for this event is HttpSessionListener.

We can perform some operations at this event such as counting total and current logged-in users, maintaing a log of user details such as login time, logout time etc.

Methods of HttpSessionListener interface:

There are two methods declared in the HttpSessionListener interface which must be implemented by the servlet programmer to perform some action.
public void sessionCreated(HttpSessionEvent e): is invoked when session object is created.
public void sessionDestroyed(ServletContextEvent e): is invoked when session is invalidated.

Example of HttpSessionEvent and HttpSessionListener to count total and current logged-in users

In this example, are counting the total and current logged-in users. For this purpose, we have created three files:
index.html: to get input from the user.
MyListener.java: A listener class that counts total and current logged-in users and stores this information in ServletContext object as an attribute.
First.java: A Servlet class that creates session and prints the total and current logged-in users.
Logout.java: A Servlet class that invalidates session.

index.html

<form action="servlet1">

Name:<input type="text" name="username"><br>

Password:<input type="password" name="userpass"><br>

<input type="submit" value="login"/>

</form>


MyListener.java

import javax.servlet.ServletContext;

import javax.servlet.http.HttpSessionEvent;

import javax.servlet.http.HttpSessionListener;

public class CountUserListener implements HttpSessionListener{

ServletContext ctx=null;

static int total=0,current=0;

public void sessionCreated(HttpSessionEvent e) {

total++;

current++;

ctx=e.getSession().getServletContext();

ctx.setAttribute("totalusers", total);

ctx.setAttribute("currentusers", current);

}

public void sessionDestroyed(HttpSessionEvent e) {

current--;

ctx.setAttribute("currentusers",current);

} }

First.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public class First extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String n=request.getParameter("username");

out.print("Welcome "+n);

HttpSession session=request.getSession();

session.setAttribute("uname",n);

//retrieving data from ServletContext object

ServletContext ctx=getServletContext();

int t=(Integer)ctx.getAttribute("totalusers");

int c=(Integer)ctx.getAttribute("currentusers");

out.print("<br>total users= "+t);

out.print("<br>current users= "+c);

out.print("<br><a href='logout'>logout</a>");

out.close();

}

}

Logout.java

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

 

public class LogoutServlet extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

HttpSession session=request.getSession(false);

session.invalidate();//invalidating session

out.print("You are successfully logged out");

out.close();

} }

Leave a Comment: