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

FirstSevlet.java

Example02
Loading editor…

RequestDemoListener.java

web.xml:

Example03
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 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
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

Example05
Loading editor…

RequestDemoListener.java

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

attribute in the request scope.

Example06
Loading editor…

RequestDemoListener.java

Example07
Loading editor…

ServletRequestAttributeEvent(C)

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

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

Example09
Loading editor…

FirstSevlet.java

Example10
Loading editor…

RequestAttributeDemoListener.java

web.xml:

Example11
Loading editor…

RequestAttributeDemoListener.java

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-RequestAttributeDemoListener.class

Example12
Loading editor…

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

Example14
Loading editor…

ServletContextEvent(C)

Increments count value for every request.

Example15
Loading editor…

ServletContextEvent(C)

Example16
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)

Example17
Loading editor…

ServletContextEvent(C)

3.FirstServlet.java:

To display count value to end user

Example18
Loading editor…

ServletContextEvent(C)

4.web.xml:

For declaring listeners

Example19
Loading editor…

ServletContextEvent(C)

Example20
Loading editor…

ServletContextEvent(C)

To save count value

listenersc

|-abc.txt

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-RequestDemoListener.class

|-ContextDemoListener.class

Example21
Loading editor…

ServletContextAttributeListener(I)

Example22
Loading editor…

ServletContextAttributeEvent(C)

Example23
Loading editor…

HttpSessionListener(I)

Example24
Loading editor…

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

Demo Program to display the number of users currently online

Example26
Loading editor…

Demo Program to display the number of users currently online

Example27
Loading editor…

Demo Program to display the number of users currently online

Example28
Loading editor…

Demo Program to display the number of users currently online

Example29
Loading editor…

Demo Program to display the number of users currently online

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-SessionCounter.class

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

Example31
Loading editor…

HttpSessionBindingListener(I)

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

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

Example33
Loading editor…

Demo Program for HttpSessionBindingListener

Example34
Loading editor…

SessionAttributeListener.java

web.xml:

Example35
Loading editor…

SessionAttributeListener.java

Note:

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

Example36
Loading editor…

FirstServlet.java

listener4

|-WEB-INF

|-web.xml

|-classes

|-FirstServlet.class

|-Dog.class

|-SessionAttributeListener.class

Example37
Loading editor…

HttpSessionActivationListener

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

Example38
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

Example39
Loading editor…
📝 Key Takeaways
  • Every example is complete and compiles as-is
  • Examples are grouped by topic
  • Typing programs is the fastest way to learn servlets

Finished this lesson?

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