50 Servlet Interview Questions and Answers

Servlets are very important topic of Java EE and all of the web applications framework such as Spring and Struts are built on top of it. This makes servlet a hot topic in Java interviews.

Here I am providing a list of 50 servlet interview questions with answers to help you tackle most of the interview questions related to servlets and web applications in java.

  1. What is different between web server and application server?
  2. Which HTTP method is non-idempotent?
  3. What is the difference between GET and POST method?
  4. What is MIME Type?
  5. What is a web application and what is it’s directory structure?
  6. What is a servlet?
  7. What are the advantages of Servlet over CGI?
  8. What are common tasks performed by Servlet Container?
  9. What is ServletConfig object?
  10. What is ServletContext object?
  11. What is difference between ServletConfig and ServletContext?
  12. What is Request Dispatcher?
  13. What is difference between PrintWriter and ServletOutputStream?
  14. Can we get PrintWriter and ServletOutputStream both in a servlet?
  15. How can we create deadlock situation in servlet?
  16. What is the use of servlet wrapper classes?
  17. What is SingleThreadModel interface?
  18. Do we need to override service() method?
  19. Is it good idea to create servlet constructor?
  20. What is difference between GenericServlet and HttpServlet?
  21. What is the inter-servlet communication?
  22. Are Servlets Thread Safe? How to achieve thread safety in servlets?
  23. What is servlet attributes and their scope?
  24. How do we call one servlet from another servlet?
  25. How can we invoke another servlet in a different application?
  26. What is difference between ServletResponse sendRedirect() and RequestDispatcher forward() method?
  27. Why HttpServlet class is declared abstract?
  28. What are the phases of servlet life cycle?
  29. What are life cycle methods of a servlet?
  30. why we should override only no-agrs init() method.
  31. What is URL Encoding?
  32. What are different methods of session management in servlets?
  33. What is URL Rewriting?
  34. How does Cookies work in Servlets?
  35. How to notify an object in session when session is invalidated or timed-out?
  36. What is the difference between encodeRedirectUrl and encodeURL?
  37. Why do we have servlet filters?
  38. What is the effective way to make sure all the servlets are accessible only when user has a valid session?
  39. Why do we have servlet listeners?
  40. How to handle exceptions thrown by application with another servlet?
  41. What is a deployment descriptor?
  42. How to make sure a servlet is loaded at the application startup?
  43. How to get the actual path of servlet in server?
  44. How to get the server information in a servlet?
  45. Write a servlet to upload file on server.
  46. How do we go with database connection and log4j integration in servlet?
  47. How to get the IP address of client in servlet?
  48. What are important features of Servlet 3?
  49. What are different ways for servlet authentication?
  50. How can we achieve transport layer security for our web application?

  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.

    WAR-directory-structure

    Read more about web applications at Java Web Application.

  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.

    Servlet-Hierarchy

    Read more at Servlet Tutorial.

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

    You can read more about IO in java at Java IO Tutorial.

  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.

    Read more about deadlock in multithreading at Java Deadlock Example.

  16. What is the use of servlet wrapper classes?

    Servlet HTTP API provides two wrapper classes – HttpServletRequestWrapper and HttpServletResponseWrapper. These wrapper classes are provided to help developers with custom implementation of servlet request and response types. We can extend these classes and override only specific methods we need to implement for custom request and response objects. These classes are not used in normal servlet programming.

  17. 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.

  18. 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.

  19. 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.

  20. 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.


That’s all for the servlet interview questions and answers. I will keep on adding more servlet based interview questions to the list in future, so don’t forget to bookmark it for future reference.

Please share your thoughts in comments and share your love with sharing on Google Plus, Facebook or Twitter. :)

Update: If you liked these questions, I am sure you will like JSP Interview Questions too.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Current day month ye@r *