Tuesday, February 25, 2014

Servlet interview questions

What is a Servlet ?
Servlet can be defined in two ways :
  • As a technology 
  • From web application point of view 
As a technology , servlet represents an API that is partially implemented by application programmers and partially by web server vendors. From web application point of view, Servlet is a java class that is executed by web server to generate dynamic contents.


What is the hierarchy of servlet api ?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or , by extending a class that implements it. The implementations of Servlet interface are javax.servlet.GenericServlet andjavax.servlet.http.HttpServlet. Below diagram shows the hierarchy of servlet.




What are the uses of Servlet ?
Typical uses for Servlets are :
  • 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. 
  • Manage state information that does not exist in the stateless HTTP protocol, such as filling the articles into the shopping cart of the appropriate customer

What are the advantages of Servlet over CGI ?
  • In CGI based application, a new process is created for each request . A lot of overhead is involved in creation and destruction of processes . In Servlet , a new thread is created to process a request. 
  •  CGI scripts were platform dependent but Servlet is not. 
  •  A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.

Define servlet life cycle.
  1. Servlet class loading 
  2. Servlet instantiation 
  3. Initialization init() 
  4. Request handling service()
  5. Removal from service destroy()
Step 1, 2 and 3 are executed only once, when the servlet is initially loaded. By default the servlet is not loaded until the first request is received for it.
Step 4 is executed for every HTTP request to the servlet .
Step 5 is executed when the servlet container unloads the servlet.

Why do we need a constructor in a servlet if we use the init method ?
The purpose of init is to initialize the Servlet but before that container needs an instance of the servlet .Constructor is used for the same purpose.


How the servlet is loaded ?
A servlet can be loaded in the following ways : 
  • When the first request for the servlet comes. 
  • At the time of server startup.
How a Servlet is unloaded ?
A Servlet gets unloaded when : Administrator manually unloads the servlet. Server shuts down.


What is the GenericServlet ?
GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. It is named GenericServlet because the class is protocol independent. GenericServlet makes writing servlets easier.
This class also provides simple versions of the lifecycle methods init and destroy and of the methods in ServletConfig interface. It also implements the log method declared in the ServletContext interface.


What is the difference between GenericServlet and HttpServlet ?
Below table shows the differences between GenericServlet and HttpServlet .


GenericServletHttpServlet
GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides an framework for handling the HTTP protocol.
GenericServlet is not specific to any protocol.HttpServlet only supports HTTP and HTTPS protocol.


Why is HttpServlet declared as abstract ?
HttpServlet is abstract because the http handler methods in HttpServlet does nothing and must be overridden. The implementation of service method has provided convinience that not all http handlers methods needs to be implemented.
For example if your custom servlet is required to handle the GET request , just implement doGet() method and there is no need to implement the doPost().

Can servlet have a constructor ?
YES , servlet can have a constructor and we can perform operations with that constructor as we normally do.The only thing is that it can not be called explicitly with the new keyword. Servlet container is responsible for instantiating a servlet , so the constructor is only called by the container only.

What are the types of protocols supported by HttpServlet ?
HttpServlet is specifically made for HTTP protocol so it can only suppory HTTP and HTTPS protocols.


What is the difference between doGet() and doPost()?
Below table shows the differences between doGet() and doPost()


doGet()doPost()
The request parameters gets appended to the URL hence visible in address bar.Request parameters are sent as a part of body so are not visible.
Limited data can be sent as request parameters are sent as a part of header and size of http header is fixed.Unlimited data can be sent because request parametrs are sent as part of the body.
Parameters are not encrypted.Parameters are encrypted.
GET request pages can be cached ( Allows bookmarking ).Disllows bookmarking.
GET request should be idempotent i.e repeating the request over and over again should not have any side effect.POST request does not need to be idempotent


When to use doGet() and when doPost()?
As we have seen the differences between a GET and POST request , we should prefer using GET requests apart for the scenarios mentioned below. Use POST if data is sensitive. Use POST if the size of data is greater than 1024 characters.

Can we support both GET and POST from the same Servlet ?
YES .

Can we override the service() method ?
YES we can but we should not . If a class overrides the service() method , then it will have to provide its own implementation for detecting the method type ( GET or POST ) of incoming request , and then invoking the corresponding handler method such as doGet or doPost.

What is a servlet context ?
ServletContext provides an interface of the servlet container to the servlets of an application. It means that the servlets communicates with the servlet container through ServletContext object. Foe example - to get MIME type of a file , dispatch requests or write a log file. There is only one context per web application per java virtual machine.

What are the differences between the ServletConfig and ServletContext ?
Below table shows the differences between ServletConfig and ServletContext.


ServletConfigServletContext
The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
There is one ServletConfig per servlet.There is one ServletContext for the entire webapp and all the servlets in a webapp share it.

What are the differences between forward() and sendRedirect()?
Below table shows the differences between forward and sendRedirect


forwardsendRedirect
A forward is performed internally by the servlet.A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original.
Both resources must be part of the same context.This method can be used to redirect users to resources that are not part of the current context, or even in the same domain.
Forward is marginally faster than redirect.Redirect is marginally slower than a forward, since it requires two browser requests, not one.
Request is forwarded to a new servlet so the request objects remains the same.A completely new request is sent by the browser so the request object changes.
The original URL does not changes.The browser is making a new request , so the URL changes .


What is the difference between the include() and forward()?
Below table shows the differences between include and forward 


includeforward
include() method inserts the contents of the specified resource directly in the flow of the servlet response.forward() forwards the request to another resource in the same context . Response is generated by the same servlet.
Included resource must not attempt to change the response status code or http headers. Any such attempt will be ignored.forwaded resource may be another servlet, jsp or a static html document but the response is issued under the same URL that was originally requested.

What are wrapper classes and what is their purpose ?
The wrapper classes can be used to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behavior is to pass all method calls directly to the underlying objects.

HttpServletRequestWrapper and HttpServletResponseWrapper are the servlet wrapper classes.

What is a deployment descriptor ?
Deployment descriptor ( DD ) is an xml file that defines component's deployment settings. The information provided by the deployment descriptor is declarative and therefore can be modified without changing the source code. The server reads the DD at runtime and acts upon the components accordingly.

What is the difference between the getRequestDispatcher(String path) method of ServletRequest interface and ServletContext interface ?
The getRequestDispatcher(String path)of ServletRequest accepts the relative path , relative to the current servlet. On the other hand, the same method in ServletContext can't accept relative paths . All the paths must start with "/" and are interpreted as relative to the current context root.

What is preinitialization of a servlet ?
Container does not initialize the servlets as 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.

What is the  <load-on-startup> element ?
The  element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the order in which the files are to be loaded. The  element is defined in deployment descriptor ( web.xml ).

<servlet>

   <servlet-name>name</servlet-name>
   <servlet-class>class</servlet-class>
   <load-on-startup>1</load-on-startup>
</servlet>

What is servlet lazy loading?
Container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading.

What is Servlet Chaining?
Servlet Chaining means the output of one servlet act as a input to another servlet. Servlet Aliasing allows us to invoke more than one servlet in sequence when the URL is opened with a common servlet alias. The output from first Servlet is sent as input to other Servlet and so on. The Output from the last Servlet is sent back to the browser. The entire process is called Servlet Chaining.

What are the functions of the Servlet container?
The various functions of a servlet container are :
Lifecycle Management
Container is responsible for managing the life cycle of the servlets.

Communication Management
Servlet container manages the communication between webserver and a servlet.

Multithreading support
Container creates a new thread each time a new request comes for a servlet.

Declarative Security
Servlet container manages the security through deployment descriptor file.

JSP Support
Servlet container is responsible for translating JSPs into servlets and maintaining them.

4 comments :

  1. HI, Friends this very usefull java servlet interview questions
    for excellent knowledge on java servlet visit http://www.itsoftpoint.com/?page_id=2425

    ReplyDelete