Nearby lessons

33 of 34

Servlet - Examples: Listeners

📌 What You Will Learn
  • See complete runnable servlet programs
  • Understand the output of each program
  • Copy and deploy programs in Tomcat

Listener programs for Request, Context, Session, Binding, and Activation listeners.

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.

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

FirstSevlet.java

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

RequestDemoListener.java

web.xml:

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

public no-arg constructor.

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

application deployment.

Example04
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

Example05
JCode Cell
1 
2 ServletRequestAttributeListener(I):
3

RequestDemoListener.java

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

attribute in the request scope.

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

RequestDemoListener.java

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

ServletRequestAttributeEvent(C)

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

Example08
JCode Cell
1 
2 public 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.

Example09
JCode Cell
1 
2 public Object getValue()
3

FirstSevlet.java

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

    <h1>This is ServletRequestAttributeListener Demo </h1>
          

RequestAttributeDemoListener.java

web.xml:

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

RequestAttributeDemoListener.java

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-RequestAttributeDemoListener.class

Example12
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 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.

Example13
JCode Cell
1 
2 public 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.

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

ServletContextEvent(C)

Increments count value for every request.

Example15
JCode Cell
1 
2 RequestDemoListener.java:
3

ServletContextEvent(C)

Example16
JCode Cell
1 
2 import javax.servlet.*;
3 public class RequestDemoListener implements ServletRequestListener
4 {
5 public static int count = 0;
6 public void requestInitialized(ServletRequestEvent e)
7 {
8 count++;
9 }
10 public 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)

Example17
JCode Cell
1 
2 ContextDemoListener.java:
3

ServletContextEvent(C)

3.FirstServlet.java:

To display count value to end user

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

ServletContextEvent(C)

4.web.xml:

For declaring listeners

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

ServletContextEvent(C)

Example20
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

Example21
JCode Cell
1 
2 abc.txt:
3

ServletContextAttributeListener(I)

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

ServletContextAttributeEvent(C)

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

HttpSessionListener(I)

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

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.

Example25
JCode Cell
1 
2 SessionCounter.java:
3

Demo Program to display the number of users currently online

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

Demo Program to display the number of users currently online

Example27
JCode Cell
1 
2 FirstServlet.java
3

Demo Program to display the number of users currently online

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

Demo Program to display the number of users currently online

Example29
JCode Cell
1 
2 web.xml
3

Demo Program to display the number of users currently online

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-SessionCounter.class

Example30
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.

Example31
JCode Cell
1 
2 HttpSessionAttributeListener(I):
3

HttpSessionBindingListener(I)

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

Example32
JCode Cell
1 
2 public 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.

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

Demo Program for HttpSessionBindingListener

Example34
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 public class Dog implements HttpSessionBindingListener
5 {
6 public void valueBound(HttpSessionBindingEvent e)
7 {
8 System.out.println("dog object has added to the session scope");
9 }
10 public void valueUnbound(HttpSessionBindingEvent e)
11 {
12 System.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:

Example35
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 public class SessionAttributeListener implements HttpSessionAttributeListener
5 {
6 public void attributeAdded(HttpSessionBindingEvent e)
7 {
8 System.out.println("attribute added");
9 }
10 public void attributeRemoved(HttpSessionBindingEvent e)
11 {
12 System.out.println("attribute removed");
13 }
14 public void attributeReplaced(HttpSessionBindingEvent e)
15 {
16 System.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.

Example36
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

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

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

HttpSessionActivationListener

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

Example38
JCode Cell
1 
2 public 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

Example39
JCode Cell
1 
2 public void sessionDidActivate(HttpSessionEvent e)
3
📝 Key Takeaways
  • Every example is complete and compiles as-is
  • Examples are grouped by topic
  • Typing programs is the fastest way to learn servlets