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
Loading editor…

FirstSevlet.java

Example03
Loading editor…

RequestDemoListener.java

web.xml:

Example04
Loading editor…

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
Loading editor…

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
Loading editor…

RequestDemoListener.java

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

attribute in the request scope.

Example07
Loading editor…

RequestDemoListener.java

Example08
Loading editor…

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
Loading editor…

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
Loading editor…

FirstSevlet.java

Example12
Loading editor…

RequestAttributeDemoListener.java

web.xml:

Example13
Loading editor…

RequestAttributeDemoListener.java

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-RequestAttributeDemoListener.class

Example14
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

ServletContextEvent(C)

Example20
Loading editor…

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
Loading editor…

ServletContextEvent(C)

3.FirstServlet.java:

To display count value to end user

Example22
Loading editor…

ServletContextEvent(C)

4.web.xml:

For declaring listeners

Example23
Loading editor…

ServletContextEvent(C)

Example24
Loading editor…

ServletContextEvent(C)

To save count value

listenersc

|-abc.txt

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-RequestDemoListener.class

|-ContextDemoListener.class

Example25
Loading editor…

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
Loading editor…

ServletContextAttributeEvent(C)

It is the child class of ServletContextEvent.

It defines the following 2 methods

ServletContextAttributeEvent(C)

Example29
Loading editor…

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
Loading editor…

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
Loading editor…

Demo Program to display the number of users currently online

Example34
Loading editor…

Demo Program to display the number of users currently online

Example35
Loading editor…

Demo Program to display the number of users currently online

Example36
Loading editor…

Demo Program to display the number of users currently online

Example37
Loading editor…

Demo Program to display the number of users currently online

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-SessionCounter.class

Example38
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

Demo Program for HttpSessionBindingListener

Dog.java:

Demo Program for HttpSessionBindingListener

Example45
Loading editor…

SessionAttributeListener.java

web.xml:

Example46
Loading editor…

SessionAttributeListener.java

Note:

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

Example47
Loading editor…

FirstServlet.java

listener4

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-Dog.class

|-SessionAttributeListener.class

Example48
Loading editor…

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
Loading editor…

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
Loading editor…
📝 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

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.