Choose.. X Home Exams Certifications

Servlets Interview Questions

1 . What is Servlets ?

  • Servlets are the programs that run under web server environment. A copy of Servlet class can handle numerous request threads. In servlets, JVM stays running and handles each request using a light weight thread.
        Servlets are modules that run within the server and receive and respond to the requests made by the client. Servlets retrieve most of the parameters using the input stream and send their responses using an output stream.
        Servlets are used to extend the server side functionality of a website. They communicate with various application on the server side and respond to the request made by the client.

2 . What are the general advantages of Servlets?

  • Servlets exhibit the following characteristics:
    • Can handle multiple requests concurrently.
    • Can synchronize requests
    • can forward requests to other servers and servlets.
    • Portable (Servlets are written in the Java programming language and follow a standard API)
    • They are Secure (Like CGI, they don't run shell and memory overflow, etc is handled by Java)
    • Inexpensive (There are a number of free or very inexpensive Web servers that are good for development use or deployment of low- or medium-volume Web sites)

3 . What is the difference between an Applet and a Servlet?

  • Applets
    • Applets are applications designed to be transmitted over the network and executed by Java compatible web browsers.
    • An Applet is a client side java program that runs within a Web browser on the client machine.
    • An applet can use the user interface classes like AWT or Swing.
    • Applet Life Cycle Methods: init(), stop(), paint(), start(), destroy()
    • Servlets are Java based analog to CGI programs, implemented by means of servlet container associated with an HTTP server.
    • Servlet is a server side component which runs on the web server.
    • The servlet does not have a user interface.
    • Servlet Methods: doGet(), doPost()

4 . Explain the life cycle methods of a Servlet.

  • The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
    1. public void init(ServletConfig config) throws ServletException
    2. public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
    3. 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 doGet()/doPost() methods in the case of HttpServlet.
    The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.

5 . What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?

  • 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 sart with a "/" and are interpreted as relative to curent context root.

6 . Explain the directory structure of a web application.

  • 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. classes directory
    3. lib directory

7 . What are the common mechanisms used for session tracking?

    1. Cookies
    2. SSL sessions
    3. URL- rewriting
    4. Hidden form fields

8 . Explain ServletContext.

  • 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 applicationor servlet container's version.
    Every web application has one and only one ServletContext and is accessible to all active resource of that application.

9 . What is preinitialization of a servlet?

  • A container doesnot 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 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.

10 . What is the difference between Difference between doGet() and doPost()?

  • 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:
    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.

11 . Define HTTP Tunneling?

  • In some organizations, the intranet is blocked by a firewall to the internet. It is exposed to the outer networks only by means of webserver port that accept only Http requests. In such situations, if protocols other than http are used, then they get rejected. The solution is to have them encapsulated in http or https and sent as an HttpRequest. Thus, masking other protocols as http requests is called HTTP Tunneling.

12 . What is the difference between HttpServlet and GenericServlet?

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

13 . What is the difference between ServletContext and ServletConfig?

  • Both are interfaces in the package javax.servlet.
    • ServletConfig is a servlet configuration object. It is used by a servlet container to pass information to a servlet during initialization.
    • The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.
    • ServletContext object is contained within the ServletConfig object. It is provided by the web server to the servlet when the servlet is initialized.
    • ServletContext is an interface which has a set of methods like getServletName(), getServletContext(), getInitParameter(), getInitParameterNames(). The servlet uses to interact with its servlet container.
    • ServletContext is common to all servlets within the same web application. So, servlets use ServletContext to share context information.

14 . What is filter? Can filter be used as request or response?

  • A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.

15 . What is new in ServletRequest interface ? (Servlet 2.4)

  • The following methods have been added to ServletRequest 2.4 version:
    • public int getRemotePort()
    • public java.lang.String getLocalName()
    • public java.lang.String getLocalAddr()
    • public int getLocalPort()

16 . How can I send user authentication information while making URL Connection?

  • You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.

17 . Can we use the constructor, instead of init(), to initialize servlet?

  • Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't.
        The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.

18 . How can a servlet refresh automatically if some new data has entered the database?

  • You can use a client-side Refresh or Server Push

19 . What are different Authentication options available in Servlets.

  • There are four ways of Authentication options available in servlets
    • HTTP basic authentication:
      In this, server uses the username and password provided by the client and these credentials are transmitted using simple base64 encoding.
    • HTTP digest authentication:
      This option is same the basic authentication except the password is encrypted and transmitted using SHA or MD5.
    • HTTPS client authentication:
      This options is based on HTTP over SSL.
    • Form-based authentication:
      Form-based authentication uses login page to collect username and password.

20 . Explain why HttpServlet is declared abstract.

  • The Constructor HttpServlet() does nothing because this is an abstract class. Default implementations in a few Java classes like HttpServlet don't really do anything. Hence, they need to be overridden.
    Usually one of the following methods of HttpServlet must be overridden by a subclass:
    • doGet, if the servlet supports HTTP GET requests
    • doPost, HTTP POST requests
    • doPut, HTTP PUT requests
    • doDelete, HTTP DELETE requests
    • init and destroy, to manage resources
    • getServletInfo, to provide information
    However, there doesn't seem to be any reason why the service method should be overridden because it eventually dispatches the task to one of the doXXX methods.

21 . What is the GenericServlet class?

  • GenericServlet makes writing servlets easier. To write a generic servlet, all you need to do is to override the abstract service method.

22 . What is the difference between using getSession(true) and getSession(false) methods?

    • getSession(true) will check whether a session already exists for the user. If yes, it will return that session object else it will create a new session object and return it.
    • getSession(false) will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.

23 . Define servlet mapping.

  • Servlet mapping controls how you access a servlet. It is recommended that you don’t use absolute URLs. Instead usage of relative URLs should be done.
    If you try to deploy the application with a different context root, you might have to change all the urls used in all the JSP programs. Relative URLs is the solution so that you can deploy your application with different context root with out changing the URLs.