0% found this document useful (0 votes)
140 views5 pages

Servlet Interview Questions

The document contains 19 questions related to servlets. The questions cover topics like the life cycle of servlets, differences between servlet interfaces like ServletRequest, ServletResponse, ServletContext and ServletConfig, session tracking mechanisms, thread safety in servlets, and common uses of servlets. [/SUMMARY]

Uploaded by

ksgdba
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
140 views5 pages

Servlet Interview Questions

The document contains 19 questions related to servlets. The questions cover topics like the life cycle of servlets, differences between servlet interfaces like ServletRequest, ServletResponse, ServletContext and ServletConfig, session tracking mechanisms, thread safety in servlets, and common uses of servlets. [/SUMMARY]

Uploaded by

ksgdba
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 5

Servlet Interview Questions

1 Explain the life cycle methods of a Servlet.


A: The javax.servlet.Servlet interface defines the three methods known as life-cycle
method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws
ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.
Any request from client are handled initially by the service() method before
delegating to the doXxx() methods in the case of HttpServlet.

The servlet is removed from service, destroyed with the destroy() method, then
garbaged collected and finalized.

(OR)
Each servlet has the same life cycle:
A server loads and initializes the servlet (init())
The servlet handles zero or more client requests (service())
The server removes the servlet (destroy()) (some servers do this step only when they shut down).
TOP

Q2:What is the difference between the getRequestDispatcher(String path)


method of javax.servlet.ServletRequest interface and
javax.servlet.ServletContext interface?
A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest
interface accepts parameter the path to the resource to be included or forwarded
to, which can be relative to the request of the calling servlet. If the path begins
with a "/" it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext


interface cannot accepts relative paths. All path must start with a "/" and are
interpreted as relative to current context root.
TOP

Q3:Explain the directory structure of a web application.


A: The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.

WEB-INF folder consists of


1.web.xml
2.Classesdirectory
3. lib directory
TOP

Q4:What are the common mechanisms used for session tracking?


A: Cookies
SSL sessions
URL- rewriting
TOP

Q5:Explain ServletContext.
A: ServletContext interface is a window for a servlet to view it's environment. A
servlet can use this interface to get information such as initialization parameters
for the web application or servlet container's version. Every web application has
one and only one ServletContext and is accessible to all active resource of that
application.
TOP

Q6:What is preinitialization of a servlet?


A: A container does not initialize the servlets ass soon as 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 preinitializing a servlet.

Q7:What is the difference between Difference between doGet() and


doPost()?
A: A doGet() method is limited with 2k of data to be sent, and doPost() method
doesn't have this limitation. A request string for doGet() looks like the following:
http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN
doPost() method call doesn't need a long text tail after a servlet name in a
request. All parameters are stored in a request itself, not in a request string, and
it's impossible to guess the data transmitted to a servlet only looking at a
request string.
[ Received from Amit Bhoir ] TOP

Q8:What is the difference between HttpServlet and GenericServlet?


A: A GenericServlet has a service() method aimed to handle requests. HttpServlet
extends GenericServlet and adds support for doGet(), doPost(), doHead()
methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods
(HTTP 1.1).
Both these classes are abstract.

(OR)
GenericServlet is for servlets that might not use HTTP, like for instance FTP service.As of only
Http is implemented completely in HttpServlet. The GenericServlet has a service() method that
gets called when a client request is made. This means that it gets called by both incoming
requests and the HTTP requests are given to the servlet as they are.
[ Received from Amit Bhoir ] TOP

Q9:What is the difference between ServletContext and ServletConfig?


A: ServletContext: Defines a set of methods that a servlet uses to communicate
with its servlet container, for example, to get the MIME type of a file, dispatch
requests, or write to a log file.The ServletContext object is contained within the
ServletConfig object, which the Web server provides the servlet when the servlet
is initialized

ServletConfig: The object created after a servlet is instantiated and its default
constructor is read. It is created to pass initialization information to the servlet.
Q10: Difference between single thread and multi thread model serv??
A: Typically, a servlet class is instantiated the first time it is invoked. The same
instance will be used over several client requests, so all members that are declared
in that servlet are shared across clients.

That is what is meant by multi threaded model, multiple clients that access the
same instance. There are situations where you want to protect your servlet member
variables from being modified by different clients.

In this case, you can have your servlet implement the marker interface
SingleThreadModel. Every time a client makes a request to a servlet that
implements this interface, the engine will create a new instance of the servlet.

For performance reasons, the engine can also maintain a instance pool, handing out
instances as they are needed. Or it could also serialize client requests, executing
one after another.

Q11: If you want a servlet to take the same action for both GET and POST request,
what should you do?
A: Simply have doGet call doPost, or vice versa.

Q12: Which code line must be set before any of the lines that use the
PrintWriter?
A: setContentType() method must be set before transmitting the actual document.

Q13: What are the advantages using servlets than using CGI?
A: Servlets provide a way to generate dynamic documents that is both easier to
write and faster to run. It is efficient, convenient, powerful, portable, secure and
inexpensive.
Servlets also address the problem of doing server-side programming with platform-
specific APIs. They are developed with Java Servlet API, a standard Java
extension.

Q14: When a servlet accepts a call from a client, it receives two objects. What are
they?
A: ServeltRequest: which encapsulates the communication from the client to the
server.
ServletResponse: which encapsulates the communication from the servlet back to
the client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet
package.
Q15: What information that the ServletResponse interface gives the servlet
methods for replying to the client?
A: It Allows the servlet to set the content length and MIME type of the reply.
Provides an output stream, ServletOutputStream and a Writer through which the
servlet can send the reply data.

Q16: What information that the ServletRequest interface allows the servlet
access to?
A: Information such as the names of the parameters passed in 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,
ServletInputStream.Servlets use the input stream to get data from clients that
use application protocols such as the HTTP POST and PUT methods.

Q17: What is a better approach for enabling thread-safe servlets and JSPs?
SingleThreadModel Interface or Synchronization?
A: Although the SingleThreadModel technique is easy to use, and works well for low
volume sites, it does not scale well. If you anticipate your users to increase in the
future, you may be better off implementing explicit synchronization for your
shared data.
The key however, is to effectively minimize the amount of code that is
synchronized so that you take maximum advantage of multithreading. Also, note
that SingleThreadModel is pretty resource intensive from the server's
perspective.

The most serious issue however is when the number of concurrent requests exhaust
the servlet instance pool. In that case, all the unserviced requests are queued until
something becomes free - which results in poor performance. Since the usage is
non-deterministic, it may not help much even if you did add more memory and
increased the size of the instance pool.

Q18: What are the uses of Servlets?


A: A servlet can handle multiple requests concurrently, and can synchronize
requests. This allows servlets to support systems such as on-line conferencing.
Servlets can forward requests to other servers and servlets. Thus servlets can be
used to balance load among several servers that mirror the same content, and to
partition a single logical service over several servers, according to task.

Q19: In how many ways we can track the sessions?


A: Method 1) By URL rewriting
Method 2) Using Session object

Getting Session form HttpServletRequest object


HttpSession session = request.getSession(true);

Get a Value from the session


session.getValue(session.getId());

Adding values to session


cart = new Cart();
session.putValue(session.getId(), cart);

At the end of the session, we can inactivate the session by using the following
command
session.invalidate();

Method 3) Using cookies

Method 4) Using hidden fields

Q20: Is there any way to generate PDF'S dynamically in servlets?


A: We need to use iText. A open source library for java. Please refer
www.sourceforge.com site for sample servlet examples.

Q21: What is the difference between using getSession(true) and getSession(false)


methods?
A: getSession(true) - This method will check whether already a session is existing
for the user. If a session is existing, it will return that session object, Otherwise it
will create new session object and return that object.

getSession(false) - This method will check existence of session. If session exists,


then it returns the reference of that session object, if not, this methods will
return null.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy