More Related Content
Similar to Identifing Listeners and Filters
Similar to Identifing Listeners and Filters (20)
More from People Strategists
More from People Strategists (20)
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.