SlideShare a Scribd company logo
1 of 36
Download to read offline
Slide 1 of 36© People Strategists www.peoplestrategists.com
Identifying Listeners
& Filters
Slide 2 of 36© People Strategists www.peoplestrategists.com
Objectives
In this session, you will learn to:
Identify listeners
Identify usage of listeners in Web application
Identify filters
Explore lifecycle of filters
Implement filters in a Web applications
Slide 3 of 36© People Strategists www.peoplestrategists.com
Identifying Listeners
How events are handled
and who performs the
action on the occurrence
of an event?
Slide 4 of 36© People Strategists www.peoplestrategists.com
A listener is an implemented interface, which responds to a particular
event.
For example, pressing a mouse button or selecting an item from a list
box, each one is an event, and the listeners are all the programs that
execute on the occurrence of these events.
The servlet specification includes the capability to track and handle
events in your Web applications through event listeners.
Identifying Listeners (Contd.)
Button Press Event
Slide 5 of 36© People Strategists www.peoplestrategists.com
The following figure depicts the events and listeners for a real life
application:
Identifying Listeners (Contd.)
Event and Listener Interaction
Slide 6 of 36© People Strategists www.peoplestrategists.com
Different levels of servlet events are:
Servlet context-level (application-level) event
 It involves resources or state held at the level of the application servlet context
object.
Session-level event
 It involves resources or state associated with the series of requests from a single
user session; that is, associated with the HTTP session object.
Each of these two levels has two event categories:
Lifecycle changes
 It involves the change in the resources or state that invokes the creation or
destruction of an object.
Attribute changes
 It involves the change in the properties or attributes associated with a resource or
state.
Identifying Listeners (Contd.)
Slide 7 of 36© People Strategists www.peoplestrategists.com
The following table lists the Event categories and the Event Listeners:
Identifying Listeners (Contd.)
Event Category Listeners
Servlet
context
Lifecycle changes javax.servlet.ServletContextListener
Attribute changes javax.servlet.ServletContextAttribut
eListener
Session
Lifecycle changes javax.servlet.http.HttpSessionListen
er
Attribute changes javax.servlet.http.HttpSessionAttrib
uteListener
Slide 8 of 36© People Strategists www.peoplestrategists.com
The following table lists the methods of the ServletContextListener
interface and ServletContextEvent class:
The servlet container creates a ServletContextEvent object that is
input for calls to ServletContextListener methods.
Identifying Listeners (Contd.)
Class/Interface Methods Description
ServletContextListener
void contextInitialized
(ServletContextEvent s)
Notifies the listener that the
servlet context has been
created and the application
is ready to process requests.
void contextDestroyed
(ServletContextEvent s)
Notifies the listener that the
application is about to be
shut down.
ServletContextEvent ServletContext
getServletContext()
Retrieves the servlet context
object that was created or is
about to be destroyed, from
which you can obtain
information as desired.
Slide 9 of 36© People Strategists www.peoplestrategists.com
The following table lists the methods of the
ServletContextAttributeListener interface and the
ServletContextAttributeEvent class:
The servlet container creates a ServletContextAttributeEvent
object that is input for calls to ServletContextAttributeListener
methods.
Identifying Listeners (Contd.)
Class/Interface Methods Description
ServletContext
AttributeListener
void attributeAdded
(ServletContextAttribute
Event s)
Notifies the listener that an attribute was
added to the servlet context.
void attributeRemoved
(ServletContextAttribute
Event s)
Notifies the listener that an attribute was
removed from the servlet context.
void attributeReplaced
(ServletContextAttribute
Event s)
Notifies the listener that an attribute was
replaced in the servlet context.
ServletContext
AttributeEvent
String getName() Returns the name of the attribute that
was added, removed, or replaced.
Object getValue() Returns the value of the attribute that
was added, removed, or replaced.
Slide 10 of 36© People Strategists www.peoplestrategists.com
The following table lists the methods of the HttpSessionListener
interface and HttpSessionEvent class:
The servlet container creates a HttpSessionEvent object that is input
for calls to HttpSessionListener methods.
Identifying Listeners (Contd.)
Class/Interface Methods Description
HttpSessionListener
Void sessionCreated
(HttpSessionEvent h)
Notifies the listener that a
session was created.
void sessionDestroyed
(HttpSessionEvent h)
Notifies the listener that a
session was destroyed.
HttpSessionEvent HttpSession getSession() Retrieves the session object
that was created or
destroyed, from which you
can obtain information as
desired.
Slide 11 of 36© People Strategists www.peoplestrategists.com
The following table lists the methods of the
HttpSessionAttributeListener interface and
HttpSessionBindingEvent class:
The servlet container creates a HttpSessionBindingEvent object
that is input for calls to HttpSessionAttributeListener
methods.
Identifying Listeners (Contd.)
Class/Interface Methods Description
ServletContext
AttributeListener
void attributeAdded
(HttpSessionBindingEvent s)
Notifies the listener that an attribute
was added to the session.
void attributeRemoved
(HttpSessionBindingEvent s)
Notifies the listener that an attribute
was removed from the servlet context.
void attributeReplaced
(HttpSessionBindingEvent s)
Notifies the listener that an attribute
was replaced in the servlet context.
HttpSession
BindingEvent
String getName() Returns the name of the attribute that
was added, removed, or replaced.
Object getValue() Returns the value of the attribute that
was added, removed, or replaced.
HttpSession getSession() Retrieves the session object that had the
attribute change.
Slide 12 of 36© People Strategists www.peoplestrategists.com
It is used to handle events related to the start and shutdown of an
application.
Implementing a ServletContextListener:
1. Import the ServletContextEvent and ServletContextListener
interfaces from the javax.servlet package.
2. Create a class that implements the ServletContextListener interface, as
shown in the following code:
3. Define the contextInitialized method, as shown in the following
code:
@Override
public void contextInitialized(ServletContextEvent arg) {
System.out.println("ServletContextListener started");
}
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyContextListener implements
ServletContextListener{
. . . .
}
Implementing ServletContextListener
Slide 13 of 36© People Strategists www.peoplestrategists.com
4. Define the contextDestroyed method, as shown in the following
code:
5. Map the declared listener in the web.xml file, as shown in the
following code:
You can annotate the listener class declaration with @WebListener, to
avoid the mapping.
<listener>
<listener-class>
com.example.listener.MyContextListener
</listener-class>
</listener>
@Override
public void contextDestroyed(ServletContextEvent arg) {
System.out.println("ServletContextListener destroyed");
}
Implementing ServletContextListener (Contd.)
Slide 14 of 36© People Strategists www.peoplestrategists.com
package com.example.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyContextListener implements
ServletContextListener{
@Override
public void contextInitialized(ServletContextEvent arg) {
System.out.println("ServletContextListener started");
}
@Override
public void contextDestroyed(ServletContextEvent arg) {
System.out.println("ServletContextListener destroyed");
}
}
On completion of the previous steps, the listener class appears as
shown in the following code:
Implementing ServletContextListener (Contd.)
Slide 15 of 36© People Strategists www.peoplestrategists.com
Activity: Context Lifecycle Listener
Consider a scenario where you have been asked to create a Web
application that displays a message at the time of initialization and at
the time of destruction of an application. For this, you need to
implement ServletContextListener interface in your application.
.
Slide 16 of 36© People Strategists www.peoplestrategists.com
Implement HttpSessionListener
The HttpSessionListener listener is used to handle the events
related to a session.
Implementing HttpSessionListener:
1. Import the HttpSessionEvent and HttpSessionListener
interfaces from the javax.servlet.http package.
2. Create a class that implements the HttpSessionListener interface,
as shown in the following code:
3. Define the sessionCreated method. Following is an example to
implement it:
In the preceding code snippet, the sessionCount variable gets
incremented whenever a new session is created.
public void sessionCreated(HttpSessionEvent event) {
synchronized (this) {
sessionCount++;
}
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener
{. . . .}
Slide 17 of 36© People Strategists www.peoplestrategists.com
Session Lifecycle Listener (Contd.)
4. Define the sessionDestroyed method, as shown in the following
code:
5. Map the listener class in the web.xml file, as shown in the following
code:
<listener>
<description>sessionListener</description>
<listener-class>
com.example.listener.MySessionListener
</listener-class>
</listener>
public void sessionDestroyed(HttpSessionEvent event) {
synchronized (this) {
sessionCount--;
}
Slide 18 of 36© People Strategists www.peoplestrategists.com
Session Lifecycle Listener (Contd.)
package com.example.listener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class MySessionListener implements HttpSessionListener
{
public static int sessionCount;
public void sessionCreated(HttpSessionEvent event) {
synchronized (this) {
sessionCount++;
}
public void sessionDestroyed(HttpSessionEvent event) {
synchronized (this) {
sessionCount--;
}
}
On completion of the previous steps, the listener class appears as
shown in the following code:
Slide 19 of 36© People Strategists www.peoplestrategists.com
Activity: Implementing HttpSessionListener
Consider a scenario where you have been asked to create a Web
application that will keep track of number of sessions currently
available. For this, you need to implement the
HttpSessionListener.
Slide 20 of 36© People Strategists www.peoplestrategists.com
Listeners can be used to:
Handle events raised by the Web application.
Manage the database connection.
Track HTTP session use.
Perform one-time application setup and shutdown task.
Usage of Listeners
Slide 21 of 36© People Strategists www.peoplestrategists.com
Identifying Filters
What does filters
means in servlet
technology?
Slide 22 of 36© People Strategists www.peoplestrategists.com
Filters:
Are Java classes that implements the javax.servlet.Filter interface.
Are objects that intercept the requests and response that flow between a
client and a servlet.
Modify the headers and content of a request coming from a Web client and
forward it to the target servlet.
Intercept and manipulate the headers and contents of the response that the
servlet sends back.
The following figure depicts how filters works:
Identifying Filters (Contd.)
Slide 23 of 36© People Strategists www.peoplestrategists.com
In a Web application, servlet filters can be used to:
Identify the type of request coming from the Web client, such as HTTP
and File Transfer Protocol (FTP) and invoke the servlet that needs to
process the request.
Validate a client using servlet filters before the client accesses the
servlet.
Retrieve the user information from the request parameters to
authenticate the user.
Identify the information about the MIME types and other header
contents of the request.
Transform the MIME types into compatible types corresponding to the
servlet.
Facilitate a servlet to communicate with the external resources.
Intercept responses and compress it before sending the response to the
client.
Identifying Filters (Contd.)
Slide 24 of 36© People Strategists www.peoplestrategists.com
The following figure displays how the servlet container calls filter.
Exploring the Execution of Filters
Servlet Invocation With Filters
Slide 25 of 36© People Strategists www.peoplestrategists.com
The order in which filters are executed depends on the order in which
they are configured in web.xml.
The first filter in web.xml is the first one to be invoked during the
request.
The last filter in web.xml is the first one to be invoked during the
response.
The order of filters’ execution in response is reverse of that in request
and vice versa.
Exploring the Execution of Filters (Contd.)
Slide 26 of 36© People Strategists www.peoplestrategists.com
A servlet filter comprises of the following methods:
Exploring Methods of Filters
Method Description
public void
init(FilterConfig)
The Web container calls this method to initialize a
filter that is being placed into service. It uses
FilterConfig to provide init parameters and
ServletContext object to Filter. The init method
enables you to get the parameters defined in the
web.xml file.
public void doFilter
(ServletRequest,
ServletResponse, FilterChain)
The Web container calls this method 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. You can add the desired functionality to a filter
using this method.
public void destroy() The Web container calls this method to notify to a
filter that it is being taken out of service. This method
is called only once in the lifetime of filter.
Slide 27 of 36© People Strategists www.peoplestrategists.com
Implementing Filters in a Web Application
Create a filter
Map a filter
To implement servlet filter in a Web application, you need to
perform following steps:
Slide 28 of 36© People Strategists www.peoplestrategists.com
Implementing Filters in a Web Application (Contd.)
Implementing filters in a Web application:
1. Create a Java class that implements the Filter interface.
2. Import the Filter, FilterChain, and FilterConfig interfaces
from the javax.servlet package.
3. Annotate the Java class as filter. For this you need to import the
@WebFilter annotation from the javax.servlet.annotation
package, as shown in the following code:
package com.example;
. . . .
@WebFilter("/AuthFilter")
public class AuthFilter implements Filter {
. . . . . }
Slide 29 of 36© People Strategists www.peoplestrategists.com
Implementing Filters in a Web Application (Contd.)
4. Define the init()method in the filter class, as shown in the following
code:
5. Define the doFilter()method, as shown in the following code:
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain)throws IOException, ServletException {
String uri = req.getRequestURI();
HttpSession session = req.getSession(false);
if(session == null && !(uri.endsWith("html")||
uri.endsWith("LoginServlet"))){
res.sendRedirect("login.html");
}else{
chain.doFilter(request, response);
}
public void init(FilterConfig f) throws ServletException {
this.context = f.getServletContext();
}
Slide 30 of 36© People Strategists www.peoplestrategists.com
Implementing Filters in a Web Application (Contd.)
In the preceding code snippet, the following execution takes place:
 The URI of the request is fetched from the request header.
 The object of the HttpSession class is retrieved using the getSession
method.
 If the session is null and the request is made to any other Web page except
Login page or LoginServlet, the res object redirects the user to login.html
page.
 If the session is not null, the requested Web page will be fetched.
Slide 31 of 36© People Strategists www.peoplestrategists.com
Implementing Filters in a Web Application (Contd.)
On completion of the previous steps, the listener class appears as
shown in the following code:
package com.example;
import java.util.*;
import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
@WebFilter("/AuthFilter")
public class AuthFilter implements Filter {
public void init(FilterConfig f) throws ServletException {
this.context = f.getServletContext();}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain)throws IOException, ServletException {
String uri = req.getRequestURI();
HttpSession session = req.getSession(false);
if(session == null && !(uri.endsWith("html")||
uri.endsWith("LoginServlet"))){
res.sendRedirect("login.html");
}else{
chain.doFilter(request, response);}
}
}
Slide 32 of 36© People Strategists www.peoplestrategists.com
Implementing Filters in a Web Application (Contd.)
Map a filter:
You need to map the filter class in the web.xml file.
To map the AuthFilter class, you can use the following code snippet:
You can map multiple filters by adding <filter> and <filter-mapping>
tag for each filter class.
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.example.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Slide 33 of 36© People Strategists www.peoplestrategists.com
Activity: Implementing Filters in a Web Application
Consider a scenario where for the maintenance purpose you need to
take your website offline for some times. For this you decide to
implement filter on the home page of your Web application so that
whenever any client try to access your application, filter will bypass
your request to a Web page that displays a "Website is temporarily
closed for maintenance. We will get back soon!!! “.
Slide 34 of 36© People Strategists www.peoplestrategists.com
Activity: Implementing Filters in a Web Application
Consider a scenario where you need to create a small Web
application that fulfills the following requirements:
Provides a form to accept user name and password, as shown in the
following figure.
Displays the welcome message with user name, if the user name is
admin and password is pass@123.
Displays “Access Denied” for users having user name James, Shelly, and
Tom.
The Expected User Interface
Slide 35 of 36© People Strategists www.peoplestrategists.com
Summary
In this you learned that:
A listener is an implemented interface, which responds to some event.
An event is a change in the state of an object like pressing mouse button.
The two level of events are:
 Servlet context-level event
 Session-level event
Servlet context-level event is an event related to application.
Session-level event is related to a session.
Based on the changes, the two types of event are:
 Lifecycle changes
 Attribute changes
Context Lifecycle Listener is an interface used to handle application level
events.
The Filter class implements the javax.servlet.Filter interface.
Slide 36 of 36© People Strategists www.peoplestrategists.com
Summary (Contd.)
A filter can be used to:
 Validate a client using servlet filters before the client accesses the servlet.
 Retrieve the user information from the request parameters to authenticate the
user.
 Identify the information about the MIME types and other header contents of
the request.
 Transform the MIME types into compatible types corresponding to the servlet.
 Facilitate a servlet to communicate with the external resources.
The order in which filters are executed depends on the order in which they
are configured in web.xml.
The first filter in web.xml is the first one to be invoked during the request.
The last filter in web.xml is the first one to be invoked during the response.
The order of filters’ execution in response is reverse of that in request and
vice versa.

More Related Content

What's hot

Java servlets
Java servletsJava servlets
Java servletslopjuan
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkRajind Ruparathna
 
Servlet api &amp; servlet http package
Servlet api &amp; servlet http packageServlet api &amp; servlet http package
Servlet api &amp; servlet http packagerenukarenuka9
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
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
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification QuestionsSpringMockExams
 
Developing Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring toolsDeveloping Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring toolsSathish Chittibabu
 
Different Types of Containers in Spring
Different Types of Containers in Spring Different Types of Containers in Spring
Different Types of Containers in Spring Sunil kumar Mohanty
 
Types of Dependency Injection in Spring
Types of Dependency Injection in SpringTypes of Dependency Injection in Spring
Types of Dependency Injection in SpringSunil kumar Mohanty
 
Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5IndicThreads
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Rossen Stoyanchev
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App EngineIndicThreads
 

What's hot (20)

Java servlets
Java servletsJava servlets
Java servlets
 
Listeners and filters in servlet
Listeners and filters in servletListeners and filters in servlet
Listeners and filters in servlet
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
Servlet api &amp; servlet http package
Servlet api &amp; servlet http packageServlet api &amp; servlet http package
Servlet api &amp; servlet http package
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
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 & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
 
Spring Certification Questions
Spring Certification QuestionsSpring Certification Questions
Spring Certification Questions
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Servlet lifecycle
Servlet lifecycleServlet lifecycle
Servlet lifecycle
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Developing Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring toolsDeveloping Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring tools
 
Different Types of Containers in Spring
Different Types of Containers in Spring Different Types of Containers in Spring
Different Types of Containers in Spring
 
Types of Dependency Injection in Spring
Types of Dependency Injection in SpringTypes of Dependency Injection in Spring
Types of Dependency Injection in Spring
 
Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5Indic threads pune12-java ee 7 platformsimplification html5
Indic threads pune12-java ee 7 platformsimplification html5
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2
 
Testing Your Application On Google App Engine
Testing Your Application On Google App EngineTesting Your Application On Google App Engine
Testing Your Application On Google App Engine
 

Similar to Identifing Listeners and Filters

Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa Aptech
Session 3   inter-servlet communication & filters  - Giáo trình Bách Khoa AptechSession 3   inter-servlet communication & filters  - Giáo trình Bách Khoa Aptech
Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa AptechMasterCode.vn
 
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
Session 2   servlet context and session tracking - Giáo trình Bách Khoa AptechSession 2   servlet context and session tracking - Giáo trình Bách Khoa Aptech
Session 2 servlet context and session tracking - Giáo trình Bách Khoa AptechMasterCode.vn
 
Java gui event
Java gui eventJava gui event
Java gui eventSoftNutx
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin componentsPeter Lehto
 
Factory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilitiesFactory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilitiesbabak danyal
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsAleksandar Ilić
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsPSTechSerbia
 
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R AugeHTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Augemfrancis
 
Webinar - What's new in Axon 3
Webinar - What's new in Axon 3 Webinar - What's new in Axon 3
Webinar - What's new in Axon 3 Allard Buijze
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Nida Ismail Shah
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJoshua Long
 
What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2Santosh Singh Paliwal
 
Advance java session 18
Advance java session 18Advance java session 18
Advance java session 18Smita B Kumar
 

Similar to Identifing Listeners and Filters (20)

Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 
Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa Aptech
Session 3   inter-servlet communication & filters  - Giáo trình Bách Khoa AptechSession 3   inter-servlet communication & filters  - Giáo trình Bách Khoa Aptech
Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa Aptech
 
Annotation processing
Annotation processingAnnotation processing
Annotation processing
 
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
Session 2   servlet context and session tracking - Giáo trình Bách Khoa AptechSession 2   servlet context and session tracking - Giáo trình Bách Khoa Aptech
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
 
Java gui event
Java gui eventJava gui event
Java gui event
 
Binding business data to vaadin components
Binding business data to vaadin componentsBinding business data to vaadin components
Binding business data to vaadin components
 
Struts2 - 101
Struts2 - 101Struts2 - 101
Struts2 - 101
 
Factory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilitiesFactory method, strategy pattern & chain of responsibilities
Factory method, strategy pattern & chain of responsibilities
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
Java Svet - Communication Between Android App Components
Java Svet - Communication Between Android App ComponentsJava Svet - Communication Between Android App Components
Java Svet - Communication Between Android App Components
 
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R AugeHTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
HTTP Whiteboard - OSGI Compendium 6.0 - How web apps should have been! - R Auge
 
Webinar - What's new in Axon 3
Webinar - What's new in Axon 3 Webinar - What's new in Axon 3
Webinar - What's new in Axon 3
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Struts2 notes
Struts2 notesStruts2 notes
Struts2 notes
 
Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.Events: The Object Oriented Hook System.
Events: The Object Oriented Hook System.
 
Java servlets
Java servletsJava servlets
Java servlets
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
 
What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2
 
Advance java session 18
Advance java session 18Advance java session 18
Advance java session 18
 
Servlet session 9
Servlet   session 9Servlet   session 9
Servlet session 9
 

More from People Strategists (20)

MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
 
Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
 
Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
 
Spring Framework -I
Spring Framework -ISpring Framework -I
Spring Framework -I
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
 
Hibernate III
Hibernate IIIHibernate III
Hibernate III
 
Hibernate I
Hibernate IHibernate I
Hibernate I
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
 
Overview of JEE Technology
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
 
JSP Technology II
JSP Technology IIJSP Technology II
JSP Technology II
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 

Recently uploaded

Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
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
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
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
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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
 
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
 
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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 

Recently uploaded (20)

Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
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
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
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
 
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
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 

Identifing Listeners and Filters

  • 1. Slide 1 of 36© People Strategists www.peoplestrategists.com Identifying Listeners & Filters
  • 2. Slide 2 of 36© People Strategists www.peoplestrategists.com Objectives In this session, you will learn to: Identify listeners Identify usage of listeners in Web application Identify filters Explore lifecycle of filters Implement filters in a Web applications
  • 3. Slide 3 of 36© People Strategists www.peoplestrategists.com Identifying Listeners How events are handled and who performs the action on the occurrence of an event?
  • 4. Slide 4 of 36© People Strategists www.peoplestrategists.com A listener is an implemented interface, which responds to a particular event. For example, pressing a mouse button or selecting an item from a list box, each one is an event, and the listeners are all the programs that execute on the occurrence of these events. The servlet specification includes the capability to track and handle events in your Web applications through event listeners. Identifying Listeners (Contd.) Button Press Event
  • 5. Slide 5 of 36© People Strategists www.peoplestrategists.com The following figure depicts the events and listeners for a real life application: Identifying Listeners (Contd.) Event and Listener Interaction
  • 6. Slide 6 of 36© People Strategists www.peoplestrategists.com Different levels of servlet events are: Servlet context-level (application-level) event  It involves resources or state held at the level of the application servlet context object. Session-level event  It involves resources or state associated with the series of requests from a single user session; that is, associated with the HTTP session object. Each of these two levels has two event categories: Lifecycle changes  It involves the change in the resources or state that invokes the creation or destruction of an object. Attribute changes  It involves the change in the properties or attributes associated with a resource or state. Identifying Listeners (Contd.)
  • 7. Slide 7 of 36© People Strategists www.peoplestrategists.com The following table lists the Event categories and the Event Listeners: Identifying Listeners (Contd.) Event Category Listeners Servlet context Lifecycle changes javax.servlet.ServletContextListener Attribute changes javax.servlet.ServletContextAttribut eListener Session Lifecycle changes javax.servlet.http.HttpSessionListen er Attribute changes javax.servlet.http.HttpSessionAttrib uteListener
  • 8. Slide 8 of 36© People Strategists www.peoplestrategists.com The following table lists the methods of the ServletContextListener interface and ServletContextEvent class: The servlet container creates a ServletContextEvent object that is input for calls to ServletContextListener methods. Identifying Listeners (Contd.) Class/Interface Methods Description ServletContextListener void contextInitialized (ServletContextEvent s) Notifies the listener that the servlet context has been created and the application is ready to process requests. void contextDestroyed (ServletContextEvent s) Notifies the listener that the application is about to be shut down. ServletContextEvent ServletContext getServletContext() Retrieves the servlet context object that was created or is about to be destroyed, from which you can obtain information as desired.
  • 9. Slide 9 of 36© People Strategists www.peoplestrategists.com The following table lists the methods of the ServletContextAttributeListener interface and the ServletContextAttributeEvent class: The servlet container creates a ServletContextAttributeEvent object that is input for calls to ServletContextAttributeListener methods. Identifying Listeners (Contd.) Class/Interface Methods Description ServletContext AttributeListener void attributeAdded (ServletContextAttribute Event s) Notifies the listener that an attribute was added to the servlet context. void attributeRemoved (ServletContextAttribute Event s) Notifies the listener that an attribute was removed from the servlet context. void attributeReplaced (ServletContextAttribute Event s) Notifies the listener that an attribute was replaced in the servlet context. ServletContext AttributeEvent String getName() Returns the name of the attribute that was added, removed, or replaced. Object getValue() Returns the value of the attribute that was added, removed, or replaced.
  • 10. Slide 10 of 36© People Strategists www.peoplestrategists.com The following table lists the methods of the HttpSessionListener interface and HttpSessionEvent class: The servlet container creates a HttpSessionEvent object that is input for calls to HttpSessionListener methods. Identifying Listeners (Contd.) Class/Interface Methods Description HttpSessionListener Void sessionCreated (HttpSessionEvent h) Notifies the listener that a session was created. void sessionDestroyed (HttpSessionEvent h) Notifies the listener that a session was destroyed. HttpSessionEvent HttpSession getSession() Retrieves the session object that was created or destroyed, from which you can obtain information as desired.
  • 11. Slide 11 of 36© People Strategists www.peoplestrategists.com The following table lists the methods of the HttpSessionAttributeListener interface and HttpSessionBindingEvent class: The servlet container creates a HttpSessionBindingEvent object that is input for calls to HttpSessionAttributeListener methods. Identifying Listeners (Contd.) Class/Interface Methods Description ServletContext AttributeListener void attributeAdded (HttpSessionBindingEvent s) Notifies the listener that an attribute was added to the session. void attributeRemoved (HttpSessionBindingEvent s) Notifies the listener that an attribute was removed from the servlet context. void attributeReplaced (HttpSessionBindingEvent s) Notifies the listener that an attribute was replaced in the servlet context. HttpSession BindingEvent String getName() Returns the name of the attribute that was added, removed, or replaced. Object getValue() Returns the value of the attribute that was added, removed, or replaced. HttpSession getSession() Retrieves the session object that had the attribute change.
  • 12. Slide 12 of 36© People Strategists www.peoplestrategists.com It is used to handle events related to the start and shutdown of an application. Implementing a ServletContextListener: 1. Import the ServletContextEvent and ServletContextListener interfaces from the javax.servlet package. 2. Create a class that implements the ServletContextListener interface, as shown in the following code: 3. Define the contextInitialized method, as shown in the following code: @Override public void contextInitialized(ServletContextEvent arg) { System.out.println("ServletContextListener started"); } import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class MyContextListener implements ServletContextListener{ . . . . } Implementing ServletContextListener
  • 13. Slide 13 of 36© People Strategists www.peoplestrategists.com 4. Define the contextDestroyed method, as shown in the following code: 5. Map the declared listener in the web.xml file, as shown in the following code: You can annotate the listener class declaration with @WebListener, to avoid the mapping. <listener> <listener-class> com.example.listener.MyContextListener </listener-class> </listener> @Override public void contextDestroyed(ServletContextEvent arg) { System.out.println("ServletContextListener destroyed"); } Implementing ServletContextListener (Contd.)
  • 14. Slide 14 of 36© People Strategists www.peoplestrategists.com package com.example.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class MyContextListener implements ServletContextListener{ @Override public void contextInitialized(ServletContextEvent arg) { System.out.println("ServletContextListener started"); } @Override public void contextDestroyed(ServletContextEvent arg) { System.out.println("ServletContextListener destroyed"); } } On completion of the previous steps, the listener class appears as shown in the following code: Implementing ServletContextListener (Contd.)
  • 15. Slide 15 of 36© People Strategists www.peoplestrategists.com Activity: Context Lifecycle Listener Consider a scenario where you have been asked to create a Web application that displays a message at the time of initialization and at the time of destruction of an application. For this, you need to implement ServletContextListener interface in your application. .
  • 16. Slide 16 of 36© People Strategists www.peoplestrategists.com Implement HttpSessionListener The HttpSessionListener listener is used to handle the events related to a session. Implementing HttpSessionListener: 1. Import the HttpSessionEvent and HttpSessionListener interfaces from the javax.servlet.http package. 2. Create a class that implements the HttpSessionListener interface, as shown in the following code: 3. Define the sessionCreated method. Following is an example to implement it: In the preceding code snippet, the sessionCount variable gets incremented whenever a new session is created. public void sessionCreated(HttpSessionEvent event) { synchronized (this) { sessionCount++; } import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class MySessionListener implements HttpSessionListener {. . . .}
  • 17. Slide 17 of 36© People Strategists www.peoplestrategists.com Session Lifecycle Listener (Contd.) 4. Define the sessionDestroyed method, as shown in the following code: 5. Map the listener class in the web.xml file, as shown in the following code: <listener> <description>sessionListener</description> <listener-class> com.example.listener.MySessionListener </listener-class> </listener> public void sessionDestroyed(HttpSessionEvent event) { synchronized (this) { sessionCount--; }
  • 18. Slide 18 of 36© People Strategists www.peoplestrategists.com Session Lifecycle Listener (Contd.) package com.example.listener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class MySessionListener implements HttpSessionListener { public static int sessionCount; public void sessionCreated(HttpSessionEvent event) { synchronized (this) { sessionCount++; } public void sessionDestroyed(HttpSessionEvent event) { synchronized (this) { sessionCount--; } } On completion of the previous steps, the listener class appears as shown in the following code:
  • 19. Slide 19 of 36© People Strategists www.peoplestrategists.com Activity: Implementing HttpSessionListener Consider a scenario where you have been asked to create a Web application that will keep track of number of sessions currently available. For this, you need to implement the HttpSessionListener.
  • 20. Slide 20 of 36© People Strategists www.peoplestrategists.com Listeners can be used to: Handle events raised by the Web application. Manage the database connection. Track HTTP session use. Perform one-time application setup and shutdown task. Usage of Listeners
  • 21. Slide 21 of 36© People Strategists www.peoplestrategists.com Identifying Filters What does filters means in servlet technology?
  • 22. Slide 22 of 36© People Strategists www.peoplestrategists.com Filters: Are Java classes that implements the javax.servlet.Filter interface. Are objects that intercept the requests and response that flow between a client and a servlet. Modify the headers and content of a request coming from a Web client and forward it to the target servlet. Intercept and manipulate the headers and contents of the response that the servlet sends back. The following figure depicts how filters works: Identifying Filters (Contd.)
  • 23. Slide 23 of 36© People Strategists www.peoplestrategists.com In a Web application, servlet filters can be used to: Identify the type of request coming from the Web client, such as HTTP and File Transfer Protocol (FTP) and invoke the servlet that needs to process the request. Validate a client using servlet filters before the client accesses the servlet. Retrieve the user information from the request parameters to authenticate the user. Identify the information about the MIME types and other header contents of the request. Transform the MIME types into compatible types corresponding to the servlet. Facilitate a servlet to communicate with the external resources. Intercept responses and compress it before sending the response to the client. Identifying Filters (Contd.)
  • 24. Slide 24 of 36© People Strategists www.peoplestrategists.com The following figure displays how the servlet container calls filter. Exploring the Execution of Filters Servlet Invocation With Filters
  • 25. Slide 25 of 36© People Strategists www.peoplestrategists.com The order in which filters are executed depends on the order in which they are configured in web.xml. The first filter in web.xml is the first one to be invoked during the request. The last filter in web.xml is the first one to be invoked during the response. The order of filters’ execution in response is reverse of that in request and vice versa. Exploring the Execution of Filters (Contd.)
  • 26. Slide 26 of 36© People Strategists www.peoplestrategists.com A servlet filter comprises of the following methods: Exploring Methods of Filters Method Description public void init(FilterConfig) The Web container calls this method to initialize a filter that is being placed into service. It uses FilterConfig to provide init parameters and ServletContext object to Filter. The init method enables you to get the parameters defined in the web.xml file. public void doFilter (ServletRequest, ServletResponse, FilterChain) The Web container calls this method 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. You can add the desired functionality to a filter using this method. public void destroy() The Web container calls this method to notify to a filter that it is being taken out of service. This method is called only once in the lifetime of filter.
  • 27. Slide 27 of 36© People Strategists www.peoplestrategists.com Implementing Filters in a Web Application Create a filter Map a filter To implement servlet filter in a Web application, you need to perform following steps:
  • 28. Slide 28 of 36© People Strategists www.peoplestrategists.com Implementing Filters in a Web Application (Contd.) Implementing filters in a Web application: 1. Create a Java class that implements the Filter interface. 2. Import the Filter, FilterChain, and FilterConfig interfaces from the javax.servlet package. 3. Annotate the Java class as filter. For this you need to import the @WebFilter annotation from the javax.servlet.annotation package, as shown in the following code: package com.example; . . . . @WebFilter("/AuthFilter") public class AuthFilter implements Filter { . . . . . }
  • 29. Slide 29 of 36© People Strategists www.peoplestrategists.com Implementing Filters in a Web Application (Contd.) 4. Define the init()method in the filter class, as shown in the following code: 5. Define the doFilter()method, as shown in the following code: public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException { String uri = req.getRequestURI(); HttpSession session = req.getSession(false); if(session == null && !(uri.endsWith("html")|| uri.endsWith("LoginServlet"))){ res.sendRedirect("login.html"); }else{ chain.doFilter(request, response); } public void init(FilterConfig f) throws ServletException { this.context = f.getServletContext(); }
  • 30. Slide 30 of 36© People Strategists www.peoplestrategists.com Implementing Filters in a Web Application (Contd.) In the preceding code snippet, the following execution takes place:  The URI of the request is fetched from the request header.  The object of the HttpSession class is retrieved using the getSession method.  If the session is null and the request is made to any other Web page except Login page or LoginServlet, the res object redirects the user to login.html page.  If the session is not null, the requested Web page will be fetched.
  • 31. Slide 31 of 36© People Strategists www.peoplestrategists.com Implementing Filters in a Web Application (Contd.) On completion of the previous steps, the listener class appears as shown in the following code: package com.example; import java.util.*; import javax.servlet.*; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; @WebFilter("/AuthFilter") public class AuthFilter implements Filter { public void init(FilterConfig f) throws ServletException { this.context = f.getServletContext();} public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException { String uri = req.getRequestURI(); HttpSession session = req.getSession(false); if(session == null && !(uri.endsWith("html")|| uri.endsWith("LoginServlet"))){ res.sendRedirect("login.html"); }else{ chain.doFilter(request, response);} } }
  • 32. Slide 32 of 36© People Strategists www.peoplestrategists.com Implementing Filters in a Web Application (Contd.) Map a filter: You need to map the filter class in the web.xml file. To map the AuthFilter class, you can use the following code snippet: You can map multiple filters by adding <filter> and <filter-mapping> tag for each filter class. <filter> <filter-name>AuthFilter</filter-name> <filter-class>com.example.AuthFilter</filter-class> </filter> <filter-mapping> <filter-name>AuthFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
  • 33. Slide 33 of 36© People Strategists www.peoplestrategists.com Activity: Implementing Filters in a Web Application Consider a scenario where for the maintenance purpose you need to take your website offline for some times. For this you decide to implement filter on the home page of your Web application so that whenever any client try to access your application, filter will bypass your request to a Web page that displays a "Website is temporarily closed for maintenance. We will get back soon!!! “.
  • 34. Slide 34 of 36© People Strategists www.peoplestrategists.com Activity: Implementing Filters in a Web Application Consider a scenario where you need to create a small Web application that fulfills the following requirements: Provides a form to accept user name and password, as shown in the following figure. Displays the welcome message with user name, if the user name is admin and password is pass@123. Displays “Access Denied” for users having user name James, Shelly, and Tom. The Expected User Interface
  • 35. Slide 35 of 36© People Strategists www.peoplestrategists.com Summary In this you learned that: A listener is an implemented interface, which responds to some event. An event is a change in the state of an object like pressing mouse button. The two level of events are:  Servlet context-level event  Session-level event Servlet context-level event is an event related to application. Session-level event is related to a session. Based on the changes, the two types of event are:  Lifecycle changes  Attribute changes Context Lifecycle Listener is an interface used to handle application level events. The Filter class implements the javax.servlet.Filter interface.
  • 36. Slide 36 of 36© People Strategists www.peoplestrategists.com Summary (Contd.) A filter can be used to:  Validate a client using servlet filters before the client accesses the servlet.  Retrieve the user information from the request parameters to authenticate the user.  Identify the information about the MIME types and other header contents of the request.  Transform the MIME types into compatible types corresponding to the servlet.  Facilitate a servlet to communicate with the external resources. The order in which filters are executed depends on the order in which they are configured in web.xml. The first filter in web.xml is the first one to be invoked during the request. The last filter in web.xml is the first one to be invoked during the response. The order of filters’ execution in response is reverse of that in request and vice versa.