Wednesday, May 15, 2013

Servlet Interview Questions - Part 2



As a continuation to the part 1 of questions on Servlets that we covered in this blog sometime ago, below are some more questions on Servlets.


1. What are the new features added to Servlet 2.5? 


Following are the new features introduced in Servlet 2.5:
• A new dependency on J2SE 5.0 
• Support for annotations 
• Loading the class 
• Several web.xml conveniences 
• A handful of removed restrictions 
• Some edge case clarifications

2. What are the phases of the servlet life cycle? 

The life cycle of a servlet consists of the following phases:
i. Servlet class loading - For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.
ii. Servlet instantiation - After loading, it instantiates one or more object instances of the servlet class to service the client requests.
iii. Initialization (call the init method) - After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container. 
iv. Request handling (call the service method) - After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.
v. Removal from service (call the destroy method) - A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection 

The life cycle of a servlet is controlled by the container in which the servlet has been deployed.

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

Let us say in a plain java class, you created an init method that gets invoked under some condition, will you be able to invoke it without actually instantiating your class? That is why we need a constructor even for a Servlet. 

4. When is the servlet 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. 

5. When is a Servlet unloaded? 

A servlet is unloaded when:
Server shuts down. 
Administrator manually unloads.

6. What is the GenericServlet class? 

GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface. 

Note: This class is known as generic servlet, since it is not specific to any protocol whereas the HttpServlet is specific to the Http Protocol

7. Why is the HttpServlet class declared abstract? 

The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. Just like any other abstract class, the HttpServlet is a partial skeleton which defines basic behavior and then gives the programmer the freedom to implement any of the other possible features he/she wants. 

The simplest example here could be the fact that, any HttpServlet could handle multiple doXXX() methods as we call them which include doGet(), doPost() etc. So, in your applications, if you handle just the POST requests, then you need not implement a doGet() to override the default doGet() implementation. 

8. Can a servlet have a constructor? 

Sure Yes. Though we don’t explicitly call the constructor using the new() operator, the container internally invokes the Servlet class’ container when the servlet is initialized. 

9. Should I override the service() method while using the HttpServlet? 

We never override the service method, since the HTTP Servlets have already taken care of it. The default service function invokes the doXXX() method corresponding to the method of the HTTP request. For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method checks the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method. 

10. What are the differences between the ServletConfig interface and the ServletContext interface? 

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. There is only one ServletConfig parameter per servlet. The param-value pairs for ServletConfig object are specified in the < init-param > within the < servlet > tags in the web.xml file

A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container. There is one ServletContext for the entire webapp and all the servlets in a webapp share it. The param-value pairs for ServletContext object are specified in the < context-param > tags in the web.xml file.

11.What are the differences between forward() and sendRedirect() methods?

Some key differences between the two methods are: 

a. A Forward is performed internally by the servlet whereas a redirect is a two-step process where the web application instructs the web browser to fetch a second/different URL
b. The browser and the user is completely unaware that a forward has taken place (The URL Remains intact) whereas in case of redirect, both the browser and the user will be made aware of the action including a change to the URL 
c. The resource to which control is being forwarded has to be part of the same context as the one that is actually calling it whereas in case of redirect this is not a restriction. 
d. Forwards are faster than redirects. Redirects are slower because it is actually handling two browser requests in place of forward’s one. 

12. What are the difference between the include() and forward() methods? 

The key differences between the two methods are: 

a. The include() method inserts the contents of the specified resource directly into the flow of the servlet response, as if it were part of the calling servlet, whereas the forward() is used to show a different resource in place of the servlet that was originally called 
b. The include() is often used to include common text or template markup that may be included in many servlets whereas forward() is often used where a servlet plays the role of a controller, processes some input and decides the outcome by returning a particular page response where control is transferred to a different resource 

13. What is the use of the servlet wrapper classes?

The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers 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.

14. What is a deployment descriptor? 

A deployment descriptor is an XML document. It defines a component's deployment settings. It declares transaction attributes and security authorization for an enterprise bean. The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean.
The Java EE server reads the deployment descriptor at run time and acts upon the components accordingly. 

15. 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, whereas, the getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accept relative paths. All path must start with a “/” and are interpreted as relative to current context root.

16. What is the < load-on-startup > element of the deployment descriptor? 

The element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. This setting by which a servlet is loaded even before it gets its first request is called pre-initialization of a servlet. It is also used to specify the order in which the files are to be loaded. The container will load the servlets in the order specified in this element. 

17. What is servlet lazy loading? 

Lazy servlet loading means – the container does not initialize the servlets as soon as it starts up. Instead it initializes servlets when they receive their first ever request. This is the standard or default behavior. If you want the container to load your servlet at start-up then use pre-initialization using the load-on-startup element in the deployment descriptor. 

18. What is Servlet Chaining? 

Servlet Chaining is a method where the output of one servlet is piped or passed onto a second servlet. The output of the second servlet could be passed on to a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

19. What are filters? 

Filters are Java components that are used to intercept an incoming request to a Web resource or the response that is sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are: 
Security checks 
Modifying the request or response 
Data compression 
Logging and auditing 
Response compression 
Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.

20. What are the functions of the Servlet container? 

The functions of the Servlet container are as follows:
a. Lifecycle management: It manages the life and death of a servlet, such as class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection. 
b. Communication support: It handles the communication between the servlet and the Web server. 
c. Multithreading support: It automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies. 
d. Declarative security: It manages the security inside the XML deployment descriptor file. 
e. JSP support: The container is responsible for converting JSPs to servlets and for maintaining them. 


If you have any questions that you want answer for, please leave a comment on this page OR drop a note to Snehal[at]TechProceed[dot]com and I will answer them. 

Servlet Interview Questions - part 1

The following are some questions you might encounter with respect to Java Servlets in any Interview. Servlets are the back-bone of almost all J2EE Web Applications and any interviewer who is selecting people for his J2EE project would want a person who is confident & comfortable using them. 



Apart from the questions below, there are a few articles that I have put up (as part of the SCWCD Certification series) on Servlets that you might find useful. You can use them to revise/review your understanding of Servlets. 

They are: 

  1. Servlet History 
  2. Servlet Handling of Http Requests 
  3. Servlet Request Types 
  4. Obtaining a Servlets Initialization Parameters 
  5. Servlet Context 
  6. Servlet Life-cycle 
  7. Servlet Exception Handling 
  8. Servlet API 

Questions: 

1. What is a Servlet?

Java Servlets are server side components that provides a powerful mechanism for developing server side of web application. Earlier CGI was used to provide server side capabilities for web applications. Although CGI played a major role in the explosion of the Internet, its performance, scalability and reusability issues made it less and less desirable among people who wanted enterprise class scalable applications. Java Servlets was the solution to all of CGIs problems. Built from ground up using Sun's java technology, servlets provide excellent framework for server side processing. They are an integral part of almost all J2EE applications

2. What are the types of Servlet?

There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides http protocl specific functionality. 

3. What are the differences between HttpServlet and Generic Servlets?

GenericServlet defines a generic, protocol-independent servlet whereas HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site that uses the Http Protocol. 

4. What are the differences between a Servlet and an Applet? 

* Servlets are server side components that executes on the server whereas applets are client side components and executes on the web browser. 
* Applets have GUI interface but there is no GUI interface in case of Servlets. 
* Applets have limited capabilities whereas Servlets are very poweful and can support a wide variety of operations 
* Servlets can perform operations like interacting with other servlets, JSP Pages, connect to databases etc while Applets cannot do all this. 

5. What are the differences between the doGet and doPost methods?

* Get sends information from the browser to the Servlet as contents appended to the query string in the URL while Post uses hidden variables 
* Because of the above point, post is a lot safer than get
* Get has a size limitation - i.e., we can send only approximately 1 Kb of data while Post can send a singnificantly higher amount of data
* Get is the most common type of sending data from a browser to a servlet, while Post is gaining popularity because of its size and safety which is better than the get. 

6. What are the different methods present in a HttpServlet?

The methods of HttpServlet class are :

* doGet() - To handle the GET, conditional GET, and HEAD requests 
* doPost() - To handle POST requests
* doPut() - To handle PUT requests
* doDelete() - To handle DELETE requests
* doOptions() - To handle the OPTIONS requests and 
* doTrace() - To handle the TRACE requests

Apart from these, a Servlet also contains init() and destroy() methods that are used to initialize and destroy the servlet respectively. They are not any operation specific and are available in all Servlets for use during their active life-cycle. 


7. What are the advantages of Servlets over CGI programs?

Java Servlets have a number of advantages over CGI and other API's. Some are: 

1. Platform Independence - Java Servlets are 100% pure Java, so it is platform independent. It can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server. You can easily run the same on apache web server without modification code. Platform independency of servlets provide a great advantages over alternatives of servlets. 

2. Performance - Anyone who has used CGI would agree that Servlets are much more powerful and quicker than CGI. Because the underlying technology is Java, it is fast and can handle multiple request simultaneously. Also, a servlet gets initialized only once in its lifetime and then continues to serve requests without having to be re-initialized again, hence the performance is much higher than CGIs. 

3. Extensibility - Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets takes all these advantages and can be extended from existing class the provide the ideal solutions. 

Also, in terms of Safety & Security Servlets are superior when compared to CGI. 

8. What are the lifecycle methods of Servlet?

The interface javax.servlet.Servlet, defines the three life-cycle methods. These are:

public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()

The container manages the lifecycle of the Servlet. When a new request come to a Servlet, the container performs the following steps: 

1. If an instance of the servlet does not exist, the web container
* Loads the servlet class.
* Creates an instance of the servlet class.
* Initializes the servlet instance by calling the init method. 
2. The container invokes the service method, passing request and response objects.
3. To remove the servlet, container finalizes the servlet by calling the servlet's destroy method.

9. What are the type of protocols supported by HttpServlet?

It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

10. What is ServletContext?

ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. 

11. What is meant by Pre-initialization of Servlet?

When servlet container is loaded, all the servlets defined in the web.xml file do not get initialized by default. When the container receives a request to hit a particular servlet, it loads that servlet. But in some cases if you want your servlet to be initialized when context is loaded, you have to use a concept called pre-initialization of Servlet. In this case, the servlet is loaded when context is loaded. You can specify 1 in between the tag in the Web.xml file in order to pre-initialize your servlet

12. What mechanisms are used by a Servlet Container to maintain session information?

Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.

13. What do you understand by servlet mapping?

Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url patterns. For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.

14. What interface must be implemented by all Servlets?

The Servlet Interface must be implemented by all servlets (either the GenericServlet or the HttpServlet)

15. What are the uses of Servlets?

* Servlets are used to process the client requests.
* A Servlet can handle multiple request concurrently and be used to develop high performance system
* A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.

16. What are the objects that are received when a servlets accepts call from client? 

The objects are: 
ServeltRequest and 
ServletResponse 

The ServeltRequest encapsulates the communication from the client to the
server. While ServletResponse encapsulates the communication from the Servlet back to the client. All the passage of data between the client and server happens by means of these request and response objects.

If you have any questions that you want answer for, please leave a comment on this page OR drop a note to Snehal[at]TechProceed[dot]com and I will answer them.