Sunday, October 11, 2015

Servlet Interview Questions and Answers

1. What is a servlet?
A servlet is a java program that runs within a web server and serves the client request hence the name servlet. Servlets can receive and respond to requests from web clients working on any client-server protocol, but HTTP is predominantly used. Servlet is a server side script technology which can process client request and give back the response.
2. What is a servlet container?
A servlet container is a container for servlets which is responsible for managing the servlets. The main functions are load, initialize and execute servlets to serve client requests. When a request is received, the container decides what servlet to call based on a configuration file. Servlet container comes installed with the web servers. Examples: Tomcat, Glassfish, JBoss.
3. What is CGI?
Common Gateway Interface(CGI) was the most commonly used for server side scripting before the evolution of the java servlet technology. With traditional CGI, a new process is started for each HTTP request eating up more of the CPU cycles thus degrading the performance of the system.
4. What are the advantages of servlet over CGI?
  • When a CGI script is called, a new process is created for each and every client request. But for servlets, each request is handled by a separate thread. Hence, servlet is more efficient because process creation takes more time compared to thread creation.
  • For each new CGI requests, CGI script is copied into memory. But with servlets, there is only one copy across requests and is shared among threads.
  • In CGI multiple process serves concurrent requests. But for servlets, only single instance serves concurrent requests.
5. Describe about the life cycle of servlet?
Life cycle methods of a servlet are:
  • init() method: During initialization web container initializes the servlet instance by calling the init() method passing a ServletConfig interface object as parameter. The ServletConfig object allows the servlet to access initialization parameters. It is called only once in the life cycle of servlet.
  • service() method: When client requests are serviced this method gets called. Each requests is serviced in its own thread. For every client requests web container calls the servlet’s service method. The service method determines the type of requests and invokes the appropriate method e.g. if the client request is HTTP get method then corresponding servlet’s doGet() method will be called.
  • destroy() method: The web container calls the destroy method and takes the servlet out of service. It is called only once in the life cycle of servlet, when you stop the server or when you undeploy the application from the server.

No comments: