Servlet Questions and Answers for Beginner Level

 1. What is Servlet?

- Java Servlet is server-side technologies to extend the capability of web servers by providing support for dynamic response and data persistence.

2. What is the difference between web server and application server?

- A web server is a device or application program which handles HTTP request from the client browser and response to the client browser. - Application Servers handles request and responses and also provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management, etc.

3. Difference between CGI and Servlet?

Servlet

CGI

Servlets can link directly to the Web server.

CGI cannot directly link to the Web server.

Servlets can share data with each other.

CGI does not provide sharing property.

Servlets can perform session tracking and caching of previous computations.

CGI cannot perform session tracking and caching of previous computations.

In Servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread.

In CGI, each request is handled by a heavyweight operating system process.

Servlets are portable.

CGI is not portable.

Servlets automatically parse and decode the HTML form data.

CGI cannot automatically parse and decode the HTML form data.

Servlets can read and set HTTP headers, handle cookies, tracking sessions

CGI cannot read and set HTTP headers, handle cookies, tracking sessions.

Servlets are inexpensive than CGI.

CGI is more expensive than Servlets.


4. Why servlet is mostly used?

- Servlets are mostly used because they are platform-independent Java classes and are compiled to platform-neutral byte code. Java byte code can be loaded dynamically into and run by java enabled webserver.

5. What is called a servlet container? 

-  A servlet container is a part of the Web server that provides network services depends on requests and responses are sent MIME-based requests and responses. It contains and manages servlets through their life cycle.

6. What is MIME Type?

 - MIME is an abbreviation for "Multipurpose Internet Mail Extensions".The “ContentType” response header is known as MIME Type. MIME describes the type of data the file contains. -A MIME type nomenclature includes a type and subtype separated by a forward slash. For example, a popular one is text/html. Here text is called type and html is known as subtype. e.g response.setContentType("text/html");

7. What is a web application and what is it’s directory structure? 

- Web Applications are modules that run on the server to provide both static and dynamic content to the client browser. Apache webserver supports PHP and we can create a web application using PHP. Java provides web application support through Servlets and JSPs that can run in a servlet container and provide dynamic content to the client browser. Java Web Applications are packaged as Web Archive (WAR) and it has a defined structure like the below image. 


8. What are common tasks performed by Servlet Container? 

Servlet containers are also known as web container, for example, Tomcat. Some of the important tasks of servlet container are: 

 • Communication Support: Servlet Container provides an easy way of communication between web clients (Browsers) and the servlets and JSPs. Because of the container, we don’t need to build a server socket to listen for any request from the web client, parse the request and generate a response. All these important and complex tasks are done by container and all we need to focus is on business logic for the applications. 

• Lifecycle and Resource Management: Servlet Container takes care of managing the life cycle of a servlet. From the loading of servlets into memory, initializing servlets, invoking servlet methods, and to destroy them. The container also provides utility like JNDI for resource pooling and management. 

• Multithreading Support: Container creates a new thread for every request to the servlet and provides them request and response objects to process. So servlets are not initialized for each request and save time and memory. 

• JSP Support: JSPs doesn’t look like normal java classes but every JSP in the application is compiled by container and converted to Servlet and then container manages them like other servlets. 

• Miscellaneous Task: Servlet container manages the resource pool, perform memory optimizations, execute garbage collector, provides security configurations, support for multiple applications, hot deployment and several other tasks behind the scene that makes a developer life easier.

 

9. Explain Life Cycle of Servlet? 

- A servlet life cycle can be defined as the entire process from its creation till the destruction. 

The following are the paths followed by a servlet. 

• The servlet is initialized by calling the init () method. 

• The servlet calls service() method to process a client's request. 

• The servlet is terminated by calling the destroy() method.

10. When init() method of servlet gets called? 

- The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.


11. When service() method of servlet gets called?

 - Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. 

12. When doGet() method of servlet to be called? 

- A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method. 

13. When doPost() method of the servlet to be called? 

- A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method. 

14. When destroy() method of servlet gets called? 

- The destroy() method is called only once at the end of the life cycle of a servlet.

15. For what purpose init() method of a servlet is used? 

- The init() method simply creates or loads some data that will be used throughout the life of the servlet.

16. For what purpose destroy() method of a servlet is used? 

- This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. 

17. How to read form data in servlet? 

- Servlets handles form data parsing automatically using the following methods depending on the situation: 

• getParameter(): You call request.getParameter() method to get the value of a form parameter. 

• getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox. 

• getParameterNames(): Call this method if you want a complete list of all parameters in the current request. 

18. What is ServletConfig object? 

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

19. What is ServletContext object? 

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

20. What is difference between ServletConfig and ServletContext? 

- Some of the differences between ServletConfig and ServletContext are: 

• ServletConfig is a unique object per servlet whereas ServletContext is a unique object for complete application.

ServletConfig is used to provide init parameters to the servlet whereas ServletContext is used to provide application level init parameters that all other servlets can use. 

• We can’t set attributes in ServletConfig object whereas we can set attributes in ServletContext that other servlets can use in their implementation. 

21. What is Request Dispatcher? 

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

22. How can we create deadlock situation in servlet? 

- We can create a deadlock in servlet by making a loop of method invocation, just call doPost() method from doGet() method and doGet() method to doPost() method to create deadlock situation in servlet. 

23. What is the use of servlet wrapper classes? 

- Servlet HTTP API provides two wrapper classes 

– HttpServletRequestWrapper and HttpServletResponseWrapper. 

These wrapper classes are provided to help developers with a custom implementation of a servlet request and response types. We can extend these classes and override only specific methods we need to implement for custom request and response objects. These classes are not used in normal servlet programming. 


Recommended Topics-

Servlet life cycle 


Previous
Next Post »