Nearby lessons

21 of 34

Servlet - Listeners

📌 What You Will Learn
  • Understand ServletRequestEvent(C)
  • Understand ServletRequestAttributeEvent(C)
  • Understand ServletContextListener
  • See complete working code examples

Listeners is an essential part of the Java Servlet technology. This lesson explains ServletRequestEvent(C), FirstSevlet.java and RequestDemoListener.java with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid.

ServletRequestEvent(C)

This class contains the following methods to return request and context objects.

ServletRequestEvent(C)

ServletRequestEvent is the child class of java.util.EventObject.

EventObject class contains one method getSource()

public Object getSource()

It returns the source which causes the event. In this case web application is the source of event

& hence we will get ServletContext object.

Example02
JCode Cell
1 
2public ServletRequest getServletRequest()
3public ServletContext getServletContext()
4

FirstSevlet.java

Example03
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class FirstSevlet extends HttpServlet
6{
7public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8{
9PrintWriter out = resp.getWriter();
10out.println("<h1>This is RequestListener Demo Servlet</h1><br>");
11out.println("<h1>The number of hits for this webapplication is:"+RequestDemoListener.count+"</h1>");
12}
13}
14

RequestDemoListener.java

web.xml:

Example04
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4public class RequestDemoListener implements ServletRequestListener
5{
6public static int count = 0;
7 
8public void requestInitialized(ServletRequestEvent e)
9{
10count++;
11System.out.println("Request Object created at :"+new java.util.Date());
12System.out.println("The hit count for this web-application is :"+count);
13}
14public void requestDestroyed(ServletRequestEvent e)
15{
16System.out.println("Request Object destroyed :"+new java.util.Date());
17}
18}
19

RequestDemoListener.java

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-RequestDemoListener.class

Note:

  • We can configure Listener in web.xml by using <listener> tag. <listener> tag is the direct child

tag of <web-app> and hence we can take anywhere within <web-app>

  • We can configure more than one listener of same type. The order of execution of these listeners

is depends on the order of <listener> tags in web.xml

  • Web container is responsible for the creation of Listener class object.For this web container

always calls public no-arg constructor. Hence every listener class should compulsory contains

public no-arg constructor.

  • Web container will create Listener object automatically at the time of either server startup or at

application deployment.

Example05
JCode Cell
1 
2<web-app>
3 
4<listener>
5<listener-class>RequestDemoListener</listener-class>
6</listener>
7<servlet>
8<servlet-name>FirstSevlet</servlet-name>
9<servlet-class>FirstSevlet</servlet-class>
10</servlet>
11 
12<servlet-mapping>
13<servlet-name>FirstSevlet</servlet-name>
14<url-pattern>/test</url-pattern>
15</servlet-mapping>
16 
17</web-app>listener1
18

RequestDemoListener.java

This listener listens the events related to request scoped attributes like attribute

addition,attribute removed and attribute replaced.

This interface defines the following 3 methods

Example06
JCode Cell
1 
2ServletRequestAttributeListener(I):
3

RequestDemoListener.java

This method will be executed automatically by the web container whenever we are adding an

attribute in the request scope.

Example07
JCode Cell
1 
2public void attributeAdded(ServletRequestAttributeEvent e)
3

RequestDemoListener.java

Example08
JCode Cell
1 
2public void attributeRemoved(SRAE e)
3public void attributeReplaced(SRAE e)
4

ServletRequestAttributeEvent(C)

This class defines the following 2 methods.

ServletRequestAttributeEvent(C)

Returns the name of the attribute which is added or removed or replaced in the request scope.

Example10
JCode Cell
1 
2public String getName()
3

ServletRequestAttributeEvent(C)

returns the value of the attribute which is added or replaced or removed.

In the case of attribute addition and removal this method returns the corresponding attribute

value.But in the case of replacement this method returns old value of the attribute.

Example11
JCode Cell
1 
2public Object getValue()
3

FirstSevlet.java

Example12
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class FirstSevlet extends HttpServlet
6{
7public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8{
9PrintWriter out = resp.getWriter();
10req.setAttribute("durga","scwcd");
11req.setAttribute("pavan","scjp");
12req.removeAttribute("pavan");
13req.setAttribute("durga","scbcd");
14out.println("<h1>This is ServletRequestAttributeListener Demo </h1>");
15 
16}
17 
18}
19
Output

<h1>This is ServletRequestAttributeListener Demo </h1>
      

RequestAttributeDemoListener.java

web.xml:

Example13
JCode Cell
1 
2import javax.servlet.*;
3public class RequestAttributeDemoListener implements ServletRequestAttributeListener
4{
5public void attributeAdded(ServletRequestAttributeEvent e)
6{
7System.out.println(e.getName()+"... Attribute Added");
8}
9public void attributeRemoved(ServletRequestAttributeEvent e)
10{
11System.out.println(e.getName()+"...Attribute Removed");
12}
13public void attributeReplaced(ServletRequestAttributeEvent e)
14{
15System.out.println(e.getName()+"...Attribute Replaced");
16}
17 
18}
19

RequestAttributeDemoListener.java

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-RequestAttributeDemoListener.class

Example14
JCode Cell
1 
2<web-app>
3 
4<listener>
5<listener-class>RequestAttributeDemoListener</listener-class>
6</listener>
7 
8<servlet>
9<servlet-name>FirstSevlet</servlet-name>
10<servlet-class>FirstSevlet</servlet-class>
11</servlet>
12 
13<servlet-mapping>
14<servlet-name>FirstSevlet</servlet-name>
15<url-pattern>/test</url-pattern>
16</servlet-mapping>
17</web-app>listener2
18

ServletContextListener

This listener listens the life cycle events of ServletContext like creation and destruction.

This interface defines the following 2 methods

ServletContextListener

This method will be executed automatically by the web container at the time of context object

creation. i.e at the time of application deployment or server startup.

Example16
JCode Cell
1 
2public void contextInitialized(ServletContextEvent e)
3

ServletContextListener

This method will be executed automatically by the web container at the time of context object

destruction. i.e at the time of application undeployment or server shutdown.

Example17
JCode Cell
1 
2public void contextDestroyed(ServletContextEvent e)
3

ServletContextEvent(C)

It is the child class of java.util.EventObject.

It contains only one method

public ServletContext getServletContext()

Demo program for ServletContextListener to display hitcount of the application where count value

will be preserved across Server restarts.

ServletContextEvent(C)

Increments count value for every request.

Example19
JCode Cell
1 
2RequestDemoListener.java:
3

ServletContextEvent(C)

Example20
JCode Cell
1 
2import javax.servlet.*;
3public class RequestDemoListener implements ServletRequestListener
4{
5public static int count = 0;
6public void requestInitialized(ServletRequestEvent e)
7{
8count++;
9}
10public void requestDestroyed(ServletRequestEvent e)
11{
12}
13}
14

ServletContextEvent(C)

saves the count value to abc.txt file at the time of context object destruction(server shutdown)

It reads the count value from abc.txt file and assign to RequestDemoListener.count variable at

context object creation(server startup)

Example21
JCode Cell
1 
2ContextDemoListener.java:
3

ServletContextEvent(C)

3.FirstServlet.java:

To display count value to end user

Example22
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class ContextDemoListener implements ServletContextListener
6{
7public void contextInitialized(ServletContextEvent e)
8{
9try{
10String path=e.getServletContext().getRealPath("abc.txt");
11BufferedReader br = new BufferedReader( new FileReader(path));
12String s = br.readLine();
13if(s != null)
14{
15int c = Integer.parseInt(s);
16RequestDemoListener.count = c;
17}
18}
19catch(Exception e1){ }
20}
21public void contextDestroyed(ServletContextEvent e)
22{
23try{
24String path=e.getServletContext().getRealPath("abc.txt");
25PrintWriter pw = new PrintWriter(path);
26pw.println(RequestDemoListener.count);
27pw.flush();
28}
29catch(Exception e1) {
30}
31}
32}
33

ServletContextEvent(C)

4.web.xml:

For declaring listeners

Example23
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class FirstSevlet extends HttpServlet
6{
7public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8{
9PrintWriter out = resp.getWriter();
10out.println("<h1>The number of hits for this webapplication is:"+RequestDemoListener.count+"</h1>");
11}
12}
13

ServletContextEvent(C)

Example24
JCode Cell
1 
2<web-app>
3 
4<listener>
5<listener-class>RequestDemoListener</listener-class>
6</listener>
7 
8<listener>
9<listener-class>ContextDemoListener</listener-class>
10</listener>
11 
12<servlet>
13<servlet-name>FirstSevlet</servlet-name>
14<servlet-class>FirstSevlet</servlet-class>
15</servlet>
16 
17<servlet-mapping>
18<servlet-name>FirstSevlet</servlet-name>
19<url-pattern>/test</url-pattern>
20</servlet-mapping>
21 
22</web-app>
23

ServletContextEvent(C)

To save count value

listenersc

|-abc.txt

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-RequestDemoListener.class

|-ContextDemoListener.class

Example25
JCode Cell
1 
2abc.txt:
3

ServletContextAttributeListener(I)

This listener listens the events related to context scoped attributes like addition,removal and

replacement.

This interface defines the following 3 methods.

ServletContextAttributeListener(I)

Example27
JCode Cell
1 
2public void attributeAdded(ServletContextAttributeEvent e)
3public void attributeRemoved(SCAE e)
4public void attributeReplaced(SCAE e)
5

ServletContextAttributeEvent(C)

It is the child class of ServletContextEvent.

It defines the following 2 methods

ServletContextAttributeEvent(C)

Example29
JCode Cell
1 
2public String getName()
3public Object getValue()
4

HttpSessionListener(I)

This listener listens the life cycle events of HttpSession object like creation and destruction.

This interface defines the following 2 methods

HttpSessionListener(I)

Example31
JCode Cell
1 
2public void sessionCreated(HttpSessionEvent e)
3public void sessionDestroyed(HttpSessionEvent e)
4

HttpSessionEvent(C)

This class defines only one method getSession()

public HttpSession getSession()

Eg: HS session = req.getSession();

Demo Program to display the number of users currently online

This listener increments count value for every session object creation and decrements count value

for every session object destruction.

Example33
JCode Cell
1 
2SessionCounter.java:
3

Demo Program to display the number of users currently online

Example34
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4public class SessionCounter implements HttpSessionListener
5{
6static int count = 0;
7public void sessionCreated(HttpSessionEvent e)
8{
9count++;
10System.out.println("A new session created with id: "+e.getSession().getId());
11}
12public void sessionDestroyed(HttpSessionEvent e)
13{
14count--;
15System.out.println("An existing session destroyed with id: "+e.getSession().getId());
16}
17}
18

Demo Program to display the number of users currently online

Example35
JCode Cell
1 
2FirstServlet.java
3

Demo Program to display the number of users currently online

Example36
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class FirstSevlet extends HttpServlet
6{
7public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8{
9PrintWriter out = resp.getWriter();
10HttpSession s = req.getSession();
11s.setMaxInactiveInterval(120);
12out.println("<h1>The number of users online is:"+SessionCounter.count+"</h1>");
13}
14}
15

Demo Program to display the number of users currently online

Example37
JCode Cell
1 
2web.xml
3

Demo Program to display the number of users currently online

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-SessionCounter.class

Example38
JCode Cell
1 
2<web-app>
3 
4<listener>
5<listener-class>SessionCounter</listener-class>
6</listener>
7 
8<servlet>
9<servlet-name>FirstSevlet</servlet-name>
10<servlet-class>FirstSevlet</servlet-class>
11</servlet>
12 
13<servlet-mapping>
14<servlet-name>FirstSevlet</servlet-name>
15<url-pattern>/test</url-pattern>
16</servlet-mapping>
17 
18</web-app>listener3
19

Demo Program to display the number of users currently online

This listener listens the events related to session scoped attributes like attribute addition,removal

and replacement.

This interface defines the following 3 methods.

public void attributeAdded(HttpSessionBindingEvent e)

public void attributeRemoved(HSBE e)

public void attributeReplaced(HSBE e)

Note:

There is no event class named with HttpSessionAttributeEvent. For this equivalent event class is

HttpSessionBindingEvent.

Example39
JCode Cell
1 
2HttpSessionAttributeListener(I):
3

HttpSessionBindingEvent

It is the child class of HttpSessionEvent.

This class contains the following 2 methods

public String getName()

public Object getValue()

HttpSessionBindingListener(I)

Whenever a particular type of object adding|removing|replacing in session scope, if we want to

perform certain activities then we should go for HttpSessionBindingListener.

This listener defines the following 2 methods

HttpSessionBindingListener(I)

This method will be executed automatically at the time of attribute addition.

Example42
JCode Cell
1 
2public void valueBound(HttpSessionBindingEvent e)
3

HttpSessionBindingListener(I)

This method will be executed automatically at the time of attribute removal.

Note: In the case of replacement both methods will be executed but valueBound() method first

followed by valueUnbound().

Note:

It is not required to configure HttpSessionBindingListener in web.xml. Whenever we are adding an

attribute,web container will check the corresponding class implements HttpSessionBindingListener

or not. If it implements then the corresponding method will be executed.

If both attribute and binding listeners are configured,then binding listener will be executed first

followed by attribute listener.

Example43
JCode Cell
1 
2public void valueUnbound(HttpSessionBindingEvent e)
3

Demo Program for HttpSessionBindingListener

Dog.java:

Demo Program for HttpSessionBindingListener

Example45
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4public class Dog implements HttpSessionBindingListener
5{
6public void valueBound(HttpSessionBindingEvent e)
7{
8System.out.println("dog object has added to the session scope");
9}
10public void valueUnbound(HttpSessionBindingEvent e)
11{
12System.out.println("Dog object has removed from the session scope");
13}
14}
15
Output

dog object has added to the session scope
Dog object has removed from the session scope
      

SessionAttributeListener.java

web.xml:

Example46
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4public class SessionAttributeListener implements HttpSessionAttributeListener
5{
6public void attributeAdded(HttpSessionBindingEvent e)
7{
8System.out.println("attribute added");
9}
10public void attributeRemoved(HttpSessionBindingEvent e)
11{
12System.out.println("attribute removed");
13}
14public void attributeReplaced(HttpSessionBindingEvent e)
15{
16System.out.println("attribute replaced");
17}
18}
19
Output

attribute added
attribute removed
attribute replaced
      

SessionAttributeListener.java

Note:

We have to configure only AttributeListener and we are not required to configure binding listener.

Example47
JCode Cell
1 
2<web-app>
3 
4<listener>
5<listener-class>SessionAttributeListener</listener-class>
6</listener>
7 
8<servlet>
9<servlet-name>FirstSevlet</servlet-name>
10<servlet-class>FirstSevlet</servlet-class>
11</servlet>
12 
13<servlet-mapping>
14<servlet-name>FirstSevlet</servlet-name>
15<url-pattern>/test</url-pattern>
16</servlet-mapping>
17 
18</web-app>
19

FirstServlet.java

listener4

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-Dog.class

|-SessionAttributeListener.class

Example48
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class FirstSevlet extends HttpServlet
6{
7public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8{
9PrintWriter out = resp.getWriter();
10HttpSession s = req.getSession();
11s.setAttribute("a1","SCJP");
12s.setAttribute("a1","SCWCD");
13s.setAttribute("a2",new Dog());
14s.setAttribute("a3",new Dog());
15s.setAttribute("a2",new Dog());
16s.removeAttribute("a3");
17out.println("<h1>This is Session Binding demo</h1>");
18}
19 
20}
21
Output

<h1>This is Session Binding demo</h1>
      

HttpSessionActivationListener

If functionality is distributed across several JVMs, then that application is called distributed web

application.

The main advantages of distributed web applications are

  • By Load balancing we can improve performance of the application
  • By Handling Fail over situations,we can keep our web application robust.(The chance of failure

is very very less).

In the distributed applications session object has to migrate from one JVM to another JVM.

Whenever a session object is migrated from one JVM to another JVM,compulsory the

corresponding session attributes should be migrated across the network. Hence every session

attribute should be compulsory implements Serializable interface.

At the time of session object migration if we want to perform certain activities then we should go

for HttpSessionActivationListener.

This interface defines the following 2 methods.

HttpSessionActivationListener

This method is called on each implementing object bound to the session just before serialization.

Example50
JCode Cell
1 
2public void sessionWillPassivate(HttpSessionEvent e)
3

HttpSessionActivationListener

This method is called on each implementing object bound to the session just after

deserialization.

Summary of all Listeners:

Listener Purpose Corresponding Corresponding Corresponding Is

MethodsEventsEvent Methodsrequired

Servlet

Request To listens life requestInitialized() ServletRequest getServletReque to

Listenercycle events ofrequestDestroyed()Eventst()configure
request object.getServletConteweb.xml
Servleti.e., requestServletRequest xt()Yes
Requestobject creationAttributeEvent
Attribute& destructiongetName()Yes
ListenerServletContext getValue()
To listensattributeAdded()EventYes
Servletevents relatedattributeReplaced()getServletConte
Contextrequest scopedattributeRemoved()ServletContext xt()Yes
ListenerattributesAttributeEvent

getName() Yes

ServletTo listens lifecontextInitialized() HttpSessiongetValue()
Contextcycle events ofcontextDestroyed()Event
Attributecontext object.getSession()

Listener i.e., context

object creation

HttpSession & destruction

Listener

To listen events attributeAdded()

related toattributeReplaced()
context scopedattributeRemoved()

attributes

To listens lifesessionCreated()
cycle events ofsessionDestroyed()

session object.

i.e., session

object creation

& destruction

HttpSession To listen events attributeAdded()HttpSessiongetName()Yes
Attributerelated toattributeReplaced()AttributeEvent getValue()
Listenersession scopedattributeRemoved()HttpSessionnot
attributesBindingEventgetName()required
HttpSessiongetValue()
BindingWhen ever weHttpSessionnot
Listenerare adding orBindingEventgetSession() required

removing or

HttpSession replacing avalueBound()
Activationparticular typevalueUnbound()

Listener of object in

session scope ,

to perform

certain activity

then we should

go for this

Listener

If we want tosessionWillPassivate HttpSession

perform any () Event

activity justsessionDidActivate()

before

serialization

and just after

de-serialization

in distributed

web-

applications

@WebListener Annotation in Servlet 3.0V:

This annotation is replacement for listener configuration in web.xml

Eg:

import javax.servlet.annotation.*;

@WebListener

public class RequestDemoListener implements ServletRequestListener

{

...

}

whenever we are using @WebListener annotation then we are not required to configure listener

in web.xml

Example51
JCode Cell
1 
2public void sessionDidActivate(HttpSessionEvent e)
3
📝 Key Takeaways
  • Key ideas of Servlet - Listeners explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end

🧠 Test Your Knowledge

3 Questions
Progress: 0 / 3