|Servlet Interview Questions
Servlet Example Program
|1. What is a servlet ?
| Servlet is a java program thatruns inside a web container.
|2. Can we use the constructor, instead of init(), to initialize servlet?
| Yes. But you will not get the
servlet specific things from constructor. The original reason for init() was
that ancient versions of Java couldn’t dynamically invoke constructors with
arguments, so there was no way to give the constructor a ServletConfig. That no
longer applies, but servlet containers still will only call your no-arg
constructor. So you won’t have access to a ServletConfig or ServletContext.
|3. What is servlet context ?
| The servlet context is an
object that contains a information about the Web application and
container. Using the context, a servlet can log events, obtain URL
references to resources, and set and store attributes that other servlets in the
context can use.
|4. What mechanisms are used by a Servlet Container to maintain session information?
| Cookies, URL rewriting, and
HTTPS protocol information are used to maintain session information.
|5. Difference between GET and POST?
| In GET your entire form
submission can be encapsulated in one URL, like a hyperlink. query length is
limited to 255 characters, not secure, faster, quick and easy. The data is
submitted as part of URL.
In POST data is submitted inside body of the HTTP request. The data is not
visible on the URL and it is more secure.
|6. What is session?
The session is an object used
by a servlet to track a user's interaction with a Web application across
multiple HTTP requests. The session is stored on the server.
|7. What is servlet mapping?
| The servlet mapping defines an
association between a URL pattern and a servlet. The mapping is used to map
requests to Servlets.
|8. What are the different ways for session tracking?
| Cookies, URL rewriting,
HttpSession, Hidden form fields.
|9. What is the difference in using request.getRequestDispatcher() and context.getRequest Dispatcher()?
request.getRequestDispatcher(path) in order to create it we need to give the
relative path of the resource. But in
resourcecontext.getRequestDispatcher(path) in order to create it we need to give
the absolute path of the resource.
|10. What are context initialization parameters?
| Context initialization
parameters are specified by the <context-param> in the web.xml file, these
are initialization parameter for the whole application.
|11. What's the Servlet Interface?
| A The central
abstraction in the Servlet API is the Servlet interface. All servlets implement
this interface, either directly or, more commonly, by extending a class that
implements it such as HttpServlet.
|12. What is the meaning of response has already been committed error?
| You will get this error only
when you try to redirect a page after you already have flushed the output
buffer. This happens because HTTP specification force the header to be set up
before the lay out of the page can be shown. When you try to send a redirect
status, your HTTP server cannot send it right now if it hasn't finished to set
up the header. Simply it is giving the error due to the specification of HTTP
1.0 and 1.1
|13. What is the difference between ServletContext and ServletConfig?
| The ServletConfig gives the
information about the servlet initialization parameters. The servlet engine
implements the ServletConfig interface in order to pass configuration
information to a servlet. The server passes an object that implements the
ServletConfig interface to the servlet's init() method. The ServletContext gives
information about the container. The ServletContext interface provides
information to servlets regarding the environment in which they are running. It
also provides standard way for servlets to write events to a log file.
|14. How can a servlet refresh automatically?
| A We can use
a client-side Refresh or Server Push.
|15. What is Server side push?
Server Side push is useful when
data needs to change regularly on the clients application or browser, without
intervention from client. The mechanism used is, when client first connects to
Server, then Server keeps the TCP/IP connection open.
|16. What is client side refresh?
| The standard HTTP protocols
ways of refreshing the page, which is normally supported by all browsers.
<META HTTP-EQUIV="Refresh" CONTENT="5; URL=/servlet/MyServlet/">
This will refresh the page in the browser automatically and loads the new data
every 5 seconds.
|17. What is the Max amount of information that can be saved in a Session Object ?
| There is no such limit on the
amount of information that can be saved in a Session Object. The only
limit is the Session ID length , which should not exceed more than 4K.
|18. Why should we go for inter servlet communication?
| The three major reasons to use
inter servlet communication are: a) Direct servlet manipulation - allows to gain
access to the other currently loaded servlets and perform certain tasks (through
the ServletContext object) b) Servlet reuse - allows the servlet to reuse the
public methods of another servlet. c) Servlet collaboration - requires to
communicate with each other by sharing specific information (through method
|19. What are the differences between a session and a cookie?
| Session is stored in server but
cookie stored in client. Session should work regardless of the settings on the
client browser. There is no limit on the amount of data that can be stored on
session. But it is limited in cookie. Session can store objects and cookies can
store only strings. Cookies are faster than session.
|20. What is HttpTunneling?
HTTP tunneling is used to
encapsulate other protocols within the HTTP or HTTPS protocols. Normally the
intranet is blocked by a firewall and the network is exposed to the outer world
only through a specific Web server port, that listens for only HTTP requests. To
use any other protocol, that by passes the firewall, the protocol is embedded in
HTTP and send as HttpRequest.
|21. How will you delete a cookie?
Cookie c = new Cookie("name", null);
|22. What is the difference between Context init parameter and Servlet init parameter?
| Servlet init parameters are for
a single servlet only. No body out side that servlet can access that. It is
declared inside the <servlet> tag inside Deployment Descriptor, where as
context init parameter is for the entire web application. Any servlet or JSP in
that web application can access context init parameter. Context parameters are
declared in a tag <context-param> directly inside the <web-app> tag.
The methods for accessing context init parameter is getServletContext ().getInitParamter
(“name”) where as method for accessing servlet init parameter is
getServletConfig ().getInitParamter (“name”);
|23. What are the different ways for getting a servlet context?
We will get ServletContext by
calling getServletConfig ().getServletContext (). This is because a
ServletConfig always hold a reference to ServletContext. By calling
this.getServletContext () also we will get a ServletContext object.
|24. What is the difference between an attribute and a parameter?
The return type of attribute is
object, where the return type of parameter is String. The method to retrieve
attribute is getAttribute () where as for parameter is getParamter (). We have a
method setAttribute to set an attribute. But there is no setters available for
setting a parameter.
|25. How to make a context thread safe?
| Synchronizing the
ServletContext is the only solution to make a ServletContext thread safe.
Eg: synchronized (getServletContext ())
// do whatever you want with thread safe context.
|26. What is the difference between setting the session time out in deployment descriptor and setting the time out programmatically?
| In DD time out is
specified in terms of minutes only. But in programmatically it is
specified in seconds. A session time out value of zero or less in DD means
that the session will never expire. To specify session will never expire
programmatically it must be negative value.
|27. How many cookies can one
set in the response object of the servlet? Also, are there any restrictions on
the size of cookies?
| If the client is using
Netscape, the browser can receive and store 300 total cookies and 4 kilobytes
per cookie. And the no of cookie is restricted to 20 cookies per server or
|28. How can my application get to know when a HttpSession is removed?
| You can define a class which
implements HttpSessionBindingListener and override the valueUnbound() method.
|29. How can we set the inactivity period on a per-session basis?
| We can set the session time out
programmatically by using the method setMaxInactiveInterval() of HttpSession.
|30. What is URL Encoding and URL Decoding ?
| URL encoding is the method of
replacing all the spaces and other extra characters into their corresponding Hex
Characters and Decoding is the process of converting all Hex Characters back to
their normal form.
|31. What is the difference between an applet and a servlet?
| Servlets run inside a web
server and applets run inside web browsers. Applets must have graphical user
interfaces whereas servlets have no graphical user interfaces.
|32. What are the different web servers available name few of them?
| Tomcat, Java
Web Server, JRun.
|33. What is a Java Bean?
| A Java Bean is a software
component that has been designed to be reusable in a variety of different
|34. What are the different types of ServletEngines?
| The different types of
ServletEngines available are:- Standalone ServletEngine: This is a server that
includes built-in support for servlets. Add-on ServletEngine: It is a plug-in to
an existing server. It adds servlet support to a server that was not originally
designed with servlets in mind.
|35. What is a Session Id?
| It is a unique id assigned by
the server to the user when a user starts a session.
|36. What is use of parseQueryString ?
| It parses a query string and
builds a Hashtable of key-value pairs, where the values are arrays of strings.
The query string should have the form of a string packaged by the GET or POST
|37. When init() and Distroy() will be called.
| init() is called whenever the
servlet is loaded for the first time into the web server. Destroy will be called
whenever the servlet is removed from the web server.
|38. What is the use of setComment and getComment methods in Cookies ?
| setComment: If a web browser
presents this cookie to a user, the cookie's purpose will be described using
this comment. This is not supported by version zero cookies.
getComment: Returns the comment describing the purpose of this cookie, or null
if no such comment has been defined.
|39. Why we are used setMaxAge() and getMaxAge() in Cookies ?
setMaxAge : Sets the maximum
age of the cookie. The cookie will expire after that many seconds have passed.
Negative values indicate the default behavior, and will be deleted when the
getMaxAge : Returns the maximum specified age of the cookie. If none was
specified, a negative value is returned, indicating the default behavior
described with setMaxAge.
|40. What is the use of setSecure() and getSecure() in Cookies ?
| setSecure method
indicates to the web browser that the cookie should only be sent using a secure
protocol (https). getSecure method returns the value of the 'secure' flag.
|41. How do you communicate between the servlets?
| We can communicate between
servlets by using RequestDespatcher interface and servlet chaining.
|42. What is Servlet chaining?
| Servlet chaining is a technique
in which two or more servlets can cooperate in servicing a single request. In
servlet chaining, one servlet’s output is the input of next servlet. This
process continues until the last servlet is reached. Its output is then sent
back to the client. We are achieving Servlet Chaining with the help of
|43. How will you communicate from an applet to servlet?
| There are three ways to
communicate from an applet to servlet and they are: HTTP Communication
(Text-based and object-based) , Socket Communication and RMI Communication.
|44. Can we call a servlet with parameters in the URL?
| Yes. You can
call a servlet with parameters in the URL like ?param=value.
|45. How do servlets handle multiple simultaneous requests?
| When a request comes in, the
web server will start a new thread and the request is assigned to a thread,
which calls a service method of the servlet.
|46. Explain the directory structure of a web application?
| The directory structure of a
web application consists of two parts. A private directory called WEB-INF and a
public resource directory which contains files server to public. WEB-INF folder
consists of web.xml (the deployment descriptor), classes directory (where we
keeps all our classes and servlets) and lib directory (where we keeps all our
jar files). The public folder contains the static resources of the web
|47. What is pre initialization of a servlet?
| A container doesn't initialize
the servlets when it starts up. It initializes a servlet when it receives a
request for that servlet first time. This is called lazy loading. The servlet
specification defines the <load-on-startup> element, which can be
specified in the deployment descriptor to make the servlet container load and
initialize the servlet as soon as it starts up. The process of loading a servlet
before any request comes in is called preloading or pre initializing a servlet.
|48. What are the uses of ServletRequest?
| The ServletRequest gives
information such as the names of the parameters passed by the client, the
protocol (scheme) being used by the client, and the names of the remote host
that made the request and the server that received it. The input stream,
|49. What are the uses of ServletResponse interface?
allows the servlet to set the content length and MIME type of that response. It
provides an output stream, ServletOutputStream and a Writer through which the
servlet can send data.
|50. How HTTP Servlet handles client requests?
| An HTTP
Servlet handles client requests through its service method. The service method
supports standard HTTP client requests by dispatching each request to a method
designed to handle that request.
|51. Is HTML page a web component?
| No. Static
HTML pages and applets are not considered as web components by J2EE
specification. Even the server-side utility classes are not considered web
|52.What is the container?
| A container
is a runtime support of a system-level entity. Containers provide components
with services such as lifecycle management, security, deployment, and
|53. What is the web container?
| A Servlet
and JSP containers are collectively referred to as Web containers.
|54. What is deployment descriptor?
| A deployment descriptor is an
XML based file which describes a web application's deployment settings.
The name of deployment descriptor of a web application is web.xml.
|55. How can you implement singleton pattern in servlets ?
| All servlets are singleton only
, if the servlet is not implementing SingleThreadModel.
|56. What is the difference between an application server and a web server?
| Everything in web server must
be achieved programmatically. But application server provides a lot of services
like security, transaction , scalability. Application server will be having EJB
support where web server don't have an EJB support.
|57. What is servlet exception?
| It indicates
that there is an exception occurred in the servlet.
|58. Can we implement Runnable interface from within our servlet?
| Our servlet
can implement the Runnable interface.
|59. What is a WAR file?
| WAR stands for Web Archive. It
is a compressed version of your web application. You can use this WAR file to
deploy your web application.
|60. What is a servlet filter?
filters are pluggable Web components that allow us to implement pre-processing
and post-processing logic in our Web applications.
|Back to Top