WHAT IS SERVLET ?

Koteswararao
7 min readMay 3, 2023

--

Introduction to Servlet

Servlet is basically a JAVA program that runs particularly inside JVM or {JAVA Virtual Machine} on the Web server. It is generally used to make/create Dynamic web applications and web pages.

It is a technology that is used to develop the Dynamic web applications. It uses the JAVA language for its work of developing web pages. This technology is secured, scalable, and robust because it uses JAVA technology which provides the same features.

Working of Servlet

Before I start explaining how the servlet works, lets get familiar with these three terms.
Web Server: it can handle HTTP Requests send by clients and responds the request with an HTTP Response.

Web Application(webapp): I would refer this as webapp in this guide. Basically the project is your web application, it is the collection of servlets.

Web Container: Also known as Servlet Container and Servlet Engine. It is a part of Web Server that interacts with Servlets. This is the main component of Web Server that manages the life cycle of Servlets.

You will find that some part of this guide is already covered in the servlet life cycle guide, however this guide focuses on the working of a servlet application (webapp)
rather then the steps of life cycle. I would highly recommend you to read this to have in depth knowledge of how the servlet actually works.

How Servlet Works?

1) When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the servlets. During this step Servlet container creates ServletContext object. ServletContext is an interface that defines the set of methods that a servlet can use to communicate with the servlet container.

Note: There is only one ServletContext per webapp which is common to all the servlets. ServletContext has several useful methods such as addListener(), addFilter() etc. For now I am not explaining them as I will cover them in a separate text about ServletContext.

2) Once the servlet is loaded, the servlet container creates the instance of servlet class. For each instantiated servlet, its init() method is invoked.

3) Client (user browser) sends an Http request to web server on a certain port. Each time the web server receives a request, the servlet container creates HttpServletRequest and HttpServletResponse objects. The HttpServletRequest object provides the access to the request information and the HttpServletResponse object allows us to format and change the http response before sending it to the client.

The servlet container spawns a new thread that calls service() method for each client request. The service() method dispatches the request to the correct handler method based on the type of request.
For example if server receives a Get Request the service() method would dispatch the request to the doGet() method by calling the doGet() method with request parameters. Similarly the requests like Post, Head, Put etc. are dispatched to the corresponding handlers doPost(), doHead(), doPut() etc. by service() method of servlet.

Life Cycle of Servlet

Servlet life cycle contains five steps: 1) Loading of Servlet 2) Creating instance of Servlet 3) Invoke init() once 4) Invoke service() repeatedly for each client request 5) Invoke destroy()

For those who are wondering what is instance and invoke means: Instance and objects are same thing. Invoking a method means calling a method, it is just a fancy word that we use in programming world in place of calling :)

Let’s back to the main topic. Here are the five steps of servlet life cycle.

Step 1: Loading of Servlet
When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the servlets.

Step 2: Creating instance of Servlet
Once all the Servlet classes loaded, the servlet container creates instances of each servlet class. Servlet container creates only once instance per servlet class and all the requests to the servlet are executed on the same servlet instance.

Step 3: Invoke init() method
Once all the servlet classes are instantiated, the init() method is invoked for each instantiated servlet. This method initializes the servlet. There are certain init parameters that you can specify in the deployment descriptor (web.xml) file. For example, if a servlet has value >=0 then its init() method is immediately invoked during web container startup.

You can specify the element in web.xml file like this:

<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.beginnersbook.MyServletDemo</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

Now the init() method for corresponding servlet class com.beginnersbook.MyServletDemo would be invoked during web container startup.

Note: The init() method is called only once during the life cycle of servlet.

Step 4: Invoke service() method
Each time the web server receives a request for servlet, it spawns a new thread that calls service() method. If the servlet is GenericServlet then the request is served by the service() method itself, if the servlet is HttpServlet then service() method receives the request and dispatches it to the correct handler method based on the type of request.

For example if its a Get Request the service() method would dispatch the request to the doGet() method by calling the doGet() method with request parameters. Similarly the requests like Post, Head, Put etc. are dispatched to the corresponding handlers doPost(), doHead(), doPut() etc. by service() method of servlet.

Step 5: Invoke destroy() method
When servlet container shuts down(this usually happens when we stop the web server), it unloads all the servlets and calls destroy() method for each initialized servlets.

Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests.

Sample Code

Following is the sample source code structure of a servlet example to show Hello World −

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {
// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Set response content type
response.setContentType("text/html");

// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {
// do nothing.
}
}

Advantages of Java Servlets

  1. Portability
  2. Powerful
  3. Efficiency
  4. Safety
  5. Integration
  6. Extensibilty
  7. Inexpensive

Each of the points are defined below:

Portability
As we know that the servlets are written in java and follow well known standardized APIs so they are highly portable across operating systems and server implementations. We can develop a servlet on Windows machine running the tomcat server or any other server and later we can deploy that servlet effortlessly on any other operating system like Unix server running on the iPlanet/Netscape Application server. So servlets are write once, run anywhere (WORA) program.

Powerful
We can do several things with the servlets which were difficult or even impossible to do with CGI, for example the servlets can talk directly to the web server while the CGI programs can’t do. Servlets can share data among each other, they even make the database connection pools easy to implement. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to request. It can do many other things which are difficult to implement in the CGI programs.

Efficiency
As compared to CGI the servlets invocation is highly efficient. When the servlet get loaded in the server, it remains in the server’s memory as a single object instance. However with servlets there are N threads but only a single copy of the servlet class. Multiple concurrent requests are handled by separate threads so we can say that the servlets are highly scalable.

Safety
As servlets are written in java, servlets inherit the strong type safety of java language. Java’s automatic garbage collection and a lack of pointers means that servlets are generally safe from memory management problems. In servlets we can easily handle the errors due to Java’s exception handling mechanism. If any exception occurs then it will throw an exception.

Integration
Servlets are tightly integrated with the server. Servlet can use the server to translate the file paths, perform logging, check authorization, and MIME type mapping etc.

Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it stands today, the servlet API support Http Servlets, but in later date it can be extended for another type of servlets.

Inexpensive
There are number of free web servers available for personal use or for commercial purpose. Web servers are relatively expensive. So by using the free available web servers you can add servlet support to it.

What are disadvantages of servlet?

There are some problems with Servlet programming.

For non-java programmers Servlet is not suitable as they need to have extensive knowledge of Java Servlet. The presentation logic (HTML code) will be mixed up with Java code (pw.println()). Lots of coding is written inside pw.println() to write html code. Modification done in one code may affect another code. Writing HTML code in Servlet programming is a complex process and it makes Servlet looks bulky.

In Servlet programming implicit objects are there but we need to write some additional code to get them access. Modifications done in source code of servlet program will be effected only after recompilation and reloading of the web application in case of most of servers. Programmers should explicitly take care of exception handling. Servlet programming is not thread safe by default. So we need to write additional codes to make the Servlet program thread safe.

--

--