Servlet Interview Questions

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 48

SERVLETS

==================================================================

1).What is different between web server and application server?

A web server responsibility is to handler HTTP requests from client browsers and respond with
HTML response. A web server understands HTTP language and runs on HTTP protocol.
Apache Web Server is kind of a web server and then we have specific containers that can
execute servlets and JSPs known as servlet container, for example Tomcat.
Application Servers provide additional features such as Enterprise JavaBeans support, JMS
Messaging support, Transaction Management etc. So we can say that Application server is a web
server with additional functionalities to help developers with enterprise applications.

2).Which HTTP method is non-idempotent?

A HTTP method is said to be idempotent if it returns the same result every time. HTTP methods
GET, PUT, DELETE, HEAD, and OPTIONS are idempotent method and we should implement
our application to make sure these methods always return same result. HTTP method POST is
non-idempotent method and we should use post method when implementing something that
changes with every request.

For example, to access an HTML page or image, we should use GET because it will always
return the same object but if we have to save customer information to database, we should use
POST method. Idempotent methods are also known as safe methods and we don’t care about the
repetitive request from the client for safe methods.

3).What is the difference between GET and POST method?

 GET is a safe method (idempotent) where POST is non-idempotent method.


 We can send limited data with GET method and it’s sent in the header request URL
whereas we can send large amount of data with POST because it’s part of the body.
 GET method is not secure because data is exposed in the URL and we can easily
bookmark it and send similar request again, POST is secure because data is sent in request
body and we can’t bookmark it.
 GET is the default HTTP method whereas we need to specify method as POST to send
request with POST method.
 Hyperlinks in a page uses GET method.
4)What is MIME Type?

The “Content-Type” response header is known as MIME Type. Server sends MIME type to
client to let them know the kind of data it’s sending. It helps client in rendering the data for user.
Some of the mostly used mime types are text/html, text/xml, application/xml etc.

We can use ServletContext getMimeType() method to get the correct MIME type of the file and
use it to set the response content type. It’s very useful in downloading file through servlet from
server.

5).What is a web application and what is it’s directory structure?

Web Applications are modules that run on server to provide both static and dynamic content to
the client browser. Apache web server supports PHP and we can create web application using
PHP. Java provides web application support through Servlets and JSPs that can run in a servlet
container and provide dynamic content to client browser.

Java Web Applications are packaged as Web Archive (WAR) and it has a defined structure like
below image.

6).What is a servlet?

Java Servlet is server side technologies to extend the capability of web servers by providing
support for dynamic response and data persistence.

The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing our
own servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle
methods. When implementing a generic service, we can extend the GenericServlet class provided
with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and
doPost(), for handling HTTP-specific services.
Most of the times, web applications are accessed using HTTP protocol and thats why we mostly
extend HttpServlet class. Servlet API hierarchy is shown in below image.

7).What are the advantages of Servlet over CGI?

Servlet technology was introduced to overcome the shortcomings of CGI technology.

 Servlets provide better performance that CGI in terms of processing time, memory
utilization because servlets uses benefits of multithreading and for each request a new
thread is created, that is faster than loading creating new Object for each request with CGI.
 Servlets and platform and system independent, the web application developed with Servlet
can be run on any standard web container such as Tomcat, JBoss, Glassfish servers and on
operating systems such as Windows, Linux, Unix, Solaris, Mac etc.
 Servlets are robust because container takes care of life cycle of servlet and we don’t need
to worry about memory leaks, security, garbage collection etc.
 Servlets are maintainable and learning curve is small because all we need to take care is
business logic for our application.

8).What are common tasks performed by Servlet Container?

Servlet containers are also known as web container, for example Tomcat. Some of the
important tasks of servlet container are:

 Communication Support: Servlet Container provides easy way of communication


between web client (Browsers) and the servlets and JSPs. Because of container, we
don’t need to build a server socket to listen for any request from web client, parse
the request and generate response. All these important and complex tasks are done
by container and all we need to focus is on business logic for the applications.
 Lifecycle and Resource Management: Servlet Container takes care of managing
the life cycle of servlet. From the loading of servlets into memory, initializing
servlets, invoking servlet methods and to destroy them. Container also provides
utility like JNDI for resource pooling and management.
 Multithreading Support: Container creates new thread for every request to the
servlet and provide them request and response objects to process. So servlets are not
initialized for each request and saves time and memory.
 JSP Support: JSPs doesn’t look like normal java classes but every JSP in the
application is compiled by container and converted to Servlet and then container
manages them like other servlets.
 Miscellaneous Task: Servlet container manages the resource pool, perform memory
optimizations, execute garbage collector, provides security configurations, support
for multiple applications, hot deployment and several other tasks behind the scene
that makes a developer life easier.
9).What is ServletConfig object?

javax.servlet.ServletConfig is used to pass configuration information to Servlet. Every


servlet has it’s own ServletConfig object and servlet container is responsible for
instantiating this object. We can provide servlet init parameters in web.xml file or through
use of WebInitParam annotation. We can use getServletConfig() method to get the
ServletConfig object of the servlet.

10).What is ServletContext object?

javax.servlet.ServletContext interface provides access to web application parameters to the


servlet. The ServletContext is unique object and available to all the servlets in the web
application. When we want some init parameters to be available to multiple or all of the
servlets in the web application, we can use ServletContext object and define parameters in
web.xml using <context-param> element. We can get the ServletContext object via
the getServletContext() method of ServletConfig. Servlet containers may also provide
context objects that are unique to a group of servlets and which is tied to a specific portion
of the URL path namespace of the host.

ServletContext is enhanced in Servlet Specs 3 to introduce methods through which we can


programmatically add Listeners and Filters and Servlet to the application. It also provides
some utility methods such as getMimeType(), getResourceAsStream() etc.

11).What is difference between ServletConfig and ServletContext?

Some of the differences between ServletConfig and ServletContext are:

 ServletConfig is a unique object per servlet whereas ServletContext is a unique


object for complete application.
 ServletConfig is used to provide init parameters to the servlet whereas
ServletContext is used to provide application level init parameters that all other
servlets can use.
 We can’t set attributes in ServletConfig object whereas we can set attributes in
ServletContext that other servlets can use in their implementation.

12).What is Request Dispatcher?

RequestDispatcher interface is used to forward the request to another resource that can be
HTML, JSP or another servlet in same application. We can also use this to include the
content of another resource to the response. This interface is used for inter-servlet
communication in the same context.

There are two methods defined in this interface:

1.void forward(ServletRequest request, ServletResponse response) – forwards the


request from a servlet to another resource (servlet, JSP file, or HTML file) on the
server.

2.void include(ServletRequest request, ServletResponse response) – includes the


content of a resource (servlet, JSP page, HTML file) in the response.

We can get RequestDispatcher in a servlet using ServletContext


getRequestDispatcher(String path) method. The path must begin with a / and is
interpreted as relative to the current context root.

13).What is difference between PrintWriter and ServletOutputStream?

PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream


class. We can use PrintWriter to write character based information such as character array
and String to the response whereas we can use ServletOutputStream to write byte array
data to the response.

We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can
use ServletResponse getOutputStream() method to get the ServletOutputStream object
reference.

14)Can we get PrintWriter and ServletOutputStream both in a servlet?

We can’t get instances of both PrintWriter and ServletOutputStream in a single servlet method, if
we invoke both the methods; getWriter() and getOutputStream() on response; we will
get java.lang.IllegalStateException at runtime with message as other method has already been
called for this response.

15).How can we create deadlock situation in servlet?

We can create deadlock in servlet by making a loop of method invocation, just call doPost()
method from doGet() method and doGet() method to doPost() method to create deadlock
situation in servlet.

16).What is SingleThreadModel interface?

SingleThreadModel interface was provided for thread safety and it guarantees that no two
threads will execute concurrently in the servlet’s service method. However SingleThreadModel
does not solve all thread safety issues. For example, session attributes and static variables can
still be accessed by multiple requests on multiple threads at the same time, even when
SingleThreadModel servlets are used. Also it takes out all the benefits of multithreading support
of servlets, thats why this interface is Deprecated in Servlet 2.4.

17).Do we need to override service() method?

When servlet container receives client request, it invokes the service() method which in
turn invokes the doGet(), doPost() methods based on the HTTP method of request. I don’t
see any use case where we would like to override service() method. The whole purpose of
service() method is to forward to request to corresponding HTTP method implementations.
If we have to do some pre-processing of request, we can always use servlet filters and
listeners.

18) Is it good idea to create servlet constructor?

We can define a constructor for servlet but I don’t think its of any use because we won’t be
having access to the ServletConfig object until unless servlet is initialized by container.
Ideally if we have to initialize any resource for servlet, we should override init() method
where we can access servlet init parameters using ServletConfig object.

19) What is difference between GenericServlet and HttpServlet?

GenericServlet is protocol independent implementation of Servlet interface whereas


HttpServlet is HTTP protocol specific implementation. Most of the times we use servlet
for creating web application and that’s why we extend HttpServlet class. HttpServlet class
extends GenericServlet and also provide some other methods specific to HTTP protocol.

20)What is the inter-servlet communication?

When we want to invoke another servlet from a servlet service methods, we use inter-
servlet communication mechanisms. We can invoke another servlet using
RequestDispatcher forward() and include() methods and provide additional attributes in
request for other servlet use.

21) Are Servlets Thread Safe? How to achieve thread safety in servlets?

HttpServlet init() method and destroy() method are called only once in servlet life cycle, so we
don’t need to worry about their synchronization. But service methods such as doGet() or
doPost() are getting called in every client request and since servlet uses multithreading, we
should provide thread safety in these methods.

If there are any local variables in service methods, we don’t need to worry about their thread
safety because they are specific to each thread but if we have a shared resource then we can use
synchronization to achieve thread safety in servlets when working with shared resources.

22) What is servlet attributes and their scope?

Servlet attributes are used for inter-servlet communication, we can set, get and remove attributes
in web application. There are three scopes for servlet attributes – request scope, session scope
and application scope.

ServletRequest, HttpSession and ServletContext interfaces provide methods to get/set/remove


attributes from request, session and application scope respectively.

Servlet attributes are different from init parameters defined in web.xml for ServletConfig or
ServletContext.

23) How do we call one servlet from another servlet?

We can use RequestDispatcher forward() method to forward the processing of a request to


another servlet. If we want to include the another servlet output to the response, we can use
RequestDispatcher include() method.

24) How can we invoke another servlet in a different application?

We can’t use RequestDispatcher to invoke servlet from another application because it’s specific
for the application. If we have to forward the request to a resource in another application, we can
use ServletResponse sendRedirect() method and provide complete URL of another servlet. This
sends the response to client with response code as 302 to forward the request to another URL. If
we have to send some data also, we can use cookies that will be part of the servlet response and
sent in the request to another servlet.

25)What is difference between ServletResponse sendRedirect() and RequestDispatcher


forward() method?

1. RequestDispatcher forward() is used to forward the same request to another resource


whereas ServletResponse sendRedirect() is a two step process. In sendRedirect(), web
application returns the response to client with status code 302 (redirect) with URL to send
the request. The request sent is a completely new request.
2. forward() is handled internally by the container whereas sednRedirect() is handled by
browser.
3. We should use forward() when accessing resources in the same application because it’s
faster than sendRedirect() method that required an extra network call.
4. In forward() browser is unaware of the actual processing resource and the URL in address
bar remains same whereas in sendRedirect() URL in address bar change to the forwarded
resource.
5. forward() can’t be used to invoke a servlet in another context, we can only use
sendRedirect() in this case.

26) Why HttpServlet class is declared abstract?

HttpServlet class provide HTTP protocol implementation of servlet but it’s left abstract because
there is no implementation logic in service methods such as doGet() and doPost() and we should
override at least one of the service methods. That’s why there is no point in having an instance of
HttpServlet and is declared abstract class.

27) What are the phases of servlet life cycle?

We know that Servlet Container manages the life cycle of Servlet, there are four phases of
servlet life cycle.

1. Servlet Class Loading – When container receives request for a servlet, it first loads the
class into memory and calls it’s default no-args constructor.
2. Servlet Class Initialization – Once the servlet class is loaded, container initializes the
ServletContext object for the servlet and then invoke it’s init method by passing servlet
config object. This is the place where a servlet class transforms from normal class to
servlet.
3. Request Handling – Once servlet is initialized, its ready to handle the client requests. For
every client request, servlet container spawns a new thread and invokes the service()
method by passing the request and response object reference.
4. Removal from Service – When container stops or we stop the application, servlet container
destroys the servlet class by invoking it’s destroy() method.

28) What are life cycle methods of a servlet?

Servlet Life Cycle consists of three methods:

1. public void init(ServletConfig config) – This method is used by container to initialize the
servlet, this method is invoked only once in the lifecycle of servlet.
2. public void service(ServletRequest request, ServletResponse response) – This method is
called once for every request, container can’t invoke service() method until unless init()
method is executed.
3. public void destroy() – This method is invoked once when servlet is unloaded from
memory.
29)What are life cycle methods of a servlet?

Servlet Life Cycle consists of three methods:

1. public void init(ServletConfig config) – This method is used by container to


initialize the servlet, this method is invoked only once in the lifecycle of servlet.
2. public void service(ServletRequest request, ServletResponse response) – This
method is called once for every request, container can’t invoke service() method
until unless init() method is executed.
3. public void destroy() – This method is invoked once when servlet is unloaded from
memory.

30) why we should override only no-agrs init() method.

If we have to initialize some resource before we want our servlet to process client requests,
we should override init() method. If we override init(ServletConfig config) method, then
the first statement should be super(config) to make sure superclass init(ServletConfig
config) method is invoked first. That’s why GenericServlet provides another helper init()
method without argument that get’s called at the end of init(ServletConfig config) method.
We should always utilize this method for overriding init() method to avoid any issues as
we may forget to add super() call in overriding init method with ServletConfig argument.

31) What are different methods of session management in servlets?

Session is a conversional state between client and server and it can consists of multiple request
and response between client and server. Since HTTP and Web Server both are stateless, the only
way to maintain a session is when some unique information about the session (session id) is
passed between server and client in every request and response.

Some of the common ways of session management in servlets are:

1. HTML Hidden Field


2. Cookies
3. URL Rewriting
4. Session Management

32).What is URL Rewriting?

We can use HttpSession for session management in servlets but it works with Cookies and we
can disable the cookie in client browser. Servlet API provides support for URL rewriting that we
can use to manage session in this case.
The best part is that from coding point of view, it’s very easy to use and involves one step –
encoding the URL. Another good thing with Servlet URL Encoding is that it’s a fallback
approach and it kicks in only if browser cookies are disabled.

We can encode URL with HttpServletResponse encodeURL() method and if we have to redirect
the request to another resource and we want to provide session information, we can use
encodeRedirectURL() method.

Index.html

<form action="servlet1">

Name:<input type="text" name="userName"/><br/>

<input type="submit" value="go"/>

</form>

FirstServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
//appending the username in the query string
out.print("<a href='servlet2?uname="+n+"'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);} } }
SecondServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//getting value from the query string
String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
Web.xml
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
33) How does Cookies work in Servlets?

Cookies are used a lot in web client-server communication, it’s not something specific to java.
Cookies are text data sent by server to the client and it gets saved at the client local machine.

Servlet API provides cookies support through javax.servlet.http.Cookie class that implements
Serializable and Cloneable interfaces.

HttpServletRequest getCookies() method is provided to get the array of Cookies from request,
since there is no point of adding Cookie to request, there are no methods to set or add cookie to
request.

Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in


response header, there are no getter methods for cookie.

Index.html

<form action="servlet1" method="post">


Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}

SecondServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}

Web.xml

<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>
34) Hidden Form Filed in servlets?
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of
an user.
n such case, we store the information in the hidden field and get it from another servlet. This
approach is better if we have to submit form in all the pages and we don't want to depend on the
browser.
Let's see the code to store value in hidden field
<input type="hidden" name="uname" value="rajkumar">
It is widely used in comment form of a website. In such case, we store page id or page name in
the hidden field so that each page can be uniquely identified.
Advantage:
It will always work whether cookie is disabled or not.
Disadvantage:
It is maintained at server side.Extra form submission is required on each pages.Only textual
information can be used.

Index.html

<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
//creating form that have invisible textfield
out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}

SecondServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
} }

web.xml
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

35) When Servlet is unloaded?

A servlet is unloaded when:

 Server shuts down


 Administrator manually unloads

36) What are the supporting protocol by HttpServlet ?

HttpServlet supports only HTTP and HTTPS protocol.

37) What is called Session Tracking?

Session tracking is used to maintain a state on the series of requests from the same user for a
given period of time.
38) Why session tracking is needed?

Every HTTP request needs to be captured by HTTP protocol and for that, state is captured.
Tracking of state is called session tracking.

39) What are the types of Session Tracking ?

There are following types of session tracking:

 URL rewriting
 Hidden Form Fields
 Cookies
 Secure Socket Layer (SSL)

40) What are the advantages of cookies?

Cookies are used to store long term information that can be maintained without server
interaction. Small and Medium size data are kept in a queue.

41) What is URL rewriting?

URL rewriting is one of the methods of session tracking in which additional data is appended at
the end of each URL. This additional data identifies the session.

42) What is servlet lazy loading?

A servlet container which does not initialize at the start up, this is known as servlet lazy loading.

43) What is Servlet Chaining?

Chaining is one of the methods where out of one servlet is given to the second servlet. This
chaining can happen for any number of servlets.

44) What are the important functions of filters?

Following are the important functions of Filters:

 Security check
 Modifying the request or response
 Data compression
 Logging and auditing
 Response compression

45) What are the functions of Servlet container?

Following are the functions of the Servlet container:

 Lifecycle management
 Communication support
 Multithreading support
 Declarative security
 JSP support

46) What is the difference between JSP and Servlets ?

JSP supports HTTP protocol which mainly used for presentation. But a servlet can support any
protocol like HTTP, FTP, SMTP etc.

47) What is the difference between Server and Container?

A server can provide service to the client and it contains one or more containers such as EJBs,
Servlet, JSP containers. Containers hold set of objects.

48) Can we refresh servlet in client and server side automatically?

On the client side, Meta http is used for refresh and server push is used for server side refresh.

49) What is the difference between ServletConfig and ServletContext?

ServletConfig provides information about configuration of a servlet which is defined inside the
web.xml file and it is a specific object for each servlet.

ServletContext is an application specific object and it is shared by all servlet. It belongs to one
application in one JVM

50) Difference between forward() method and sendRedirect() method ?

forward() method sendRedirect() method

1) forward() sends the same request to 1) sendRedirect() method sends new request always bec
another resource. bar of the browser.

2) forward() method works at server side. 2) sendRedirect() method works at client side.

3) forward() method works within the server 3) sendRedirect() method works within and outside the s
only.
51) What are the annotations used in Servlet 3?

There are mainly 3 annotations used for the servlet.

1. @WebServlet : for servlet class.


2. @WebListener : for listener class.
3. @WebFilter : for filter class.

52). What is the difference between Servlet Request and Servlet Context when calling a
Request Dispatcher?

Relative URL can be called when Servlet Request is used and Relative URL is not used when
using Servlet Context.
53). What are the features added in Servlet 2.5?

Following are the features added in Servlet 2.5:

 Dependency on J2SE 5.0


 Support for annotations
 Loading the class
 Several web.xml
 Removed restrictions
 Edge case clarifications

54) When servlet is loaded?

A servlet can be loaded when:

 First request is made


 Auto loading and Server starts up
 There is a single instance that answers all requests concurrently which saves memory
 Administrator manually loads.

55). When Servlet is unloaded?

A servlet is unloaded when:

 Server shuts down


 Administrator manually unloads

56). What are the important functions of filters?

Following are the important functions of Filters:

 Security check
 Modifying the request or response
 Data compression
 Logging and auditing
 Response compression

57). What are the functions of Servlet container?

Following are the functions of the Servlet container:

 Lifecycle management
 Communication support
 Multithreading support
 Declarative security
 JSP support

58). What is the difference between JSP and Servlets ?


JSP supports HTTP protocol which mainly used for presentation. But a servlet can support any
protocol like HTTP, FTP, SMTP etc.

59). What is the difference between ServletConfig and ServletContext?

ServletConfig provides information about configuration of a servlet which is defined inside the
web.xml file and it is a specific object for each servlet.

ServletContext is an application specific object and it is shared by all servlet. It belongs to one
application in one JVM

60). What are the different mode that servlets can be used?

Following are the modes that servlets can be used:

 Filter chains can be used to collect servlets together


 Support HTTP protocol
 Used for CGI based applications
 Dynamic generation of servlets

61) Why super.init (config) is the first statement inside init(config) method.

This will be the first statement if we are overriding the init(config) method by this way
we will store the config object for future reference and we can use by getServletConfig()
to get information about config object if will not do this config object will be lost and we
have only one way to get config object because servlet pass config object only in init
method . Without doing this if we call the ServletConfig method will
get NullPointerException.
62) Can we call destroy() method inside the init() method is yes what will happen?
Yes we can call like this but if we have not overridden this method container

will call the default method and nothing will happen.after calling this if any we

have overridden the method then the code written inside is executed.

63) How can you get the information about one servlet context in another servlet?
In context object we can set the attribute which we want on another servlet and

we can get that attribute using their name on another servlet.

Context.setAttribute (“name”,” value”)


Context.getAttribute (“name”)

64) Why we need to implement Single Thread model in the case of Servlet
Ans: In J2EE we can implement our servlet in two different ways either by using:
1. Single Thread Model
2. Multithread Model
Depending upon our scenario, if we have implemented single thread means only one
instance is going handle one request at a time no two thread will concurrently execute
service method of the servlet.
The example in banking accounts where sensitive data is handled mostly this scenario
was used this interface is deprecated in Servlet API version 2.4.

 As the name signifies multi-thread means a servlet is capable of handling multiple


requests at the same time. This servlet interview question was quite popular few years
back on entry level but now it's losing its shine.
65) What is servlet collaboration?
communication between two servlets is called servlet collaboration which is achieved by
3 ways.
1. RequestDispatchers include () and forward() method .
2. Using sendRedirect()method of Response object.
3. Using servlet Context methods

66) What is the difference between ServletConfig and ServletContext?


Ans: ServletConfig as the name implies provide the information about the configuration
of a servlet which is defined inside the web.xml file or we can say deployment
descriptor.its a specific object for each servlet.

ServletContext is an application specific object which is shared by all the servlet belongs
to one application in one JVM .this is a single object which represents our application and
all the servlet access application specific data using this object.servlet also use their
method to communicate with the container.

1. What is Filter ?

A filter is an object that is invoked at the pre-processing and post-processing 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.

Servlet Filters are Java classes that can be used in Servlet Programming for the following
purposes −

 To intercept requests from a client before they access a resource at back end.
 To manipulate responses from server before they are sent back to the client.
2. Types Of Filter.

There are various types of filters suggested by the specifications −

 Authentication Filters.
 Data compression Filters.
 Encryption Filters.
 Filters that trigger resource access events.
 Image Conversion Filters.
 Logging and Auditing Filters.
 MIME-TYPE Chain Filters.
 Tokenizing Filters .
 XSL/T Filters That Transform XML Content.

3. Usage of Filter

 recording all incoming requests


 logs the IP addresses of the computers from which the requests originate
 conversion
 data compression
 encryption and decryption
 input validation etc.

4. Advantage of Filter

1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance.

5. Filter API

Like Servlet filter have its own API. The javax.servlet package contains the three interfaces of
Filter API.

1. Filter
2. FilterChain
3. FilterConfig

1) Filter Interface

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

Method Description

(i) public void init(FilterConfig config) init() This method is invoked only once. It is used
to initialize the filter. Or This method is called by
the web container to indicate to a filter that it is
being placed into service.

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

This method is called by the web container to


indicate to a filter that it is being taken out of
(iii) public void destroy()
service. This is invoked only once when filter is
taken out of the service.

2) 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:

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


passes the control to the next filter or resource.

3) 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.

Methods of FilterConfig interface

There are following 4 methods in the FilterConfig interface.

1. public void init(FilterConfig config): init() method is invoked only once it is used to
initialize the filter.
2. public String getInitParameter(String parameterName): Returns the parameter value
for the specified parameter name.
3. public java.util.Enumeration getInitParameterNames(): Returns an enumeration
containing all the parameter names.
4. public ServletContext getServletContext(): Returns the ServletContext object.

Example of FilterConfig

In this example, if you change the param-value to no, request will be forwarded to the servlet
otherwise filter will create the response with the message: this page is underprocessing. Let's see
the simple example of FilterConfig. Here, we have created 4 files:
 index.html
 MyFilter.java
 HelloServlet.java
 web.xml

index.html

1. <a href="servlet1">click here</a>

MyFilter.java

1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.*;
5.
6. public class MyFilter implements Filter{
7. FilterConfig config;
8.
9. public void init(FilterConfig config) throws ServletException {
10. this.config=config;
11. }
12.
13. public void doFilter(ServletRequest req, ServletResponse resp,
14. FilterChain chain) throws IOException, ServletException {
15.
16. PrintWriter out=resp.getWriter();
17.
18. String s=config.getInitParameter("construction");
19.
20. if(s.equals("yes")){
21. out.print("This page is under construction");
22. }
23. else{
24. chain.doFilter(req, resp);//sends request to next resource
25. }
26.
27. }
28. public void destroy() {}
29. }

HelloServlet.java

1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.*;
5. public class HelloServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
8. response.setContentType("text/html");
9. PrintWriter out = response.getWriter();
10. out.print("<br>welcome to servlet<br>");
11.
12. }
13.
14. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>HelloServlet</servlet-name>
5. <servlet-class>HelloServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>HelloServlet</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <filter>
14. <filter-name>f1</filter-name>
15. <filter-class>MyFilter</filter-class>
16. <init-param>
17. <param-name>construction</param-name>
18. <param-value>no</param-value>
19. </init-param>
20. </filter>
21. <filter-mapping>
22. <filter-name>f1</filter-name>
23. <url-pattern>/servlet1</url-pattern>
24. </filter-mapping>
25.
26.
27. </web-app>

Following is the Servlet Filter Example that would print the clients IP address and current
date time.
Application 4 :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Implements Filter class


public class LogFilter implements Filter
{
public void init(FilterConfig config) throws ServletException {

// Get init parameter


String testParam = config.getInitParameter("test-param");

//Print the init parameter


System.out.println("Test Param: " + testParam);
}

public void doFilter(ServletRequest request, ServletResponse response,


FilterChain chain) throws java.io.IOException, ServletException {

// Get the IP address of client machine.


String ipAddress = request.getRemoteAddr();

// Log the IP address and current timestamp.


System.out.println("IP "+ ipAddress + ", Time " + new Date().toString());

// Pass request back down the filter chain


chain.doFilter(request,response);
}

public void destroy( ) {


/* Called before the Filter instance is removed from service by the web container*/
}
}

Compile LogFilter.java in usual way and put your class file in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes

Servlet Filter Mapping in Web.xml

Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet is
defined and then mapped to a URL pattern. Create the following entry for filter tag in the
deployment descriptor file web.xml

<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

The above filter would apply to all the servlets because we specified /* in our configuration. You
can specicy a particular servlet path if you want to apply filter on few servlets only.

Using Multiple Filters

Your web application may define several different filters with a specific purpose. Consider, you
define two filters AuthenFilter and LogFilter. Rest of the process would remain as explained
above except you need to create a different mapping as mentioned below −

<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>

<filter>
<filter-name>AuthenFilter</filter-name>
<filter-class>AuthenFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Filters Application Order

The order of filter-mapping elements in web.xml determines the order in which the web
container applies the filter to the servlet. To reverse the order of the filter, you just need to
reverse the filter-mapping elements in the web.xml file.

For example, above example would apply LogFilter first and then it would apply AuthenFilter to
any servlet but the following example would reverse the order −

<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

5. How to define Filter

We can define filter same as Servlet. Let's see the elements of filter and filter-mapping.

1. <web-app>
2. <filter>
3. <filter-name>...</filter-name>
4. <filter-class>...</filter-class>
5. </filter>
6. <filter-mapping>
7. <filter-name>...</filter-name>
8. <url-pattern>...</url-pattern>
9. </filter-mapping>
10. </web-app>

For mapping filter we can use, either url-pattern or servlet-name. The url-pattern elements has an
advantage over servlet-name element i.e. it can be applied on servlet, JSP or HTML.

Example For Filter:

Application 1:

Simple Example of Filter


In this example, we are simply displaying information that filter is invoked automatically after
the post processing of the request.

Step1# index.html

<a href="servlet1">click here</a>

Step2# MyFilter.java

1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.*;
4. public class MyFilter implements Filter{
5. public void init(FilterConfig arg0) throws ServletException {}
6. public void doFilter(ServletRequest req, ServletResponse resp,
7. FilterChain chain) throws IOException, ServletException {
8. PrintWriter out=resp.getWriter();
9. out.print("filter is invoked before");
10. chain.doFilter(req, resp);//sends request to next resource
11. out.print("filter is invoked after");
12. }
13. public void destroy() {}
14. }

Step3# HelloServlet.java

1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.*;
5. public class HelloServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
8. response.setContentType("text/html");
9. PrintWriter out = response.getWriter();
10. out.print("<br>welcome to servlet<br>");
11. }
12. }

Step4# web.xml
For defining the filter, filter element of web-app must be defined just like servlet.

1. <web-app>
2. <servlet>
3. <servlet-name>s1</servlet-name>
4. <servlet-class>HelloServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>s1</servlet-name>
8. <url-pattern>/servlet1</url-pattern>
9. </servlet-mapping>
10. <filter>
11. <filter-name>f1</filter-name>
12. <filter-class>MyFilter</filter-class>
13. </filter>
14. <filter-mapping>
15. <filter-name>f1</filter-name>
16. <url-pattern>/servlet1</url-pattern>
17. </filter-mapping>
18. </web-app>

Authentication Filter

We can perform authentication in filter. Here, we are going to check to password given by the
user in filter class, if given password is admin, it will forward the request to the WelcomeAdmin
servlet otherwise it will display error message.

Application 2 :

Example of authenticating user using filter

Let's see the simple example of authenticating user using filter.

Here, we have created 4 files:

 index.html
 MyFilter.java
 AdminServlet.java
 web.xml

Step1# index.html

1. <form action="servlet1">
2. Name:<input type="text" name="name"/><br/>
3. Password:<input type="password" name="password"/><br/>
4. <input type="submit" value="login">
5. </form>

Step2# MyFilter.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.*;
4. public class MyFilter implements Filter{
5. public void init(FilterConfig arg0) throws ServletException {}
6. public void doFilter(ServletRequest req, ServletResponse resp,
7. FilterChain chain) throws IOException, ServletException {
8. PrintWriter out=resp.getWriter();
9. String password=req.getParameter("password");
10. if(password.equals("admin")){
11. chain.doFilter(req, resp);//sends request to next resource
12. }
13. else{
14. out.print("username or password error!");
15. RequestDispatcher rd=req.getRequestDispatcher("index.html");
16. rd.include(req, resp);
17. }
18. }
19. public void destroy() {}
20. }

Step3# : AdminServlet.java

1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.ServletException;
4. import javax.servlet.http.*;
5. public class AdminServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
8. response.setContentType("text/html");
9. PrintWriter out = response.getWriter();
10. out.print("welcome ADMIN");
11. out.close();
12. }
13. }

Step4# : web.xml

1. <web-app>
2. <servlet>
3. <servlet-name>AdminServlet</servlet-name>
4. <servlet-class>AdminServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>AdminServlet</servlet-name>
8. <url-pattern>/servlet1</url-pattern>
9. </servlet-mapping>
10. <filter>
11. <filter-name>f1</filter-name>
12. <filter-class>MyFilter</filter-class>
13. </filter>
14. <filter-mapping>
15. <filter-name>f1</filter-name>
16. <url-pattern>/servlet1</url-pattern>
17. </filter-mapping>
18. </web-app>

Application 3:

Example of sending response by filter only

MyFilter.java

1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class MyFilter implements Filter{
5. public void init(FilterConfig arg0) throws ServletException {}
6.
7. public void doFilter(ServletRequest req, ServletResponse res,
8. FilterChain chain) throws IOException, ServletException {
9.
10. PrintWriter out=res.getWriter();
11.
12. out.print("<br/>this site is underconstruction..");
13. out.close();
14.
15. }
16. public void destroy() {}
17. }

Application 4:

Example of counting number of visitors for a single page

MyFilter.java

1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class MyFilter implements Filter{
5. static int count=0;
6. public void init(FilterConfig arg0) throws ServletException {}
7.
8. public void doFilter(ServletRequest req, ServletResponse res,
9. FilterChain chain) throws IOException, ServletException {
10.
11. PrintWriter out=res.getWriter();
12. chain.doFilter(request,response);
13.
14. out.print("<br/>Total visitors "+(++count));
15. out.close();
16.
17. }
18. public void destroy() {}
19. }

Application 5:

Example of checking total response time in filter

MyFilter.java

1. import java.io.*;
2. import javax.servlet.*;
3. public class MyFilter implements Filter{
4. static int count=0;
5. public void init(FilterConfig arg0) throws ServletException {}
6. public void doFilter(ServletRequest req, ServletResponse res,
7. FilterChain chain) throws IOException, ServletException {
8. PrintWriter out=res.getWriter();
9. long before=System.currentTimeMillis();
10. chain.doFilter(request,response);
11. long after=System.currentTimeMillis();
12. out.print("<br/>Total response time "+(after-before)+" miliseconds");
13. out.close();
14. }
15. public void destroy() {}
16. }
17.

Event and Listener in Servlet

1. Event and Listener in Servlet


2. Event classes
3. Event interfaces

Events are basically occurrence of something. Changing the state of an object is known as an
event.

We can perform some important tasks at the occurrence of these exceptions, such as counting
total and current logged-in users, creating tables of the database at time of deploying the project,
creating database connection object etc.

There are many Event classes and Listener interfaces in the javax.servlet and javax.servlet.http
packages.

Event classes

The event classes are as follows:

1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent

Event Interfaces

The event interfaces are as follows:

1. ServletRequestListener.
2. ServletRequestAttributeListener.
3. ServletContextListener.
4. ServletContextAttributeListener.
5. HttpSessionListener.
6. HttpSessionAttributeListener.
7. HttpSessionBindingListener.
8. HttpSessionActivationListener.

ServletContextEvent and ServletContextListener

1. ServletContextEvent and ServletContextListener


2. Constructor of ServletContextEvent class
3. Method of ServletContextEvent class
4. Methods of ServletContextListener interface
5. Example of ServletContextEvent and ServletContextListener
6. Example of ServletContextListener to create table of a project

The ServletContextEvent is notified when web application is deployed on the server.

If you want to perform some action at the time of deploying the web application such as creating
database connection, creating all the tables of the project etc, you need to implement
ServletContextListener interface and provide the implementation of its methods.

Constructor of ServletContextEvent class

There is only one constructor defined in the ServletContextEvent class. The web container
creates the instance of ServletContextEvent after the ServletContext instance.

1. ServletContextEvent(ServletContext e)

Method of ServletContextEvent class

There is only one method defined in the ServletContextEvent class:

1. public ServletContext getServletContext(): returns the instance of ServletContext.

Methods of ServletContextListener interface

There are two methods declared in the ServletContextListener interface which must be
implemented by the servlet programmer to perform some action such as creating database
connection etc.

1. public void contextInitialized(ServletContextEvent e): is invoked when application is


deployed on the server.
2. public void contextDestroyed(ServletContextEvent e): is invoked when application is
undeployed from the server.

Example of ServletContextEvent and ServletContextListener

In this example, we are retrieving the data from the emp32 table. To serve this, we have created
the connection object in the listener class and used the connection object in the servlet.

index.html

1. <a href="servlet1">fetch records</a>

MyListener.java
1. import javax.servlet.*;
2. import java.sql.*;
3.
4. public class MyListener implements ServletContextListener{
5. public void contextInitialized(ServletContextEvent event) {
6. try{
7. Class.forName("oracle.jdbc.driver.OracleDriver");
8. Connection con=DriverManager.getConnection(
9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
10.
11. //storing connection object as an attribute in ServletContext
12. ServletContext ctx=event.getServletContext();
13. ctx.setAttribute("mycon", con);
14.
15. }catch(Exception e){e.printStackTrace();}
16. }
17.
18. public void contextDestroyed(ServletContextEvent arg0) {}
19. }

MyListener.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. import java.sql.*;
5.
6. public class FetchData extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. try{
15. //Retrieving connection object from ServletContext object
16. ServletContext ctx=getServletContext();
17. Connection con=(Connection)ctx.getAttribute("mycon");

18. //retieving data from emp32 table


19. PreparedStatement ps=con.prepareStatement("select * from emp32",
20. ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
21.
22. ResultSet rs=ps.executeQuery();
23. while(rs.next()){
24. out.print("<br>"+rs.getString(1)+" "+rs.getString(2));
25. }
26.
27. con.close();
28. }catch(Exception e){e.printStackTrace();}
29.
30. out.close();
31. }
32. }

Example of ServletContextListener to create table of a project

In this example, we are creating table of the project. So we don't need to create all the tables
manually in the database.

MyListener.java

1. import javax.servlet.*;
2. import java.sql.*;
3. public class MyListener implements ServletContextListener{
4. public void contextInitialized(ServletContextEvent arg0) {
5. try{
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7. Connection con=DriverManager.getConnection("
8. jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
9. String query="create table emp32(id number(10),name varchar2(40))";
10. PreparedStatement ps=con.prepareStatement(query);
11. ps.executeUpdate();
12. System.out.println(query);
13. }catch(Exception e){e.printStackTrace();}
14. }
15. public void contextDestroyed(ServletContextEvent arg0) {
16. System.out.println("project undeployed");
17. }
18. }

Servlet Filters are Java classes that can be used in Servlet Programming for the following
purposes −

 To intercept requests from a client before they access a resource at back end.
 To manipulate responses from server before they are sent back to the client.

There are various types of filters suggested by the specifications −


 Authentication Filters.
 Data compression Filters.
 Encryption Filters.
 Filters that trigger resource access events.
 Image Conversion Filters.
 Logging and Auditing Filters.
 MIME-TYPE Chain Filters.
 Tokenizing Filters .
 XSL/T Filters That Transform XML Content.

Filters are deployed in the deployment descriptor file web.xml and then map to either servlet
names or URL patterns in your application's deployment descriptor.

When the web container starts up your web application, it creates an instance of each filter that
you have declared in the deployment descriptor. The filters execute in the order that they are
declared in the deployment descriptor.

Servlet Filter Methods

A filter is simply a Java class that implements the javax.servlet.Filter interface. The
javax.servlet.Filter interface defines three methods −

Sr.No. Method & Description

public void doFilter (ServletRequest, ServletResponse, FilterChain)


1
This method is called by the container each time a request/response pair is passed
through the chain due to a client request for a resource at the end of the chain.
public void init(FilterConfig filterConfig)
2
This method is called by the web container to indicate to a filter that it is being placed
into service.
public void destroy()

This method is called by the web container to indicate to a filter that it is being taken out
3 of service.

Servlet Filter − Example

Following is the Servlet Filter Example that would print the clients IP address and current date
time. This example would give you basic understanding of Servlet Filter, but you can write more
sophisticated filter applications using the same concept −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Implements Filter class


public class LogFilter implements Filter {
public void init(FilterConfig config) throws ServletException {

// Get init parameter


String testParam = config.getInitParameter("test-param");

//Print the init parameter


System.out.println("Test Param: " + testParam);
}

public void doFilter(ServletRequest request, ServletResponse response,


FilterChain chain) throws java.io.IOException, ServletException {

// Get the IP address of client machine.


String ipAddress = request.getRemoteAddr();

// Log the IP address and current timestamp.


System.out.println("IP "+ ipAddress + ", Time " + new Date().toString());

// Pass request back down the filter chain


chain.doFilter(request,response);
}

public void destroy( ) {


/* Called before the Filter instance is removed from service by the web container*/
}
}

Compile LogFilter.java in usual way and put your class file in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes

Servlet Filter Mapping in Web.xml

Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet is
defined and then mapped to a URL pattern. Create the following entry for filter tag in the
deployment descriptor file web.xml

<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

The above filter would apply to all the servlets because we specified /* in our configuration. You
can specicy a particular servlet path if you want to apply filter on few servlets only.

Now try to call any servlet in usual way and you would see generated log in your web server log.
You can use Log4J logger to log above log in a separate file.

Using Multiple Filters

Your web application may define several different filters with a specific purpose. Consider, you
define two filters AuthenFilter and LogFilter. Rest of the process would remain as explained
above except you need to create a different mapping as mentioned below −

<filter>
<filter-name>LogFilter</filter-name>
<filter-class>LogFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>

<filter>
<filter-name>AuthenFilter</filter-name>
<filter-class>AuthenFilter</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>Initialization Paramter</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Filters Application Order

The order of filter-mapping elements in web.xml determines the order in which the web
container applies the filter to the servlet. To reverse the order of the filter, you just need to
reverse the filter-mapping elements in the web.xml file.

For example, above example would apply LogFilter first and then it would apply AuthenFilter to
any servlet but the following example would reverse the order −

<filter-mapping>
<filter-name>AuthenFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

Listener:
1. What is the use of listener in Java?
Listeners do some work when an event occurs. They are called as "Event Listeners". Events
like click, hover etc. For Example, we have ActionListener interface in Java. It calls
actionPerformed() method when an event occurs.
Servlet Listener is used for listening to events in a web containers, such as when you create a
session, or place an attribute in an session or if you passivate and activate in another container, to
subscribe to these events you can configure listener in web.xml , for example
HttpSessionListener .
Listener Classes get notified on selected events, such as starting up the application or creating a
new Session. Listener Classes : These are simple Java classes which implement one of the two
following interfaces : javax.servlet.ServletContextListener.
javax.servlet.http.HttpSessionListener.Se
2. What is the event listener?
An event listener is a procedure or function in a computer program that waits for an event to
occur; that event may be a user clicking or moving the mouse, pressing a key on the keyboard, or
an internal timer or interrupt. The listener is in effect a loop that is programmed to react to an
input or signal

What is the purpose of a listener class in a large project


<listener>
<listener-class>com.sun.javaee.blueprints.petstore.model.CatalogFacade</listener-class>
</listener>

Listener Classes get notified on selected events, such as starting up the application or creating a
new Session.

Listener Classes :

These are simple Java classes which implement one of the two following interfaces :

 javax.servlet.ServletContextListener
 javax.servlet.http.HttpSessionListener

If you want your class to listen for application startup and shutdown events then implement
ServletContextListener interface. If you want your class to listen for session creation and
invalidation events then implement HttpSessionListener interface.

Difference between Filter and Listener in Servlet .

Servlet Filter is used for monitoring request and response from client to the servlet, or to modify
the request and response, or to audit and log.

Servlet Listener is used for listening to events in a web containers, such as when you create a
session, or place an attribute in an session or if you passivate and activate in another container, to
subscribe to these events you can configure listener in web.xml, for example HttpSessionListener

Why do we have servlet filters?

Servlet Filters are pluggable java components that we can use to intercept and process requests
before they are sent to servlets and response after servlet code is finished and before container
sends the response back to the client.
Some common tasks that we can do with filters are:

 Logging request parameters to log files.


 Authentication and autherization of request for resources.
 Formatting of request body or header before sending it to servlet.
 Compressing the response data sent to the client.
 Alter response by adding some cookies, header information etc.

Why do we have servlet listeners?

We know that using ServletContext, we can create an attribute with application scope that all
other servlets can access but we can initialize ServletContext init parameters as String only in
deployment descriptor (web.xml). What if our application is database oriented and we want to set
an attribute in ServletContext for Database Connection.

If you application has a single entry point (user login), then you can do it in the first servlet
request but if we have multiple entry points then doing it everywhere will result in a lot of code
redundancy. Also if database is down or not configured properly, we won’t know until first client
request comes to server. To handle these scenario, servlet API provides Listener interfaces that
we can implement and configure to listen to an event and do certain operations.

1. Filter

Filter Servlet is the server javax.servlet.Filter interface, is the main purpose of the filtration
character encoding, do some business logic judgment. Its working principle is, as long as you
request

in the web.xml configuration files to intercept the client, it will help you to intercept the request,
you can request or response (Request, Response) unified set of code, simplify operation; also can
be logical judgment, as the user is logged in or not, there is no authority access the page etc. It is
start with the web start the application you, initialized only once, can intercept related request,
only is destroyed when the web application you stop or redeployment, following by filtering the
code example to understand its use:

MyCharsetFilter.java

package ...;
import ...;
//Main purpose: filtration character encoding; secondly, to do some application logic. making
// Filter with web application together to start making
// when web application restart or destroyed, Filter also destroyed making
public class MyCharsetFilter implements Filter {
private FilterConfig config = null;
public void destroy() {
System.out.println("MyCharsetFilter is ready to destroy...");
}
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOEx
ception, ServletException {
// casts making
HttpServletRequest request = (HttpServletRequest)arg0;
HttpServletResponse response = (HttpServletResponse)arg1;
// gets web.xm setup code set, set to Request, Response making
request.setCharacterEncoding(config.getInitParameter("charset"));
response.setContentType(config.getInitParameter("contentType"));
response.setCharacterEncoding(config.getInitParameter("charset"));
// forwards the request to the destination making
chain.doFilter(request, response);
}

public void init(FilterConfig arg0) throws ServletException {


this.config = arg0;
System.out.println("MyCharsetFilter initialization...");
}
}

The following is MyCharsetFilter.java in web.xml configuration:

1. <filter>
2. <filter-name>filter</filter-name>
3. <filter-class>dc.gz.filters.MyCharsetFilter</filter-class>
4. <init-param>
5. <param-name>charset</param-name>
6. <param-value>UTF-8</param-value>
7. </init-param>
8. <init-param>
9. <param-name>contentType</param-name>
10. <param-value>text/html;charset=UTF-8</param-value>
11. </init-param>
12. </filter>
13. <filter-mapping>
14. <filter-name>filter</filter-name>
15. <!-- * request all representative intercepted or specify request/test.do /xxx.do --
>
16. <url-pattern>/*</url-pattern>
17. </filter-mapping>
2. listeners

Now about the Servlet listener Listener, it is the realization of the server
javax.servlet.ServletContextListener interface, it is also with the web application startup
and restart, initialized only once, and the destruction of web application with the stop.
Main function is: do some initialization work content, set some of its basic contents, such
as the number of parameters or some fixed object etc. The use of database connection
pool using the listener DataSource initialization demo of it:

MyServletContextListener.java
package dc.gz.listeners;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.dbcp.BasicDataSource;

/**
Making * listener making Web application
*/
public class MyServletContextListener implements ServletContextListener {
//Method of destruction application listener making
public void contextDestroyed(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
// call before the destruction of the entire web, all applications will be space setting
emptied of its contents making
sc.removeAttribute("dataSource");
System.out.println("The destruction of the work completed...");
}

//Initialization method application listener making


public void contextInitialized(ServletContextEvent event) {
// through this event can obtain the entire application space making
//When launched in the entire web following some initial content work aking
ServletContext sc = event.getServletContext();
// provided some basic content; for example, some parameters or some fixed
object making
// creates the DataSource object, connection pool technology DBCP making
BasicDataSource bds = new BasicDataSource();

bds.setDriverClassName("com.mysql.jdbc.Driver"); bds.setUrl("jdbc:mysql
://localhost:3306/hibernate");
bds.setUsername("root");
bds.setPassword("root");
bds.setMaxActive(10);//The maximum number of connections making
bds.setMaxIdle(5);//The maximum number of making management
//bds.setMaxWait(maxWait); maximum waiting time making
//The DataSource in ServletContext space,
//The use of for the entire web application (for the database connection) aking
sc.setAttribute("dataSource", bds);
System.out.println("Application Monitor initialization completed...");
System.out.println("DataSource has already been created...");
}
The web.xml configuration is as follows, very simple:

18. <!-- configuration application listener making -->


19. <listener>
20. <listener-class>dc.gz.listeners.MyServletContextListener</listener-class>
21. </listener>

Thus configured, then can be used in Web BasicDataSource object through the
ServletContext, so as to get connected, and improve database performance, ease of use.

3 . interceptor

Interceptor is used in aspect oriented programming, is to call on your service or a method of a


method call, or in method a method. Reflection mechanism based on JAVA. The interceptor is
not in the web.xml, such as struts in struts.xml configuration,

22. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
23. {
24. Object result = null;
25. System.out.println("before invoke method :" + method.getName());
26. result = method.invoke(this.targetObj, args);
27. System.out.println("after invoke method : " + method.getName());
28. return result;
29. }

1: the so-called filter is used to filter filter name, In the Java Web, You pass the request,
response to filter out some information, Or to set some parameters, And then passed to
the servlet or struts action for business logic, For example, filter out illegal URL (not the
login.do address request, If the user does not have the landing are filtered out), or in the
incoming servlet or struts before the action set character set, Or remove some illegal
characters (chat rooms are often used, Some curse words). The filter process is linear,
then, URL came to check, maintain the original process continue execution, is the next
filter, servlet reception.

2. listeners: this thing is often used in c/s mode, he will produce a treatment for specific
events. Monitoring used in many mode. For example, the observer pattern, is a listening
to. For instance struts can be used to monitor to start. The Servlet listener listens for some
important events, the listener object can do some processing can occur before it
happened, after.

3.java interceptor is mainly used in plug-ins, extensions such as hivernate spring Struts2
are similar for slicing technique, to something in the configuration file or XML file
statement section before using.

You might also like