0% found this document useful (0 votes)
15 views23 pages

UNIT-3-Java Servlet Programming-AJP-6TH-SEM-SUMMER-2024

The document discusses Java servlet programming. It defines servlets and lists their advantages. It describes the different types of servlets and their lifecycle. It also compares servlets with CGI and explains the ServletConfig interface.

Uploaded by

mark.co0411
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views23 pages

UNIT-3-Java Servlet Programming-AJP-6TH-SEM-SUMMER-2024

The document discusses Java servlet programming. It defines servlets and lists their advantages. It describes the different types of servlets and their lifecycle. It also compares servlets with CGI and explains the ServletConfig interface.

Uploaded by

mark.co0411
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

BHAGWAN MAHAVIR UNIVERSITY

FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Unit-3: Java Servlet Programming

Que:1: What is Servlet? Write the advantages of Servlet.


o Servlet is a technology which is used to create a web application.
o Servlet technology is robust and scalable.
o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web
page.
o Servlets are built from two packages:

 Javax.servlet
 Javax.servlet.http

Advantages of Servlet:

1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
4. Secure: because it uses java language.
5. Servlet is faster than CGI as it doesn’t involve the creation of a new process for every
new request received.
6. Servlets, as written in Java, are platform independent.

Advanced Java Programming – Theory (1010206604) Page 1 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Que:2: List out the types of servlet?


There are two types of servlet
 Generic Servlet
 javax.servlet (package)
 extends javax.servlet.Servlet
 service method
 service(ServletRequest req, ServletResponse res)
 Http Servlet
 javax.servlet.http (package)
 extends javax.servlet.HttpServlet
 doGet(), doPost()
 doGet(HttpServletRequest req,HttpServletResponse res)
 doPost(HttpServletRequest req,HttpServletResponse res)

Que:3: Give the Difference between Servlet and CGI.

Servlet CGI (Common Gateway Interface)

Servlets are portable and efficient. CGI is not portable.

In Servlets, sharing data is possible. In CGI, sharing data is not possible.

Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.

Servlets are less expensive than CGI. CGI is more expensive than Servlets.

Servlets can handle the cookies. CGI cannot handle the cookies.

Advanced Java Programming – Theory (1010206604) Page 2 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Que:4: Explain Servlet Life cycle.


There are Five stages of Servlet Life Cycle

1. Servlet class is loaded


2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked

1. Servlet class is loaded:


 The classloader is responsible to load the servlet class.
 The servlet class is loaded when the first request for the servlet is received by the web
container.

Advanced Java Programming – Theory (1010206604) Page 3 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

2. Servlet instance is created:


 The web container creates the instance of a servlet after loading the servlet class.
 The servlet instance is created only once in the servlet life cycle.
3. Init method is invoked:
 The web container calls the init method only once after creating the servlet instance.
 The init method is used to initialize the servlet.
 It is the life cycle method of the javax.servlet.Servlet interface.
 Syntax of the init method is given below:
 public void init(ServletConfig config) throws ServletException
4. Service method is invoked:
 The web container calls the service method each time when request for the servlet is
received.
 If servlet is not initialized, it follows the first three steps as described above then calls
the service method.
 If servlet is initialized, it calls the service method.
 Notice that servlet is initialized only once.
 The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
 The doGet() and doPost() are most frequently used methods with in each service
request.
 The syntax of the service method of the Servlet interface is given below:
 public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
5. Destroy method is invoked:
 The web container calls the destroy method before removing the servlet instance from
the service.
 It gives the servlet an opportunity to clean up any resource for example memory,
thread etc.
 The syntax of the destroy method of the Servlet interface is given below:
 public void destroy()

Advanced Java Programming – Theory (1010206604) Page 4 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Que:5: Difference between GenericServlet and HttpServlet.

GenericServlet HttpServlet

javax.servlet.GenericServlet javax.servlet.http.HttpServlet

It defines a generic, protocol-independent It defines a HTTP protocol specific servlet.


servlet.

GenericServlet is a super class of HttpServlet is a sub class of GenericServlet


HttpServlet class. class.

Can handle all types of protocols only HTTP specific protocols.

It supports only one abstract It support doGet(), doPost() etc.


method:service()

Que:6: Explain ServletConfig interface in Servlet with example.


 javax.servlet.ServletConfig is an interface as a part of servlet API.
 For every Servlet class in our application, the web container will create one
ServletConfig object and the web container will pass this object as an argument to
the public void init(ServletConfig config) method of our Servlet class object.
 ServletContext is created by the web container at time of deploying the project.
 It can be used to get configuration information from web.xml file.
 There is only one ServletContext object per web application.
 If any information is shared to many servlet, it is better to provide it from the web.xml
file using the <context-param> element.
 There are four methods of ServletConfig interface listed in a given table.

Advanced Java Programming – Theory (1010206604) Page 5 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Method name Description

public abstract java.lang.String we use the method getServletName()


getServletName() it will return the logical name of
Servlet

This method will simply return


public abstract javax.servlet.ServletContext
ServletContext Object. Web
getServletContext()
container creates one ServletContext
object for every web application.

public abstract java.lang.String By using getInitParameter() we can


getInitParameter(java.lang.String) access the value of init parameters in
our Servlet.

public abstract
This method will return
java.util.Enumeration<java.lang.String>
Enumeration having names of all
getInitParameterNames()
init parameter names.

Example:
File: Web.xml
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
<init-param>
<param-name>name</param-name>
<param-value>Trupti</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>

Advanced Java Programming – Theory (1010206604) Page 6 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

</servlet-mapping>
</web-app>
File: MyServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet
{ String msg;
PrintWriter out;
public void init(ServletConfig config)throws ServletException
{
msg = config.getInitParameter("name");
}
public void doGet(HttpServletRequest request , HttpServletResponse response) throws
ServletException,IOException
{ response.setContentType("text/html");
out = response.getWriter();
out.println("<h1>"+ msg +"</h1>");
}
public void destroy()
{ out.close();
}
}

Que:7: Explain ServletContext interface with example.


 ServletContext is created by the web container at time of deploying the project.
 It can be used to get configuration information from web.xml file.
 There is only one ServletContext object per web application.
 If any information is shared to many servlet, it is better to provide it from the web.xml file
using the <context-param> element.
 Example:
 File:Web.xml:
<?xml version="1.0" encoding="UTF-8"?>

Advanced Java Programming – Theory (1010206604) Page 7 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

<web-app>
<servlet>
<servlet-name>ServletContextDemo</servlet-name>
<servlet-class>ServletContextDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletContextDemo</servlet-name>
<url-pattern>/ServletContextDemo</url-pattern>
</servlet-mapping>
<context-param>
<param-name>name</param-name>
<param-value>DIET</param-value>
</context-param>
</web-app>
File:MyServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletContextDemo extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{ res.setContentType("text/html");
PrintWriter out=res.getWriter();
//creating ServletContext object
ServletContext context=getServletContext();
//Getting the value of the initialization parameter and printing it
String college=context.getInitParameter("name");
out.println("College name is="+college);
out.close();
}
}

Advanced Java Programming – Theory (1010206604) Page 8 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Que:8: Difference between SetvletConfig and ServletContext interface.

ServletConfig ServletContext

ServletConfig is servlet specific ServletContext is for whole application

Parameters of servletConfig are Parameters of servletContext are present as


present as name-value pair in <init- name-value pair in <context-param> which is
param> inside <servlet>. outside of <servlet> and inside <web-app>

ServletConfig object is obtained by ServletContext object is obtained by


getServletConfig() method. getServletContext() method.

Each servlet has got its own ServletContext object is only one and used by
ServletConfig object. different servlets of the application.

Use ServletConfig when only one


Use ServletContext when whole application
servlet needs information shared by
needs information shared by it
it.

Que:9: Difference between doGet() and doPost() in servlet.

Get method Post method

Get Request sends the request parameter as query Post request send the request parameters as
string appended at the end of the request. part of the http request body.

Get method is visible to every one (It will be Post method variables are not displayed in
displayed in the address bar of browser ). the URL.

Restriction on form data, only ASCII characters No Restriction on form data, Binary data is
allowed. also allowed.

Advanced Java Programming – Theory (1010206604) Page 9 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Get methods have maximum size is 2000


Post methods have maximum size is 8 mb.
character.

Restriction on form length, So URL length is


No restriction on form data.
restricted

Remain in browser history. Never remain the browser history.

doGet() is faster comparatively doPost() is slower compared to doGet()


since doPost() does not write the content
length

Que:10: Explain HttpRequest Method with example.

HttpRequest Methods Description

String getContextPath() Returns the portion of the request URI that indicates the
context of the request.

Enumeration Returns an enumeration of all the header names this request


getHeaderNames() contains.

String Returns the value of the specified request header as


getHeader(String name) a String.

Returns the query string that is contained in the request


String getQueryString()
URL after the path.

Returns the part of this request's URL that calls the servlet.
String getServletPath()
This path starts with a "/" character and includes either the
servlet name or a path to the servlet.

String getMethod() Returns the name of the HTTP method with which this
request was made, for example GET or POST.

Advanced Java Programming – Theory (1010206604) Page 10 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

(1) String getContextPath():

Returns the portion of the request URI that indicates the context of the request.
Example:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
out.println("<p>request.getContextPath():"+request.getContextPath()+"</p>");
}

(2) Enumeration getHeaderNames()


Returns an enumeration of all the header names this request contains.
Example:
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
Enumeration h=request.getHeaderNames();
while(h.hasMoreElements())
{
String paramName = (String)h.nextElement();
out.print("<p>" + paramName + "\t");
String paramValue = request.getHeader(paramName);
out.println( paramValue + "</p>\n");
}
}
(3) String getHeader(String name)
Returns the value of the specified request header as a String.
Example:
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
out.println("<p>request.getHeader(): " +request.getHeader("host")+"</p>");
out.println("<p>request.getHeader(): " +request.getHeader("referer")+"</p>");
}

Advanced Java Programming – Theory (1010206604) Page 11 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

(4) String getQueryString()


Returns the query string that is contained in the request URL after the path.
Example:
public void doGet(HttpServletRequest request,HttpServletResponse response)
{
out.println("<p>request.getQueryString():" +request.getQueryString()+"</p>");
}

(5) String getServletPath()


Returns the part of this request's URL that calls the servlet. This path starts with a "/"
character and includes either the servlet name or a path to the servlet.
Example:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
out.println("<p>request.getServletPath():" +request.getServletPath()+"</p>");
}
(6) String getMethod()
Returns the name of the HTTP method with which this request was made, for example
GET or POST.
Example:
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
out.println("<p>request.getMethod():"+request.getMethod()+"</p>");
}

Advanced Java Programming – Theory (1010206604) Page 12 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Que:11: What is Session Managemnet/Session Tracking Techniques in


Servlet?
 Session Management is a mechanism
 It is used by the Web container
 It stores session information for a particular user
 There are four different techniques for session management

(1) Hidden Form Field in Session Managemnet:


 hidden / invisible textfield is used for maintaining the state of an user

 store the information in the hidden field

 and get it from another servlet

 Example: we store page id or page name in the hidden field so that each
page can be uniquely identified
Advantages:
 Easy to implement
 It will always work whether cookie is disabled or not
Disadvantages:
 Maintained at server side
 Extra form submission is required on each pages
 Only textual information can be used
 It does not support hyperlink submission
 Hidden field will be visible with GET method
 User might view page source and can view hidden field

Advanced Java Programming – Theory (1010206604) Page 13 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Example:
Login.html
<html>
<head>
<title>login</title>
</head>
<body>
<form action="/Session/Valid" method="POST">
<p>Login ID:<input type="text" name="login"></p>
<p>Password:<input type="text" name="pwd"></p>
<p><input type="hidden" name="session_id" value="054"> </p>
<p><input type="submit" value="Sign In"></p>
</form>
</body>
</html>
Valid.java
public class Valid extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
RequestDispatcher rd;
String login=request.getParameter("login");
String pwd=request.getParameter("pwd");
String session=request.getParameter("session_id");
if(login.equals("java") && pwd.equals("servlet"))
{
rd=request.getRequestDispatcher("Welcome");
rd.forward(request, response);
}

Advanced Java Programming – Theory (1010206604) Page 14 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

else
{
out.println("<p><h1>Incorrect LoginId/Password </h1></p>");
rd=request.getRequestDispatcher("/login.html");
rd.include(request, response);
}
}
}
(2) URL Rewriting in Session Managemnet
• In URL rewriting, a token or identifier is appended to the URL of the next Servlet or the
next resource.
• We can send parameter name/value pairs using the following format:
URL ? Name1 = value1 & name2 = value2 &…
o A name and a value is separated using an equal (=) sign
o name/value pair is separated from another parameter using the ampersand(&)
• When the user clicks the hyperlink, the parameter name/value pairs will be passed to the
server.
• From a Servlet, we can use getParameter() method to obtain a parameter value.
Advantage:
• It will always work whether cookie is disabled or not (browser independent).
• Extra form submission is not required on each pages.
Disadvantage:
• It will work only with links.
• It can send only textual information.
• URL header size constraint.
• Not Securite because name/value field will be visible with URL followed by ‘?’.
Example:
Form1.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Form1 extends HttpServlet
{

Advanced Java Programming – Theory (1010206604) Page 15 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

public void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException
{
String url;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
//for URL rewriting
url= "http://localhost:8080/Session/Form2?s_id1=054&s_id2=055";
out.println("<a href="+url+">next page</a>");
}
}
Form2.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Form2 extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String session1=request.getParameter("s_id1");
String session2=request.getParameter("s_id2");
out.println("<h3>"+"id:"+session1+"</h3>");
out.println("<h3>"+"id:"+session2+"</h3>");
}
}

Advanced Java Programming – Theory (1010206604) Page 16 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

(3) Cookies in Session Management


 A cookie is a small piece of information that is persisted between the multiple client
requests.
 A cookie has a
o Name
o Single value
 There are two types of cookies
o Persistent cookies and
 It is valid for multiple session .
 It is not removed each time when user closes the browser.
 It is removed only if user logout or signout.

o Non-Persistent cookie
 It is valid for single session only.
 It is removed each time when user closes the browser.
• Cookie class
javax.servlet.http.Cookie
o This class provides the functionality of using cookies.
o It provides a lots of useful methods for cookies.
• Constructor
Cookie(String name, String value)
o constructs a cookie with a specified name and value.
• Coookie Example
Cookie c= new Cookie("id","054");

Advanced Java Programming – Theory (1010206604) Page 17 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Methods of Cookies
Cookie Methods Description

void setMaxAge(int expiry) Sets the maximum age in seconds for this Cookie

Gets the maximum age in seconds of this Cookie.


int getMaxAge() By default, -1 is returned, which indicates that the cookie
will persist until browser shutdown.

Returns the name of the cookie. The name cannot be


String getName()
changed after creation.

void setValue(String
Assigns a new value to this Cookie.
newValue)

String getValue() Gets the current value of this Cookie.

void addCookie(Cookie Method of HttpServletResponse interface is used to add


cookie) cookie in response object.

Returns an array containing all of the Cookie objects the


Cookie[] getCookies() client sent with this request. This method returns null if
no cookies were sent.

 How to create Cookie


Example:
//creating cookie object
Cookie c= new Cookie("id","054");
//adding cookie in the response
response.addCookie(c);

Advanced Java Programming – Theory (1010206604) Page 18 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

 How to retrieve Cookie


Example:
Cookie c[]=request.getCookies();
for(int i=0;i<c.length;i++)
{
//printing name&value of cookie
out.print(c[i].getName()+””+c[i].getValue());
}
 How to delete Cookie
Set cookie age as zero using setMaxAge() method to delete an existing cookie
Example:
//deleting value of cookie
Cookie c = new Cookie("user","");
//changing the maximum age to 0 seconds
c.setMaxAge(0);
//adding cookie in the response
response.addCookie(c);

 Advantages of Cookie
o It is a simplest technique of maintaining the state.
o Cookies are maintained at client side.

 Disadvantages of Cookie
o It will not work if cookie is disabled from the browser.
o Only textual information can be set in Cookie object.

Advanced Java Programming – Theory (1010206604) Page 19 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

(4) HttpSession in Session Management


 Package: javax.servlet.http.HttpSession
 The servlet container uses this interface to create a session between an HTTP client and
an HTTP server.
 In this technique create a session object at server side for each client.
 Session is available until the session time out, until the client log out.
 The default session time is 30 minutes and can configure explicit session time in web.xml
file.
 The HttpServletRequest interface provides two methods to get the object of HttpSession
 Methods of HttpSession

HttpSession Methods Description

Returns the current session associated with this request, or if


HttpSession getSession()
the request does not have a session, creates one.

HttpSession Returns the current HttpSession associated with this request


getSession(boolean or, if there is no current session and create is true then it will
create) returns a new session.

String getId() Returns a string containing the unique identifier value.

Returns the time when this session was created, measured in


long getCreationTime()
milliseconds.

long Returns the last time the client sent a request associated with
getLastAccessedTime() this session, as the number of milliseconds.

void invalidate() Invalidates this session then unbinds any objects bound to it.

Advanced Java Programming – Theory (1010206604) Page 20 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

 How to create Session


Example:
HttpSession hs=request.getSession();
hs.setAttribute("s_id", "054");
 How to retrieve Session
Example:
HttpSession hs=request.getSession(false);
String n=(String)hs.getAttribute("s_id");
 How to invalid a Session
Example:
hs.invalidate();
 How to Session Timeout
• The session timeout in a web application can be configured in two ways
o Timeout in the deployment descriptor (web.xml)
Example
<web-app>
<session-config>
<session-timeout> 10 </session-timeout>
</session-config>
</web-app>
Here time specified in minute
o Timeout with setMaxInactiveInterval()
Example:
HttpSession session = request.getSession();
session.setMaxInactiveInterval(10*60);
Here time specified in second

Advanced Java Programming – Theory (1010206604) Page 21 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Que:12: What is Filter in Servlet?


• Filter is used for pre-processing of requests and post-processing of responses.
• Filters are configured in the deployment descriptor of a web application.
• Uses of Filter
o Recording all incoming requests
o Logs the IP addresses of the computers from which the requests originate
o Conversion
o Data compression
o Encryption and Decryption
o Input validation etc.
• The javax.servlet package contains the three interfaces of Filter API.
o Filter
o FilterChain
o FilterConfig
• Advantage of Filter
o Filter is pluggable.
o One filter don't have dependency onto another resource.
o Less Maintenance Cost
o 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.
o So maintenance cost will be less.

Advanced Java Programming – Theory (1010206604) Page 22 of 23


BHAGWAN MAHAVIR UNIVERSITY
FACULTY OF ENGINEERING
COMPUTER/IT ENGINEERING DEPARTMENT
6TH SEM
READING MATERIAL

Que:13: Explain Filter interface in Servlet.


• For creating any filter, you must implement the Filter interface.
• Filter interface provides the life cycle methods for a filter.
• Methods of Filter interface

Filter Methods Description

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


void init(FilterConfig config)
initialize the filter.

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

This is invoked only once when filter is taken out


void destroy()
of the service.

Que:14:Explain FilterChain Interface with Example.


• 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:

FilterChain Methods Description

void doFilter
It passes the control to the next filter
(HttpServletRequest request,
or resource.
HttpServletResponse response)

 Example:
FilterChain chain;
chain.doFilter(req, resp);//send request to next resource

Advanced Java Programming – Theory (1010206604) Page 23 of 23

You might also like