SlideShare a Scribd company logo
1 of 26
LISTENERS AND FILTERS
Using ServletContextListener,
HttpSessionListener,
Understanding of all the other Listeners viz.
ServletRequestListener,
ServletContextAttributeListener,
ServletRequestAttributeListener,
HttpSessionAttributeListener
LISTENERS AND FILTERS
 Listeners are the classes which listens to a particular type
of events and when that event occurs , triggers the
functionality.
 Each type of listener is bind to a type of event.
 There are two most widely used Servlet Listener i.e.
ServletContextListener and HttpSessionListener.
 With listeners you can track application-level, session-level,
life-cycle changes, attribute changes etc.
 The implemented interfaces are javax.servlet.Listener
interface.
 Servlet Filter is used for monitoring request and response
from client to the servlet, or to modify the request and
response, or to audit and log.
LISTENERS
 There are total eight type of listeners available in servlet
framework which listens to a particular event and they are
 ServletContextListener
 ServletContextAttributeListener
 HttpSessionListener
 HttpSessionAttributeListener
 ServletRequestListener
 ServletRequestAttributeListener
 HttpSessionActivationListener
 HttpSessionBindingListener
 As the configurations of servlets , filters goes inside web.xml ,
similarly listeners are also configured inside web.xml using
<listener> </listener> tag.
SERVLETCONTEXTLISTENER
 ServletContextListener will be executed once
your web application is deployed in your
application server (Tomcat or etc).
 If you have any requirements that need to be
executed before the application is started,
ServletContextListener is the best place for you.
 ServletContextListener listens to
SessionContextEvent event which gives a
notification when Servlet Context is initialized or
destroyed and used on the events
ServletContextListener executes the functionality.
 ServletContextListener is the interface and it defines two
methods –
 void contextDestroyed(ServletContextEvent e) – This
method is executed when application is destroyed
 void contextInitialized(ServletContextEvent e)- This
method is executed when application is initialized
 ServletContext object can be obtained
from ServletContextEvent and listener can set the
attributes in Servlet context object which can be used in
servlets later.
 We can use the “ServletContextListener “ listener for any
activity that is required either at the application deployment
time or any clean up activity required when application is
destroyed.
 One of the practical example that is initializing database
connections and clean up of database connections.
HTTPSESSIONLISTENER
 HttpSessionListener listens to HttpSessionEvent event
which gives a notification when session is created or
destroyed.
 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.
SERVLETCONTEXTATTRIBUTELISTENER
 ServletContextAttributeListener listens to
ServletContexAttributetEvent event which gives a notification
when any object is added, removed or replaced from servlet
context .
 ServletContextAttributeListener is the interface and it defines
three methods –
 attributeAdded(ServletContextAttributeEvent e): It notifies
whenever a new attribute is added to the servlet context.
 attributeRemoved(ServletContextAttributeEvent e): It
notifies whenever the attribute is removed from the servlet
context.
 attributeReplaced(ServletContextAttributeEvent e): It
notifies whenever the attribute gets replaced on the servlet
context.
 Attribute name and value that has been added, removed or
replaced can be obtained from the getName() and
getValue() method of ServletContextAttributeEvent
HTTPSESSIONATTRIBUTELISTENER
 HttpSessionAttributeListener listens to
HttpSessionBindingEvent event which gives a notification when
any object is added, removed or replaced from session .
 HttpSessionAttributeListener is the interface and it defines three
methods –
 attributeAdded(HttpSessionBindingEvent e): It notifies
whenever a new attribute is added to the session.
 attributeRemoved(HttpSessionBindingEvent e): It notifies
whenever the attribute is removed from the session.
 attributeReplaced(HttpSessionBindingEvent e): It notifies
whenever the attribute gets replaced on the session.
 Attribute name and value that has been added, removed or
replaced can be obtained from the getName() and getValue()
method of HttpSessionBindingEvent
SERVLETREQUESTLISTENER
 ServletRequestListener listens to ServletRequestEvent
event which gives a notification when request is created or
destroyed.
 ServletRequestListener is the interface and it defines two
methods –
 void requestDestroyed(ServletRequestEvent e) – This
method is executed when request is destroyed
 void requestInitialized(ServletRequestEvent e)- This
method is executed when request is initialized.
 Request object can be Obtained from HttpRequestEvent.
SERVLETREQUESTATTRIBUTELISTENER
 ServletRequestAttributeListener listens to
ServletRequestAttributeEvent event which gives a notification when
any object is added, removed or replaced from request .
 ServletRequestAttributeListener is the interface and it defines three
methods –
 attributeAdded(ServletRequestAttributeEvent e): It notifies whenever
a new attribute is added to the request.
 attributeRemoved(ServletRequestAttributeEvent e): It notifies
whenever the attribute is removed from the request.
 attributeReplaced(ServletRequestAttributeEvent e): It notifies
whenever the attribute gets replaced on the request.
 Attribute name and value that has been added, removed or
replaced can be obtained from the getName() and getValue() method of
ServletRequestAttributeEvent
INTRODUCTION TO FILTER API
 Filters are compontents that you can use and
configure to perform some filtering tasks.
 Filter is used for pre-processing of requests and
post-processing of responses.
 You can have any number of filters for pre-
processing of a request and post-processing of a
response.
 Filters are configured in the deployment descriptor
of a web application.
HOW FILTERS WORKS?
 When a request reaches the Web Container, it checks if any
filter has URL patterns that matches the requested URL.
 The Web Container locates the first filter with a matching URL
pattern and filter's code is executed.
 If another filter has a matching URL pattern, its code is then
executed. This continues until there are no filters with
matching URL patterns left.
 If no error occurs, the request passes to the target servlet.
Hence we know, that the request will be passed to the target
servlet only when all the related Filters are successfully
executed.
 The servlet returns the response back to its caller. The last filter that was
applied to the request is the first filter applied to the response.
 At last the response will be passed to the Web Container which passes it
to the client.
 Filter API is part of Servlet API.
 Filter interface is found in the javax.servlet package.
 For creating a filter, we must implement Filter interface.
 Filter interface gives the following life cycle methods for a
filter:
 void init(FilterConfig filterConfig): invoked by the web
container to indicate to a filter that it is being placed into
service.
 void doFilter(ServletRequest request, ServletResponse
response, FilterChain chain): invoked by the container
each time a request/response pair is passed through the
chain due to a client request for a resource at the end of
the chain.
 void destroy(): invoked by the web container to indicate to
a filter that it is being taken out of service.
WHAT IS FILTERCHAIN INTERFACE?
 FilterChain object is used to invoke the next filter in the
chain, or if the calling filter is the last filter in the chain
then the rosource at the end of the chain invoked.
 The resources at the end of Filter chain can either be a
target Servlet(in case of request flow) or the Client(in case
of response flow) as described in the diagram.
DECLARING A FILTER INSIDE DEPLOYMENT
DESCRIPTOR
EXAMPLE DEMONSTRATING FILTER USAGE
 In this example we are using Filter to authenticate(check
correct username and password).
 Here index.html will ask username and password from
the user, MyFilter will validate the password entered by
the user, if the user has entered "1234" as password, then
he will be forwarded to first servlet else the index.html will
be shown again to the user.
 http://www.wideskills.com/servlets/servlet-listeners
 https://www.java-tips.org/introduction-to-servlet-
listener-using-eclipse.html
 http://www.studytonight.com/servlet/filter-api.php

More Related Content

What's hot

Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationSeven Peaks Speaks
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 
Design Pattern - Observer Pattern
Design Pattern - Observer PatternDesign Pattern - Observer Pattern
Design Pattern - Observer PatternMudasir Qazi
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
L11 array list
L11 array listL11 array list
L11 array listteach4uin
 
Java collections concept
Java collections conceptJava collections concept
Java collections conceptkumar gaurav
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJSAbul Hasan
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserializationYoung Alista
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Aijaz Ali Abro
 
Clean architecture with ddd layering in php
Clean architecture with ddd layering in phpClean architecture with ddd layering in php
Clean architecture with ddd layering in phpLeonardo Proietti
 

What's hot (20)

Iterator
IteratorIterator
Iterator
 
Utilizing kotlin flows in an android application
Utilizing kotlin flows in an android applicationUtilizing kotlin flows in an android application
Utilizing kotlin flows in an android application
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Java servlets
Java servletsJava servlets
Java servlets
 
Design Pattern - Observer Pattern
Design Pattern - Observer PatternDesign Pattern - Observer Pattern
Design Pattern - Observer Pattern
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Servlets
ServletsServlets
Servlets
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
javathreads
javathreadsjavathreads
javathreads
 
L11 array list
L11 array listL11 array list
L11 array list
 
Servlet Filter
Servlet FilterServlet Filter
Servlet Filter
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Introduction to RxJS
Introduction to RxJSIntroduction to RxJS
Introduction to RxJS
 
Serialization/deserialization
Serialization/deserializationSerialization/deserialization
Serialization/deserialization
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
Composite pattern
Composite patternComposite pattern
Composite pattern
 
Clean architecture with ddd layering in php
Clean architecture with ddd layering in phpClean architecture with ddd layering in php
Clean architecture with ddd layering in php
 
Servlets
ServletsServlets
Servlets
 

Similar to Servlet Listeners and Filters Guide

Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalizationsusant sahu
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and FiltersPeople Strategists
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4Ben Abdallah Helmi
 
Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 
Architectural Patterns - Interactive and Event Handling Patterns
Architectural Patterns  - Interactive and Event Handling PatternsArchitectural Patterns  - Interactive and Event Handling Patterns
Architectural Patterns - Interactive and Event Handling Patternsassinha
 
Advance java session 18
Advance java session 18Advance java session 18
Advance java session 18Smita B Kumar
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T Spatinijava
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesbharathiv53
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...WebStackAcademy
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9aminmesbahi
 

Similar to Servlet Listeners and Filters Guide (20)

Servlets - filter, listeners, wrapper, internationalization
Servlets -  filter, listeners, wrapper, internationalizationServlets -  filter, listeners, wrapper, internationalization
Servlets - filter, listeners, wrapper, internationalization
 
Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
 
Servlet Filters
Servlet FiltersServlet Filters
Servlet Filters
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Architectural Patterns - Interactive and Event Handling Patterns
Architectural Patterns  - Interactive and Event Handling PatternsArchitectural Patterns  - Interactive and Event Handling Patterns
Architectural Patterns - Interactive and Event Handling Patterns
 
Advance java session 18
Advance java session 18Advance java session 18
Advance java session 18
 
Java servlets
Java servletsJava servlets
Java servlets
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
 
Java servlets
Java servletsJava servlets
Java servlets
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 

More from Shree M.L.Kakadiya MCA mahila college, Amreli

More from Shree M.L.Kakadiya MCA mahila college, Amreli (20)

Machine Learning by Rj
Machine Learning by RjMachine Learning by Rj
Machine Learning by Rj
 
Servlet unit 2
Servlet unit 2 Servlet unit 2
Servlet unit 2
 
Research paper on python by Rj
Research paper on python by RjResearch paper on python by Rj
Research paper on python by Rj
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
 
Jsp in Servlet by Rj
Jsp in Servlet by RjJsp in Servlet by Rj
Jsp in Servlet by Rj
 
Motion capture by Rj
Motion capture by RjMotion capture by Rj
Motion capture by Rj
 
Research paper on big data and hadoop
Research paper on big data and hadoopResearch paper on big data and hadoop
Research paper on big data and hadoop
 
Text processing by Rj
Text processing by RjText processing by Rj
Text processing by Rj
 
Python and data analytics
Python and data analyticsPython and data analytics
Python and data analytics
 
Multithreading by rj
Multithreading by rjMultithreading by rj
Multithreading by rj
 
Django by rj
Django by rjDjango by rj
Django by rj
 
Database programming
Database programmingDatabase programming
Database programming
 
CGI by rj
CGI by rjCGI by rj
CGI by rj
 
Adv. python regular expression by Rj
Adv. python regular expression by RjAdv. python regular expression by Rj
Adv. python regular expression by Rj
 
Seminar on Project Management by Rj
Seminar on Project Management by RjSeminar on Project Management by Rj
Seminar on Project Management by Rj
 
Spring by rj
Spring by rjSpring by rj
Spring by rj
 
Python by Rj
Python by RjPython by Rj
Python by Rj
 
Leadership & Motivation
Leadership & MotivationLeadership & Motivation
Leadership & Motivation
 
Event handling
Event handlingEvent handling
Event handling
 
Layout manager
Layout managerLayout manager
Layout manager
 

Recently uploaded

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Recently uploaded (20)

08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Servlet Listeners and Filters Guide

  • 1. LISTENERS AND FILTERS Using ServletContextListener, HttpSessionListener, Understanding of all the other Listeners viz. ServletRequestListener, ServletContextAttributeListener, ServletRequestAttributeListener, HttpSessionAttributeListener
  • 2. LISTENERS AND FILTERS  Listeners are the classes which listens to a particular type of events and when that event occurs , triggers the functionality.  Each type of listener is bind to a type of event.  There are two most widely used Servlet Listener i.e. ServletContextListener and HttpSessionListener.  With listeners you can track application-level, session-level, life-cycle changes, attribute changes etc.  The implemented interfaces are javax.servlet.Listener interface.  Servlet Filter is used for monitoring request and response from client to the servlet, or to modify the request and response, or to audit and log.
  • 3.
  • 4.
  • 5. LISTENERS  There are total eight type of listeners available in servlet framework which listens to a particular event and they are  ServletContextListener  ServletContextAttributeListener  HttpSessionListener  HttpSessionAttributeListener  ServletRequestListener  ServletRequestAttributeListener  HttpSessionActivationListener  HttpSessionBindingListener  As the configurations of servlets , filters goes inside web.xml , similarly listeners are also configured inside web.xml using <listener> </listener> tag.
  • 6. SERVLETCONTEXTLISTENER  ServletContextListener will be executed once your web application is deployed in your application server (Tomcat or etc).  If you have any requirements that need to be executed before the application is started, ServletContextListener is the best place for you.  ServletContextListener listens to SessionContextEvent event which gives a notification when Servlet Context is initialized or destroyed and used on the events ServletContextListener executes the functionality.
  • 7.  ServletContextListener is the interface and it defines two methods –  void contextDestroyed(ServletContextEvent e) – This method is executed when application is destroyed  void contextInitialized(ServletContextEvent e)- This method is executed when application is initialized
  • 8.  ServletContext object can be obtained from ServletContextEvent and listener can set the attributes in Servlet context object which can be used in servlets later.  We can use the “ServletContextListener “ listener for any activity that is required either at the application deployment time or any clean up activity required when application is destroyed.  One of the practical example that is initializing database connections and clean up of database connections.
  • 9.
  • 10.
  • 11. HTTPSESSIONLISTENER  HttpSessionListener listens to HttpSessionEvent event which gives a notification when session is created or destroyed.  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.
  • 12. 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.
  • 13. SERVLETCONTEXTATTRIBUTELISTENER  ServletContextAttributeListener listens to ServletContexAttributetEvent event which gives a notification when any object is added, removed or replaced from servlet context .  ServletContextAttributeListener is the interface and it defines three methods –  attributeAdded(ServletContextAttributeEvent e): It notifies whenever a new attribute is added to the servlet context.  attributeRemoved(ServletContextAttributeEvent e): It notifies whenever the attribute is removed from the servlet context.  attributeReplaced(ServletContextAttributeEvent e): It notifies whenever the attribute gets replaced on the servlet context.
  • 14.  Attribute name and value that has been added, removed or replaced can be obtained from the getName() and getValue() method of ServletContextAttributeEvent
  • 15. HTTPSESSIONATTRIBUTELISTENER  HttpSessionAttributeListener listens to HttpSessionBindingEvent event which gives a notification when any object is added, removed or replaced from session .  HttpSessionAttributeListener is the interface and it defines three methods –  attributeAdded(HttpSessionBindingEvent e): It notifies whenever a new attribute is added to the session.  attributeRemoved(HttpSessionBindingEvent e): It notifies whenever the attribute is removed from the session.  attributeReplaced(HttpSessionBindingEvent e): It notifies whenever the attribute gets replaced on the session.  Attribute name and value that has been added, removed or replaced can be obtained from the getName() and getValue() method of HttpSessionBindingEvent
  • 16. SERVLETREQUESTLISTENER  ServletRequestListener listens to ServletRequestEvent event which gives a notification when request is created or destroyed.  ServletRequestListener is the interface and it defines two methods –  void requestDestroyed(ServletRequestEvent e) – This method is executed when request is destroyed  void requestInitialized(ServletRequestEvent e)- This method is executed when request is initialized.  Request object can be Obtained from HttpRequestEvent.
  • 17. SERVLETREQUESTATTRIBUTELISTENER  ServletRequestAttributeListener listens to ServletRequestAttributeEvent event which gives a notification when any object is added, removed or replaced from request .  ServletRequestAttributeListener is the interface and it defines three methods –  attributeAdded(ServletRequestAttributeEvent e): It notifies whenever a new attribute is added to the request.  attributeRemoved(ServletRequestAttributeEvent e): It notifies whenever the attribute is removed from the request.  attributeReplaced(ServletRequestAttributeEvent e): It notifies whenever the attribute gets replaced on the request.  Attribute name and value that has been added, removed or replaced can be obtained from the getName() and getValue() method of ServletRequestAttributeEvent
  • 18. INTRODUCTION TO FILTER API  Filters are compontents that you can use and configure to perform some filtering tasks.  Filter is used for pre-processing of requests and post-processing of responses.  You can have any number of filters for pre- processing of a request and post-processing of a response.  Filters are configured in the deployment descriptor of a web application.
  • 19.
  • 20. HOW FILTERS WORKS?  When a request reaches the Web Container, it checks if any filter has URL patterns that matches the requested URL.  The Web Container locates the first filter with a matching URL pattern and filter's code is executed.  If another filter has a matching URL pattern, its code is then executed. This continues until there are no filters with matching URL patterns left.  If no error occurs, the request passes to the target servlet. Hence we know, that the request will be passed to the target servlet only when all the related Filters are successfully executed.  The servlet returns the response back to its caller. The last filter that was applied to the request is the first filter applied to the response.  At last the response will be passed to the Web Container which passes it to the client.
  • 21.  Filter API is part of Servlet API.  Filter interface is found in the javax.servlet package.  For creating a filter, we must implement Filter interface.  Filter interface gives the following life cycle methods for a filter:  void init(FilterConfig filterConfig): invoked by the web container to indicate to a filter that it is being placed into service.  void doFilter(ServletRequest request, ServletResponse response, FilterChain chain): invoked by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.  void destroy(): invoked by the web container to indicate to a filter that it is being taken out of service.
  • 22. WHAT IS FILTERCHAIN INTERFACE?  FilterChain object is used to invoke the next filter in the chain, or if the calling filter is the last filter in the chain then the rosource at the end of the chain invoked.  The resources at the end of Filter chain can either be a target Servlet(in case of request flow) or the Client(in case of response flow) as described in the diagram.
  • 23. DECLARING A FILTER INSIDE DEPLOYMENT DESCRIPTOR
  • 24. EXAMPLE DEMONSTRATING FILTER USAGE  In this example we are using Filter to authenticate(check correct username and password).  Here index.html will ask username and password from the user, MyFilter will validate the password entered by the user, if the user has entered "1234" as password, then he will be forwarded to first servlet else the index.html will be shown again to the user.
  • 25.