Servlet Interview Questions and Answers

1) What is a servlet?

A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request. Basically servlets are usually used to implement web applications. All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods.

2) Explain functioning of web server with an example in context to servlet?

Suppose user made the request for the URL <strong> </strong> then: <br/> <strong>1. </strong> web browser establishes a connection with server by locating its IP address from a DNS server. <br/> <strong>2. </strong> The web browser then sends a request to the server to retrieve the intl/en/privcy.html file.<br/> <strong>3. </strong>The server respond with the info about the the requested HTML page and the contents of privacy.html file.<br/> This process of sending a request and receiving a response from the server is known as transaction.An HTTP session remains open till a single transaction is completed.

3) How performance of Servlet is better than CGI?

Performance of servlets is better than CGI scripts because CGI scripts need to be loaded in various process for every request. On the other hand, a servlet , once loaded in the memory, can be run multiple times on a single lightweight thread.

4) What is the role of web server in a J2EE application?

<strong>1.</strong> Web server converts the request into an HTTPServletRequest object.<br/> <strong>2.</strong> The HTTPServletRequest object is sent to a web compnent to establish a communication with javabeans components.<br/> <strong>3. </strong>The HTTPServletResponse object is generated by the web component and finally the HTTPServletResponse object displys the data to the client as the resonse generated by the web server.

5) What are the functions of Servlet container?

The main functions of Servlet container are:<br/> <strong>1. Lifecycle management : </strong>Managing the lifecycle events of a servlet lik class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.<br/> <strong>2. Communication support : </strong>Handling the communication between servlet and Web server.<br/> <strong>3. Multithreading support : </strong>Automatically creating a new thread for every servlet request and finishing it when the Servlet service() method is over.<br/> <strong>4. Declarative security : </strong>Managing the security inside the XML deployment descriptor file.<br/> <strong>5. JSP support : </strong>Converting JSPs to servlets and maintaining them.

6) Explain Servlet Workflow.

When a client request is received by a web container , firstly the container maps the request with an appropriate servlet according to deployment descriptor. After the servlet is idenified, the web container loads the servlet class and creates an instance of the servlet. The servlet is then initialized by calling init() method. After calling the init() method, the service() ethod passess the request and response object to the web conatainer. The web container invokes the destroy() method to remove the servlet, if the servlet is not required.

7) Can we define costructor in Servlet?

Yes, Servlet implementation classes can have constructor but there is no point in creating a constructor in servlet because Servlet require ServletConfig object for initialization which is created by container itself.

8) What is difference between GenericServlet and HttpServlet?

<strong>javax.servlet.Servlet </strong>is interface, it defines methods for all the implementations - that's what interfaces usually do.<br/> <strong>javax.servlet.GenericServlet </strong>is protocol independent. It is abstract, so it is not to be directly instantiated. It is usable class to extend if you some day have to write servlet for protocol other than HTTP.<br/> <strong>javax.servlet.http.HttpServlet</strong> is abstract class to be extended if you want to communicate over HTTP protocol. Most likely you only have to care about this one.

9) What is a deployment descriptor in Servlet?

Deployment descriptor is a configuration file for the web application and it’s name is web.xml and it resides in WEB-INF directory. Servlet container use this file to configure web application servlets, servlet config params, context init params, filters, listeners, welcome pages and error handlers.<br/> With servlet 3.0 annotations, we can remove a lot of clutter from web.xml by configuring servlets, filters and listeners using annotations.

10) What is the inter-servlet communication?

Based on the bussiness, we can have multiple servlets for specific business scenario. In that case it is required to have inter-servlet communication. We can achieve this in Servlet by using RequestDispatcher forward() and include() methods and provide additional attributes in request for other servlet use.

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

<strong>1.</strong> The first aim for a servlet is to achieve thread safety by virtue of no shared state. Any shared state will fail to be that when the servlet is deployed into a load-balancing cluster. <br/> <strong>2.</strong> Any local variables in service methods are thread safe because they are specific to each thread but for shared resource we can use synchronization to achieve thread safety in servlets.

12) What is difference between ServletResponse sendRedirect() and RequestDispatcher forward() method?

<strong>1.</strong> 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.<br/> <strong>2.</strong> forward() is handled internally by the container whereas sendRedirect() is handled by browser.<br/> <strong>3.</strong> We should use forward() when accessing resources in the same application because it’s faster than sendRedirect() method that required an extra network call.<br/> <strong>4.</strong> 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.<br/> <strong>5.</strong> forward() can’t be used to invoke a servlet in another context, we can only use sendRedirect() in this case.

13) Why HttpServlet class is declared abstract?

To have any useful behaviour, it is expected that you will have to override the methods. HttpServlet does not have useful functionality on its own.Making its constructors private would limit the ability for subclasses to be created.<br/> The design of HttpServlet was probably not ideal -- as on many pages, forms especially, GET and POST logic should proceed at least partly along a common path. The design idea of HttpServlet however was to offer doGet(), doPost() etc implementations answering a 'not supported' error depending on HTTP version. These stubs would be useful to inherit if you needed to return such an answer.<br/> In summary, the API/ interface is complete -- but the functionality is definitively not. Thus it is declared as abstract.

14) What are life cycle methods of a servlet?

The javax.servlet.Servlet interface defines the life cycle methods of servlet such as init(), service() and destroy(). The Web container invokes the init(), service() and destroy() methods of a servlet during its life cycle.

15) What are the different HTTP methods?

<strong>1.</strong> GET <strong>2.</strong> POST <strong>3.</strong> PUT <strong>4.</strong> DELETE <strong>5.</strong> OPTIONS <strong>6.</strong> HEAD <strong>7.</strong> TRACE

16) Which HTTP method is non-idempotent?

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

17) What is MIME Type?

The <strong>Content-Type</strong> 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.

18) What is a web application and what is it’s directory structure in Servlet?

Web Applications are modules that requires to run on server to handle the request and return the response. Java provides web application support through Servlets and JSPs that can run in a servlet container and provide dynamic content to client browser.<br/> Java Web Applications are packaged as Web Archive (WAR) and it has following folders in it.<br/> <strong>WEB-INF :</strong> contains the lib directory(application dependencies), classes(contains java servlet files) and web.xml(Deployment Descriptor)<br/> <strong>META-INF: </strong> contains MANIFEST.MF<br/> <STRONG>webapp:</strong> contains all the static pages like .html , .js etc

19) What is Servlet Chaining?

It is a method in which the output of one servlet is piped into the next servlet.<br/> It is the last servlet in the chain that provides the output to the Web browser.

20) 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 by calling servlet's init() method.A servlet is initialized only once in its life cycle and hence the init() method is called only once per servlet by a web server.

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

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

23) What is difference between ServletConfig and ServletContext?

ServletConfig is a unique object per servlet whereas ServletContext is a unique object for complete application.<br/> 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.<br/> We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext that other servlets can use in their implementation.

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

25) What is the difference between include() and forward() in Servlet?

<strong>include()</strong> Includes the response of another servlet into the calling servlet. This method can be invoked from calling servlet while servicing the request. It includes contents of resource such as Servlet, JSP page or HTML page in response.<br/> <strong>forward() </strong> mehod is used to forward requests to resource such as Servlet, JSP file or HTML page on the server. I implies that after invoking forward() method, the servlet can not add any response content.

26) 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.<br/> There are two methods defined in this interface:<br/> <strong>void forward(ServletRequest request, ServletResponse response)</strong> – forwards the request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.<br/> <strong>void include(ServletRequest request, ServletResponse response) </strong>– includes the content of a resource (servlet, JSP page, HTML file) in the response.

27) What is difference between PrintWriter and ServletOutputStream?

<strong>1.</strong>PrintWriter is a character-stream class whereas ServletOutputStream is a byte-stream class. <br/> <strong>2.</strong>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.<br/> <strong>3.</strong>We can use ServletResponse getWriter() to get the PrintWriter instance whereas we can use ServletResponse getOutputStream() method to get the ServletOutputStream object reference.

28) What is session management and What are different methods of session management in servlets?

Http is a stateless, client-side pull only protocol.To implement a stateful conversation over it, Java EE Web Server need to hide some information (which is sessionid) in client-side and the mechanism it can use should follow HTTP and HTML spec.<br/> There are three ways to accomplish this goal:<br/> <strong>Cookies </strong> - Server will ask browser to maintain a cookie.<br/> <strong>Hidden Form Field </strong> - server will add an additional parameter at every form in HTML<br/> <strong>URL Rewriting </strong> - Server will add an additional parameter at the end of URL link

29) How do we manage session using cookies?

Using cookies is the simplest and easiest way to track a session.A unique session id (stored in the form of a cookie) is sent by the server to the client as a part of the response and the same session id saved with the client is sent to the server as a part of the request which helps the server to recognize the unique client session.

30) What is the difference between encodeRedirectUrl and encodeURL?

<strong>encodeURL() </strong>is used for all URLs in a servlet's output. It helps session ids to be encoded with the URL.<br/> <strong>encodeRedirectURL() </strong> is used with res.sendRedirect only. It is also used for encoding session ids with URL but only while redirecting.

31) Why servlet filter is required?

Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:<br/> To intercept requests from a client before they access a resource at back end.<br/> To manipulate responses from server before they are sent back to the client.

32) How to handle exceptions thrown by application with another servlet?

We can configure them in web.xml like below:<br/> &lt;error-page&gt;<br/> &lt;error-code&gt;400&lt;/error-code&gt;<br/> &lt;location&gt;/BadRequestExceptionHandler&lt;/location &gt;<br/> &lt;/error-page &gt;<br/><br/> &lt;error-page&gt;<br/> &lt;exception-type &gt;javax.servlet.ServletException&lt;/exception-type&gt;<br/> &lt;location&gt;/BadRequestExceptionHandler&lt;/location&gt;<br/> &lt;/error-page&gt;

33) What do load-on-startup does?

Usually servlet container loads a servlet on the first client request but sometimes when the servlet is heavy and takes time to loads, we might want to load it on application startup. We can use load-on-startup element with servlet configuration in web.xml file or use WebServlet annotation loadOnStartup variable to tell container to load the servlet on system startup.<br/> <br/> &lt;servlet&gt;<br/> &lt;servlet-name&gt;bar&lt;/servlet-name&gt;<br/> &lt;servlet-class&gt;;/servlet-class&gt;<br/> &lt;load-on-startup&gt;1&lt;/load-on-startup&gt;<br/> &lt;/servlet&gt; <br/><br/> The load-on-startup value should be int, if it’s negative integer then servlet container will load the servlet based on client requests and requirement but if it’s 0 or positive, then container will load it on application startup.<br/> If there are multiple servlets with load-on-startup value such as 0,1,2,3 then lower integer value servlet will be loaded first.

34) How can we create deadlock condition on our servlet?

one simple way to call doPost() method inside doGet() and doGet()method inside doPost() it will create deadlock situation for a servlet.

35) How many objects are created when same or different client send 100 requests to a servlet?

Servlet creates only one instance either request is 100 or 200.

36) What are Wrappers in servlet?

Wrappers are sandwiched between servlet classes and servlet environments by wrapping servlet APIs. Wrappers allow to add additional functionalities to the request and response object given by the servlet container.<br/> Filters can also use wrappers to wrap request or response.Servlet 3.0 provide following 4 wrapper classes.<br/> <strong>1.</strong> java.serlet.ServletRequestWrapper<br/> <strong>2.</strong> javax.servlet.ServletResponseWrapper<br/> <strong>3.</strong> javax.servlet.http.HTTPServletResponseWrapper

Is this page helpful to you? Please give us your feedback below. We would love to hear your thoughts on these articles, it will help us improve further our learning process.