You are on page 1of 28

JAVA

SERVLETS
Introduction
Servlet is a server-side technology written in Java. It runs inside a java enabled server or
application server. It is loaded and executed within the JVM of the Web Server or Application
Server.
Servlets more closely resemble Common Gateway Interface (CGI) scripts or programs than
applets in terms of functionality. As in CGI programs, Servlets can respond to user events from
an HTML request, and then dynamically construct an HTML response that is sent back to the
client.
Common Gateway Interface (CGI)
CGI scripts are written in C, C++ or Perl. With CGI, a server passes a client’s request to an
external program. This program executes, creates some content and sends a response to the
client. In case of an Application Server using CGI script to process a client request, the server
creates a separate instance of the CGI script to process the request. As a result, the efficiency of
the server is affected when there are a large number of concurrent requests.

Java Servlets
Using Servlets, a single process is used to handle multiple requests. This allows the main
process to share resources between multiple Servlets and multiple requests.
Web Server

Process

Request Servlet

Request Servlet

Request Servlet

IPSR Solutions Ltd www.ipsr.edu.in 1


JAVA

Servlet Features
Besides inheriting all the Java features, Servlets have the following features.
∑ Security: A Web container provides a run time environment for executing a Servlet.
Servlets inherit the security features provided by a Web container. This allows developers to
focus on the Servlet functionality and leave the security issues to the Web container to
handle.
∑ Session management: It is the mechanism of tracking the state of a user across multiple
requests. A session maintains the client identity and state across multiple requests.
∑ Instance persistence: Servlets help to enhance the performance of the server by preventing
frequent disk access.

Web Container
A Web container provides a runtime environment for running a Servlet. It provides services
required by the Web Applications such as:
∑ Managing various stages in the life cycle of a servlet, such as initializing a Servlet instance,
processing the client request and removing the Servlet instance from service
∑ Defining the security credentials that specifies that only authorized users can use the
deployed Servlets.
∑ Managing database transactions when a Servlet needs to read and write data from a database.
∑ Creating and removing Servlet instances from an instance pool during multiple requests.

IPSR Solutions Ltd www.ipsr.edu.in 2


JAVA

J2EE
Working of Servlets

Web

Loads the Servlet class


Instantiates the Servlet
Initializes the Servlet
First Client Request Passes request to the Servlet instance
Sends response

∑ Whenever a client sends a request to the Application Server for a particular Servlet, the
Application Server passes the request to the Container. The Web container checks whether
an instance of the requested Servlet exists. If the Servlet instance exists, then the Web
container delegates the request to the Servlet which processes the client request and sends
back the response.
∑ In case the Servlet does not exist, the Web container then locates and loads the Servlet class
and initializes it. Then the Servlet instance starts processing the request. The Web container
passes the response to the client.

The Java Servlets API

The Java Servlet API is a set of Java classes which define a standard interface between a Web
client and a Web servlet. Client requests are made to the Web server, which then invokes the
servlet to service the request through this interface.
The API is composed of two packages:
∑ javax.servlet
∑ javax.servlet.http
IPSR Solutions Ltd www.ipsr.edu.in 3
JAVA

The javax.servlet package contains classes to support generic protocol-independent Servlets.


This means that Servlets can be used for many protocols, for example, HTTP and FTP. The
javax.servlet.http package extends the functionality of the base package to include specific
support for the HTTP protocol
The Servlet Class Hierarchy

Servlet Interface ServletConfig Interface Serializable Interface

GenericServlet

HttpServlet

User Defined
Servlet Interface

Servlet interface
The Servlet interface is the root interface of the servlet class hierarchy. The class defines
methods which servlets must implement, including a service() method for the handling of
requests.
The main methods in javax.servlet.Servlet interface are as follows.
1. public void destroy(): the web container calls the destroy() just before removing the
servlet instance from service.
2. public ServletConfig getServletConfig(): Returns a ServletConfig object that contains
configuration information such as initialization parameters for a servlet.
3. public String getServletInfo(): Returns a string that contains information about the
servlet, such as author, version and copyright.
4. public void init(ServletConfig config) throws ServletException: The web container
calls this method after creating a servlet instance.
IPSR Solutions Ltd www.ipsr.edu.in 4
JAVA

GenericServlet Class
GenericServlet class implements the Servlet interface and defines a generic, protocol-
independent servlet. In addition to Servlet interface, it implements ServletConfig and
Serializable interfaces. The object of servletConfig interface is used by the Web container to
pass the configuration information to a servlet when a servlet is initialized.
HttpServlet Class
To develop a servlet that communicates using HTTP, we need to extend the HttpServlet class. It
extends the GenericServlet class and provides built-in HTTP functionality. HttpServlet provides
additional methods for the processing of HTTP requests such as GET ( doGet method) and
POST ( doPost method). Although our Servlets may implement a service method, in most cases
we will implement the HTTP specific request handling methods of doGet() and doPost() .
ServletConfig interface
The javax.servlet.ServletConfig is implemented by Web container to pass configuration
information to a servlet during initialization of a servlet. A servlet is initialized by passing an
object of ServletConfig to its init() by Web container. It contains initialization information and
provides access to the ServletContext object.
The object of ServletContext interface enables the servlet to communicate with the container
that hosts it.
The main methods in ServletConfig interface are:
1. public String getInitParameter(String param): Returns a string containing the value of
the specified initialization parameter or null if the parameter does not exist.
2. public Enumeration getInitParameterNames(): Returns the names of all initialization
parameters. If no parameters have been defined, an empty enumeration is returned.
3. public ServletContext getServletContext(): Returns ServletContext object for the
servlet which allows interaction with the Web container.

IPSR Solutions Ltd www.ipsr.edu.in 5


JAVA

The servlet life cycle


Servlets follow a three phase life: initialization, service and destruction. Initialization and
destruction are performed once, and service is performed many times. All servlets must
implement Servlet interface. The Servlet interface defines the life cycle methods such as init(),
service() and destroy(). The Web container invokes these methods during the life cycle of
servlets in the following sequence.
1. The Web container loads the servlet class and creates one or more instances of the servlet
class.
2. The Web container invokes the init() method of the servlet instance during the
initialization of the servlet.
3. The Web container invokes the service() method to allow a servlet to process a client
request. The service() is invoked once per request and is responsible for generating the
response to that request.
4. The service() processes the request and returns the response back to the Web container.
5. The servlet then waits to receive and process subsequent requests.
6. The Web container calls the destroy() method before removing the servlet instance from
service.

IPSR Solutions Ltd www.ipsr.edu.in 6


JAVA

Servlet Initialization : the init() method


The init() method is called during the initialization phase of the servlet life cycle. The Web
container first maps the requested URL to the corresponding servlet available in the Web
container and then instantiates the servlet. The Web container then creates an object of the
ServletConfig interface, which contains the startup configuration information such as
initialization parameters. The Web container then calls the init() method and passes the
ServletConfig object to it.
The init() method throws a ServletException if the Web container can’t initialize the servlet
resources.
public void init(ServletConfig config) throws ServletException
Servlet request handling : the service() method
The service() processes the request and is invoked only after the initialization of the servlet is
complete. When the Web container calls the service(), it passes an object of the ServletRequest
interface and an object of the ServletResponse interface.
The ServletRequest object contains information about the service request made by the client.
The ServletResponse object contains the information returned by the servlet to the client.
public void service(ServletRequest req, ServletResponse res) throws ServletException,
IOException
The service() method dispatches a client request to one of the request handler methods of the
HttpServlet interface such as doGet(), doPost(), doHead() or doPut().

The doGet() method


The doGet() method processes client request, which is sent by the client using the HTTP Get
method. Get is a type of HTTP request method that is commonly used to retrieve static
resources. The data sent using Get method is appeared as a query string to the URL and are
passed to the QueryString property of the HttpServletRequest. doGet() should be used when no
modifications will be made on the server or when the data are not sensitive.

IPSR Solutions Ltd www.ipsr.edu.in 7


JAVA

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws


ServletException, IOException
The doPost() method
The doPost() method processes client request, which is sent by the client using the HTTP Post
method. The Post method sends data as part of the HTTP request body and the data does not
appear as part of the URL. The doPost() should be used whenever modifications on the server
will take place and when the data is sensitive.
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
The destroy() method
The Web container calls the destroy() by removing a servlet instance from the service.
The Web container calls the destroy() when :
∑ The time period specified for the servlet has elapsed.
∑ The Web container needs to release servlet instances to conserve memory
∑ The Web container is about to shutdown.
In destroy() method, we can write code to release the resources occupied by the servlet. It is
also used to save any persistent information before the servlet instance is removed from the
service.
public void destroy()

The Servlet API


The classes and interfaces of the Servlet API are stored in the packages javax.servlet and
javax.servlet.http

The ServletRequest interface

The ServletRequest interface contains various methods to handle client requests to access a
servlet.
IPSR Solutions Ltd www.ipsr.edu.in 8
JAVA

The main methods of ServletRequest interface are:


1. public String getParameter(String param): Returns a String object that specifies the
value of a particular request parameter.
2. public String[ ] getParameterValues(String param): Returns an array of String objects
that contains all the values of the request parameter.
3. public String getRemoteHost( ): Returns a String that specifies the fully-qualified name
of a computer from which the request is sent.
4. public String getRemoteAddr():Returns a String that specifies the ipaddress of a
computer from which the request is sent.

The HttpServletRequest interface (extends ServletRequest interface)

HTTP requests have a number of associated headers. These headers provide extra information
about the client such as name and version of browser sending the request.
Some of the important HTTP request headers are:
∑ Accept: Specifies the MIME type that the client prefers to accept
∑ Accept-Language: Specifies the language in which the client prefers to receive the
request
∑ User-Agent: Specifies the name and version of the browser sending the request.
The main methods of HttpServletRequest interface are:
1. public String getHeader(String fieldname): returns the value of the request header
field such as cache-contril and accept-language specified in parameter.
2. public Enumeration getHeaders(String name): returns all the values associated with a
specified request header as an enumeration of String objects.
3. public Enumeration getHeaderNames()

IPSR Solutions Ltd www.ipsr.edu.in 9


JAVA

The ServletResponse interface


The ServletResponse interface contains various methods that allow a servlet to respond to the
client requests. A servlet can send the response either as character data or as binary data. The
PrintWriter stream can be used to send character data as response. The servletOutStream can be
used to send binary data as servlet response.
The main methods of ServletResponse interface are:
1. public ServletOutputStream getOutputStream() throws IOException: Returns an
object of the ServletOutStream class that represents an output stream to send binary data
as response.
2. public PrintWriter getWriter() throws IOException: Returns an object of the
PrintWriter class that the servlet uses to send character data as response.
3. public void setContentType(String type): Sets the MIME type for a servlet response.
Some of the MIME types are text/plain, image/jpeg and text/html.

The HttpServletResponse interface (extends ServletResponse interface)


It provides methods to handle response, status codes and response headers for servlets that
communicate using HTTP.
The main methods of HttpServletResponse interface are:
1. void setHeader(String hname, String hvalue): if the header has already been set, the
new value overwrites the existing value
2. void setIntHeader(String hname, int hvalue)
3. void setDateHeder(String haname, long value)
4. void addHeader(string hname,String hvalue): adds a new header if the header already
exists.
5. void addIntHeader(String hname, int hvalue)
6. void addDateHeder(String haname, long value)
7. boolean containsHeader(String hname)
8. void sendRedirect(String url): redirects a request to the specified url
IPSR Solutions Ltd www.ipsr.edu.in 10
JAVA

The ServletContext interface


The ServletContext interface provides information to servlets regarding the environment in
which they are running. The context is also called as servlet context or web context and is
created by Web container as an object of ServletContext interface. The Web container creates a
ServletContext object for each web application.
This object can be used to find path information of other files of the Web application, access
other servlets of the Web application and log messages to the application server log file. The
object can also be used to set attributes that other servlets can access.
The main methods of ServletContext interface are:
1. public void setAttribute(String name, Object object): Binds the object with a name
and stores the name/value pair as an attribute of the ServletContext object. If an attribute
already exists, then the method replaces the existing attribute.
2. public Object getAttribute(String name): Returns the object stored in the
ServletContext object with the name passed as parameter.
3. public enumeration getAttributeNames()
4. public String getInitParameter(String name): Returns the value of the servlet
initialization parameter with the specified name.
5. public Enumeration getInitParameterNames()
To use the ServletContext object, we need to retrieve the ServletContext object in init(). The
getServletContext() method of the ServletConfig interface enables us to obtain ServletContext
object.

Example

Servlet to set the context attribute

IPSR Solutions Ltd www.ipsr.edu.in 11


JAVA

Servlet to retrieve the context attribute

IPSR Solutions Ltd www.ipsr.edu.in 12


JAVA

The HttpSession interface

The HttpSession interface contains methods to maintain the state of an end user across a Web
application. It provides support for tracking and managing the session of an end user.
The main methods are:
1. public void setAttribute(String name, Object value)
2. public Object getAttribute(String name)
3. public Enumeration getAttributeNames()

Servlet Initialization Parameter


This initialization parameter is available only to the servlet for which it is declared.
The <init-param> element of the deployment descriptor, web.xml, specifies the name/value pair
of Servlet initialization parameter.

Context Initialization Parameter


Context initialization parameters are name/value pairs that we can specify during the
deployment of a Web application. The initialization parameters can be used to provide
information that are accessible to all servlets of a Web application. When we deploy a Web
application, the Web container reads the initialization parameter from the deployment descriptor
and initializes the ServletContext object with it. The <context-param> element of the
deployment descriptor specifies the name/value pair of context initialization parameter.

Servlet Events
The Web container provides notifications to a listener class when an event occurs during the life
cycle of the servlet. To receive notification of an event, a listener class needs to extend a listener
interface of the Servlet API.
Types of events
IPSR Solutions Ltd www.ipsr.edu.in 13
JAVA

The various events that are generated during the life cycle of a servlet are:
∑ Servlet request events
∑ Servlet context events
∑ Servlet session events
The Servlet Request Events
The events that are related to changes in the request objects associated with a Web application
are known as servlet request events.
The following two interfaces represent the servlet request events.
∑ javax.servlet.ServletRequestEvent
∑ javax.servlet.ServletRequestAttributeEvent
The Web container creates ServletRequestEvent object while:
∑ initializing a request object when a request arrives
∑ removing a request object when it is not required.

The Web container creates ServletRequestAttributeEvent object when there is a change in the
attribute of a servlet request such as:
∑ addition of an attribute to the request object
∑ removal of an attribute from the servlet request object
∑ replacement of an attribute in the servlet request object with another attribute of the same
name

The Servlet Context Events


The events that are related to changes in the context of a Web application are known as servlet
request events.
The following two interfaces represent the servlet context events.
∑ javax.servlet.ServletContextEvent
∑ javax.servlet.ServletContextAttributeEvent
IPSR Solutions Ltd www.ipsr.edu.in 14
JAVA

The Web container creates ServletContextEvent object during:


∑ initialization phase of the servlet life cycle
∑ removal of the ServletContext object

The Web container creates ServletContextAttributeEvent object when there is a change in the
attribute of a servlet context such as:
∑ addition of an attribute to the context object
∑ removal of an attribute from the servlet context object
∑ replacement of an attribute in the servlet context object with another attribute of the same
name.

The Http Session Events


The events that are related to changes in the session of a Web application are known as servlet
request events.
The following interfaces represent the servlet session events.
∑ javax.servlet.http.HttpSessionEvent
∑ javax.servlet.http.HttpSessionAttributeEvent
∑ javax.servlet.http.HttpSessionActivationEvent
∑ javax.servlet.http.HttpSessionBindingEvent
The Web container creates the HttpSessionEvent object during:
∑ creation of a new session
∑ invalidation of a new session
∑ expiry of a session
The Web container creates the HttpSessionAttributeEvent object during:
∑ addition of an attribute to the session object
∑ removal of an attribute from the servlet sessionobject
∑ replacement of an attribute in the servlet session object with another attribute of the same
name.
IPSR Solutions Ltd www.ipsr.edu.in 15
JAVA

The Web container creates the HttpSessionBindingEvent object when:


∑ a servlet object is bound to a session
∑ a servlet object is unbounded from the session
The Web container creates the HttpSessionActivationEvent object when:
∑ the session is activated
∑ the session is passivated

Handling of Servlet Life Cycle Events


The classes that receive notification about the servlet life cycle events are known as event
listeners. These listener classes implement one or more servlet event listener interfaces that are
defined in the Servlet API. The listener classes are:
∑ Servlet Request Listeners
∑ Servlet Context Listeners
∑ HTTP Session Listeners
The Servlet Request Listener
It implements javax.servlet.ServletRequestListener interface and javax. servlet. ServletRequest
AttributeListener interface.

The main methods in these interfaces are:


∑ javax.servlet.ServletRequestListener
ÿ void requestInitialized(ServletRequestEvent e)
ÿ void requestDestroyed(ServletRequestEvent e)
∑ javax.servlet.ServletRequestAttributeListener
ÿ void attributeAdded(ServletRequestAttributeEvent e)
ÿ void attributeRemoved(ServletRequestAttributeEvent e)
ÿ void attributeReplaced(ServletRequestAttributeEvent e)

The Servlet Context Listener


IPSR Solutions Ltd www.ipsr.edu.in 16
JAVA

It implements javax.servlet.ServletContextListener interface and javax. servlet. ServletContext


AttributeListener interface.

The main methods in these interfaces are:


∑ javax.servlet.ServletContextListener
ÿ void contextInitialized(ServletContextEvent e)
ÿ void contextDestroyed(ServletContextEvent e)
∑ javax.servlet.ServletContextAttributeListener
ÿ void attributeAdded(ServletContextAttributeEvent e)
ÿ void attributeRemoved(ServletContextAttributeEvent e)
ÿ void attributeReplaced(ServletContextAttributeEvent e)

The HTTP Session Listener


It implements javax.servlet.http.HttpSessionListener interface, javax.servlet.http.HttpSession
AttributeListener interface and javax.servlet.http.HttpSessionActivationListener.

The main methods in these interfaces are:


∑ javax.servlet.http.HttpSessionListener
ÿ void sessionCreated(HttpSessionEvent e)
ÿ void sessionDestroyed(HttpSessionEvent e)
∑ javax.servlet.http.HttpSessionAttributeListener
ÿ void attributeAdded(HttpSessionBindingEvent e)
ÿ void attributeRemoved(HttpSessionBindingEvent e)
ÿ void attributeReplaced(HttpSessionBindingEvent e)
∑ javax.servlet.http.HttpSessionActivationListener
ÿ void sessionDidActivate(HttpSessionEvent e)
ÿ void sessionWillPassivate(HttpSessionEvent e)

IPSR Solutions Ltd www.ipsr.edu.in 17


JAVA

Example
The following program logs the time when the request and context objects are initialized and
when an attribute is added to the context object. At the same, it also logs the time when the
attribute is removed from the context object and when the request and context objects are
destroyed

Servlet that adds attribute to the context object

Servlet that logs the time of events

IPSR Solutions Ltd www.ipsr.edu.in 18


JAVA

IPSR Solutions Ltd www.ipsr.edu.in 19


JAVA

Session Management
Session management is the process of keeping track of the activities of a user across Web pages.
It can also be used to keep track of the user’s preferences.
Session Management Techniques
HTTP is a stateless protocol and therefore cannot store information about the user activities
across Web pages. The techniques used to maintain the session information are:
∑ Hidden form field
∑ URL rewriting
∑ Cookies
∑ Servlet Session API

Hidden Form Field


A hidden form field is embedded in an HTML page and is not visible when viewed in a
browser.
<input type=”hidden” name=” user“ value=”ipsr “/>
It can be taken in the servlet as
request.getParameter(user);

URL rewriting
This technique manages the session by modifying a URL. Usually this technique is used when
information that is to be transferred is not very critical because the URL can be intercepted
easily during transfer.
pw.println(“<a
href=\http://localhost:8080/rewrite_cntxt/servlet/SecondServlet?uname=+user+”\”>Click</a>
to proceed”>
in SecondServlet the value for uname is retrieved using request object
request. getParameter(uname);

IPSR Solutions Ltd www.ipsr.edu.in 20


JAVA

Using Cookies
Cookies are small text files that are stored by an application server in the client browser to keep
track of all the users. A cookie has values in the form of name/value pairs.
Cookies are created by the server and are sent to the client with the HTTP response headers.
The client saves the cookies in the local hard disk and sends them along with the HTTP request
headers to the server.
A Web browser is expected to support 20 cookies per host and the size of each cookie can be a
maximum of 4 bytes. Cookies can only be read by the application server that had written them
in the client browser. Cookies can be used by the server to find out the computer name, IP
address or any other details of the client by retrieving the remote host address of the client
where the cookies are stored.
The Cookie class of javax.servlet.http package represents a cookie. The Cookie class provides a
constructor that accepts the name and value to create a cookie.
public Cookie(String,String){ }
The HttpServletResponse interface provides the addCookie() to add a cookie to the Response
object.
response.addCookie(cookiename);
The HttpServletRequest interface provides the getCookies() that returns an array of Cookies
that the request contains.
Cookie[] cookie=request.getCookies();
Methods of Cookie class
Method Description
public String getName() Returns name of the Cookie
public void setMaxAge(int expiry) Sets the maximum time for which the
client browser retains the cookie value.
public int getMaxAge() Returns the maximum age of the cookie in
seconds

IPSR Solutions Ltd www.ipsr.edu.in 21


JAVA

public void setValue(String value) Sets a new value to the cookie


public String getValue() Returns the value of the cookie

Servlet Session API


Various interfaces provided by Servlet Session API to create and manage user session are,
∑ javax.servlet.http.HttpSession
∑ javax.servlet.http.HttpSessionListener
∑ javax.servlet.http.HttpSessionBindingListener
Methods of HttpSession interface
∑ public void setAttribute(String name,Object value)
∑ public Object getAttribute(String name)
∑ public Enumeration getAttributeNames()
∑ public void removeAttribute(String name)
∑ public void setMaxInactiveInterval(int interval)
∑ public int maxInactiveInterval()
∑ public String getId() – returns unique id associated with the session
∑ public void invalidate()
Session invalidate
We may require invalidating a session in various situations such as when the user logs off from
the application, or when the user is idle for a considerable period of time. We can invalidate a
session by using various methods of HttpSession interface
∑ by setting the maximum inactive time by using the setMaxInactiveInterval(int s) method.
∑ By explicitly calling the invalidate() method of session object
∑ By specifying the time out value of the session in minutes, in the session-time-out
element of the deployment descriptor.

Inter Servlet Communication


IPSR Solutions Ltd www.ipsr.edu.in 22
JAVA

The inter-servlet communication can be implemented in the following two ways.


∑ Using request dispatcher
∑ Using sendRedirect()

Request Dispatcher
A request dispatcher is an object of the javax.servlet.RequestDispatcher interface that allows
inter-servlet communication.
The ServletContext interface provides the getRequestDispatcher(String path) method that
returns the RequestDispatcher object. With the object, we can perform the following two
functions:
∑ Include contents of another servlet
∑ Forward request to another servlet
Including contents of another servlet

RequestDispatcher dispatch= getServletContext() .


getRequestDispatcher(“/servlet/CopyServlet”);
dispatch.include(request,response);

Forwarding requests to other servlets


RequestDispatcher dispatch= getServletContext() .
getRequestDispatcher(“/servlet/CopyServlet”);

IPSR Solutions Ltd www.ipsr.edu.in 23


JAVA

dispatch.forward(request,response);

SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to
another resource, it may be servlet, jsp or html file. It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make another request. So, it
can work inside and outside the server.

Difference between forward() and sendRedirect() method


forward() sendRedirect()
The forward() method works at server side. The sendRedirect() method works at client
side.
It sends the same request and response It always sends a new request.
objects to another servlet.
It can work within the server only. It can be used within and outside
the server.
We can use request dispatcher only when Send Redirect can be used in both the
the other servlet to which the request is cases if the two servlets resides in a same
being forwarded lies in the same application or in different applications.
application.

IPSR Solutions Ltd www.ipsr.edu.in 24


JAVA

Servlet Filter
A filter is an object that is invoked at the preprocessing and postprocessing of a request. It is
mainly used to perform filtering tasks such as conversion, logging, compression, encryption and
decryption, input validation etc. The servlet filter is pluggable, i.e. its entry is defined in the
web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet. So maintenance cost will be less.
Usage of Filter
∑ records all incoming requests
∑ logs the IP addresses of the computers from which the requests originate
∑ conversion
∑ data compression
∑ encryption and decryption
∑ input validation etc.

Filter API
Filter has its own API. The javax.servlet package contains the three interfaces of Filter API –
Filter, FilterChain, FilterConfig
Filter Interface
For creating any filter, you must implement the Filter interface. Filter interface provides the life
cycle methods for a filter.
Method Description

public void init(FilterConfig init() method is invoked only once. It is used to


config) initialize the filter.
public void doFilter() method is invoked every time when user
doFilter(HttpServletRequest request to any resource, to which the filter is mapped.
request,HttpServletResponse It is used to perform filtering tasks.
response, FilterChain chain)

IPSR Solutions Ltd www.ipsr.edu.in 25


JAVA

public void destroy() This is invoked only once when filter is taken out of
the service.

FilterChain interface
The object of FilterChain is responsible to invoke the next filter or resource in the chain. This
object is passed in the doFilter method of Filter interface. The FilterChain interface contains
only one method:

public void doFilter(HttpServletRequest request, HttpServletResponse response): it passes


the control to the next filter or resource.
FilterConfig interface
An object of FilterConfig is created by the web container. This object can be used to get the
configuration information from the web.xml file.
Method Description

public void init(FilterConfig init() method is invoked only once. It is used to


config) initialize the filter.
public String Returns the parameter value for the specified
getInitParameter(String parameter name
parameterName)
Public java.util.Enumeration Returns an enumeration containing all the parameter
getInitParameterNames() names.
public ServletContext Returns the ServletContext object.
getServletContext()

Example of authenticating user using filter


index.html

IPSR Solutions Ltd www.ipsr.edu.in 26


JAVA

MyFilter.java

AdminServlet.java

IPSR Solutions Ltd www.ipsr.edu.in 27


JAVA

web.xml

IPSR Solutions Ltd www.ipsr.edu.in 28

You might also like