Servlets - Interview Questions - Tutorialspoint
Servlets - Interview Questions - Tutorialspoint
Dear readers, these Servlets Interview Questions have been designed especially to get you
acquainted with the nature of questions you may encounter during your interview for the subject of
Servlets Programming. As per my experience, good interviewers hardly planned to ask any
particular question during your interview, normally questions start with some basic concept of the
subject and later they continue based on further discussion and what you answer:
Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a request coming from a Web browser or other HTTP client and databases or applications
on the HTTP server.
directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet.
The servlet is initialized by calling the init () method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
The init method is designed to be called only once. It is called when the servlet is first created, and
not called again for each user request. So, it is used for one-time initializations, just as with the init
method of applets.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and
calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
https://www.tutorialspoint.com/servlets/servlets_interview_questions.htm 2/10
2/24/2021 Servlets - Interview Questions - Tutorialspoint
The destroy() method is called only once at the end of the life cycle of a servlet.
The init() method simply creates or loads some data that will be used throughout the life of the
servlet.
This method gives your servlet a chance to close database connections, halt background threads,
write cookie lists or hit counts to disk, and perform other such cleanup activities.
The service() method is the main method to perform the actual task. The servlet container (i.e. web
server) calls the service() method to handle requests coming from the client( browsers) and to write
the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and
calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
The service () method is called by the container and service method invokes doGe, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you
override either doGet() or doPost() depending on what type of request you receive from the client.
https://www.tutorialspoint.com/servlets/servlets_interview_questions.htm 3/10
2/24/2021 Servlets - Interview Questions - Tutorialspoint
Servlets handles form data parsing automatically using the following methods depending on the
situation:
getParameter(): You call request.getParameter() method to get the value of a form
parameter.
getParameterValues(): Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
getParameterNames(): Call this method if you want a complete list of all parameters in
the current request.
When a browser requests for a web page, it sends lot of information to the web server which can
not be read directly because this information travel as a part of header of HTTP request.
HTTPServletRequest represents this HTTP Request.
when a Web server responds to a HTTP request to the browser, the response typically consists of
a status line, some response headers, a blank line, and the document. HTTPServletResponse
represents this HTTP Response.
https://www.tutorialspoint.com/servlets/servlets_interview_questions.htm 4/10
2/24/2021 Servlets - Interview Questions - Tutorialspoint
out.println("Hello World");
Page redirection is generally used when a document moves to a new location and we need to send
the client to this new location or may be because of load balancing, or for simple randomization.
The simplest way of redirecting a request to another page is using method sendRedirect() of
response object.
This method generates a 302 response along with a Location header giving the URL of the new
document.
This method sends a status code (usually 404) along with a short message that is automatically
formatted inside an HTML document and sent to the client.
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.
https://www.tutorialspoint.com/servlets/servlets_interview_questions.htm 5/10
2/24/2021 Servlets - Interview Questions - Tutorialspoint
Authentication Filters.
Data compression Filters.
Encryption Filters.
Filters that trigger resource access events.
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.
This method is called by the web container to indicate to a filter that it is being placed into service.
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.
This method is called by the web container to indicate to a filter that it is being taken out of service.
Yes.
Yes. 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.
https://www.tutorialspoint.com/servlets/servlets_interview_questions.htm 6/10
2/24/2021 Servlets - Interview Questions - Tutorialspoint
Use the error-page element in web.xml to specify the invocation of servlets in response to certain
exceptions or HTTP status codes.
If you want to have a generic Error Handler for all the exceptions then you should define following
error-page instead of defining separate error-page elements for every exception:
<error-page>
<exception-type>java.lang.Throwable</exception-type >
<location>/ErrorHandler</location>
</error-page>
Cookies are text files stored on the client computer and they are kept for various information
tracking purpose. Java Servlets transparently supports HTTP cookies.
Keep in mind, neither the name nor the value should contain white space or any of the following
characters: [ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie
should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add
cookies in the HTTP response header as follows:
response.addCookie(cookie);
To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the
getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and
getValue() methods to access each cookie and associated value.
To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up
following three steps:
Read an already exsiting cookie and store it in Cookie object.
Set cookie age as zero using setMaxAge() method to delete an existing cookie.
What is session?
Session provides a way to identify a user across more than one page request or visit to a Web site
and to store information about that user. The session persists for a specified time period, across
more than one connection or page request from the user.
You can append some extra data on the end of each URL that identifies the session, and the server
can associate that session identifier with data it has stored about that session. For example, with
http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as
sessionid=12345 which can be accessed at the web server to identify the client.
You would get HttpSession object by calling the public method getSession() of HttpServletRequest,
as below:
When you are done with a user's session data, you have several options:
Remove a particular attribute: You can call public void removeAttribute(String name)
method to delete the value associated with a particular key.
Delete the whole session: You can call public void invalidate() method to discard an
entire session. Setting Session timeout: You can call public void setMaxInactiveInterval(int
interval) method to set the timeout for a session individually.
https://www.tutorialspoint.com/servlets/servlets_interview_questions.htm 8/10
2/24/2021 Servlets - Interview Questions - Tutorialspoint
Log the user out: The servers that support servlets 2.4, you can call logout to log the
client out of the Web server and invalidate all sessions belonging to all the users.
setAttribute(String name, Object value) of HTTPSession object binds an object to this session,
using the name specified and can be used to update an attribute in session.
The simplest way of refreshing a web page is using method setIntHeader() of response object.
What is internalization?
This means enabling a web site to provide different versions of content translated into the visitor's
language or nationality.
What is localization?
This means adding resources to a web site to adapt it to a particular geographical or cultural region
for example Hindi translation to a web site.
What is locale?
java.util.Locale request.getLocale()
Following method returns a name for the locale's country that is appropriate for display to the user.
https://www.tutorialspoint.com/servlets/servlets_interview_questions.htm 9/10
2/24/2021 Servlets - Interview Questions - Tutorialspoint
String getDisplayCountry()
What is Next?
Further, you can go through your past assignments you have done with the subject and make sure
you are able to speak confidently on them. If you are fresher then interviewer does not expect you
will answer very complex questions, rather you have to make your basics concepts very strong.
Second it really doesn't matter much if you could not answer few questions but it matters that
whatever you answered, you must have answered with confidence. So just feel confident during
your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very
best for your future endeavor. Cheers :-)
https://www.tutorialspoint.com/servlets/servlets_interview_questions.htm 10/10