Servlet Interview Question
  1. What is different between web server and application server?

    A web server is responsible to handle HTTP requests from client browsers and respond to 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 provides 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. 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 Java. 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 the HTTP protocol and that’s why we mostly extend HttpServlet class.

  3. What are the uses of Servlet?

    Typical uses for HTTP Servlets include:

    • Processing and/or storing data submitted by an HTML form.
    • Providing dynamic content, e.g. returning the results of a database query to the client.
    • A Servlet can handle multiple request concurrently and be used to develop high performance systems.
    • Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

  4. What is the life cycle of Servlet?

    Following is the life cycle of Servlet:

    • Loaded
    • Initialized
    • Destroy
    • Unloaded
  5. Why do we need a constructor in a servlet if we use the init method?

    Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet’s constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven’t constructed an object to call it on yet.

  6. How the servlet is loaded?

    A servlet can be loaded when:

    • First request is made.
    • Server starts up (auto-load).
    • There is only a single instance, which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
    • Administrator manually loads.
  7. How a Servlet is unloaded?

    A servlet is unloaded when:

    • Server shuts down.
    • Administrator manually unloads.
  8. What is deployment descriptor?

    web.xml file of a web application is known as deployment descriptor. It is usually placed in the WEB-INF folder of application.

    It has the information like Servlet name, Servlet mapping, etc. This file tells the Servlet container which Servlet class needs to be called for the given URL pattern.

  9. What is Servlet interface?

    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.

  10. Are Servlets Thread Safe?

    HttpServlet init() method and destroy() method are called only once in a servlet life cycle, so we don’t need to worry about their synchronization. But service methods such as doGet() or doPost() are getting called in every client request and since the servlet uses multi threading, we should provide thread safety in these methods.

  11. How to achieve thread safety in servlets?

    If there are any local variables in service methods, we don’t need to worry about their thread safety because they are specific to each thread, but if we have a shared resource then we can use synchronization to achieve thread safety in servlets when working with shared resources.

  12. 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 multi threading support of servlets, that’s why this interface is Deprecated in Servlet 2.4.

  13. Explain the difference between HttpServlet and GenericServlet?

    A GenericServlet has a service() method to handle the requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doPut(), doOptions(), doDelete(), doTrace() methods.

    GenericServlet does not support any protocol. HTTPSeervlet support HTTP and HTTPS protocol.

    GenericServlet cannot handle cookies and session while HTTPServlet can handle them.

  14. What is ServletConfig?

    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.

  15. What is ServletContext?

    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.

  16. Explain the difference between ServletConfig and ServletContext?

    ServletConfig as the name implies provide the information about the configuration of a servlet which is defined inside the web.xml file or we can say deployment descriptor. Its a specific object for each servlet.

    ServletContext is an application specific object which is shared by all the servlet belongs to one application in one JVM. This is a single object which represents our application and all the servlet access application specific data using this object. Servlet also use their method to communicate with the container.

  17. What is RequestDispatcher?

    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.

    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.

  18. How do we call one servlet from another servlet?

    We can use RequestDispatcher forward() method to forward the processing of a request to another servlet.

    If we want to include the another servlet output to the response, we can use RequestDispatcher include() method.

  19. How can we invoke another servlet in a different application?

    We cannot use RequestDispatcher to invoke servlet from another application because it’s specific for the application. If we have to forward the request to a resource in another application, we can use ServletResponse sendRedirect() method and provide complete URL of another servlet.

    This sends the response to client with response code as 302 to forward the request to another URL. If we have to send some data also, we can use cookies that will be part of the servlet response and sent in the request to another servlet.

  20. What is session management?

    Session management is a mechanism for maintaining state across multiple HTTP requests. This is managed by the web container. In other words it is a technique to hold some values passed by user across multiple HTTP requests arising out from a single browser instance.

  21. What are different methods of session management in servlets?
    1. User Authentication
    2. HTML Hidden Field
    3. Cookies
    4. URL Rewriting
    5. Session Management API
  22. What is a HTML Hidden Field?

    Hidden Fields are nothing but normal HTML form element with type Hidden to store the user data across HTTP request.

  23. How to manage session using Cookies?

    Cookies are used a lot in web client-server communication, it’s not something specific to java. Cookies are text data sent by server to the client and it gets saved at the client local machine.

    Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.

    HttpServletRequest getCookies() method is provided to get the array of Cookies from request, since there is no point of adding Cookie to request, there are no methods to set or add cookie to request.

    Similarly HttpServletResponse addCookie(Cookie c) method is provided to attach cookie in response header, there are no getter methods for cookie.

  24. What is URL Rewriting?

    We can use HttpSession for session management in servlets but it works with Cookies and we can disable the cookie in client browser. Servlet API provides support for URL rewriting that we can use to manage session in this case.

    The best part is that from coding point of view, it’s very easy to use and involves one step – encoding the URL. Another good thing with Servlet URL Encoding is that it’s a fallback approach and it kicks in only if browser cookies are disabled.

    We can encode URL with HttpServletResponse encodeURL() method and if we have to redirect the request to another resource and we want to provide session information, we can use encodeRedirectURL() method.

  25. What is HTTP Session in servlets?

    Session tracking in Servlets is done by using Interface HttpSession. It helps to identify a client throughout many page requests or visiting a website and to store details about that client.

    HttpSession session = request.getSession();
    • If user already has a session the existing session is returned.
    • If no session exists a new one is created and returned.
    • If you want to know if this is a new session: call the Session isNew() method.
  26. How to invalidate a session in servlet?

    By calling session.invalidate() method.

  27. How to notify an object in session when session is invalidated or timed-out?

    If we have to make sure an object gets notified when session is destroyed, the object should implement javax.servlet.http.HttpSessionBindingListener interface.

    This interface defines two callback methods – valueBound() and valueUnbound() that we can define to implement processing logic when the object is added as attribute to the session and when session is destroyed.

  28. 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 piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.

  29. What are the Scope Objects available?

    Enables sharing information among collaborating web components via attributes maintained in Scope objects.Attributes are name/object pairs.Attributes maintained in the Scope objects are accessed with getAttribute() & setAttribute()

    Scope objects are four types:

    • Web Context: Accessible from Web components within a Web context
    • Session: Accessible from Web components handling a request that belongs to the session
    • Request: Accessible from Web components handling the request
    • Page: Accessible from JSP page that creates the object
  30. What is servlet filters?

    Servlet Filters are pluggable java components that we can use to intercept and process requests before they are sent to servlets and response after servlet code is finished and before container sends the response back to the client.

    Some common tasks that we can do with filters are:

    • Logging request parameters to log files.
    • Authentication and autherization of request for resources.
    • Formatting of request body or header before sending it to servlet.
    • Compressing the response data sent to the client.
    • Alter response by adding some cookies, header information etc.
It's good to share...Share on FacebookTweet about this on TwitterShare on LinkedInPin on PinterestShare on Google+Email this to someone

Leave a Reply

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