Java Servlet


Like applets (discussed in the previous chapter), servlets are also Java classes. However, unlike applets, which are used to implement client-side of a client-server application, servlets are used at the server-side. They usually run inside a Java-enabled web server and extend its capabilities. This capability is provided by servicing complex requests obtained from the web server, which itself is not capable of handling those requests. Since, servlets are written in Java and Java is an extremely powerful language, even a simple web server bundled with servlets, becomes unquestionably powerful. Consequently, it has become the most popular technology for building interactive web applications.

Note that servlets are not tied to a specific client-server protocol, but are most commonly used with HTTP. That is why, the word servlet is often used to mean HTTP servlet. Execution of a servlet consists of four basic steps [Figure 20.1:]:

  • The client sends a request to the web server.
  • The web server interprets it and forwards it to the corresponding servlet.
  • The servlet processes the request, generates the output (if any), and sends it back to the web server.
  • The web server sends the response back to the client. The browser then displays it on the screen.

Figure 20.1: Execution of a Java Servlet

It runs entirely within the Java Virtual Machine (JVM). Since it runs on the server and may be designed to generate simple output, which even older versions of browsers can interpret, there is no browser incompatibility.


Applets, upon download from the server, run in the client’s browser. They will function properly, provided a proper Java Runtime Environment (JRE) is installed in the client’s browser. If the client uses old fashioned browsers and the applets use advanced features, the browsers may fail to execute them.

Servlets, on the other hand, run on the server machine and usually generate simple HTML codes. So, even an older version of the browser can display these HTML pages correctly.

Applets cannot access local resources such as files and databases. Servlets, if configured properly, have full access to system resources. Therefore, servlets are more powerful than applets. However, since applets and servlets are used at the opposite side of a client-server application, making a direct comparison between them should be avoided.


Numerous parallel technologies to servlets exist. However, each has its own set of problems. Some of the other server-side technologies are discussed briefly here.

3.1. Common Gateway Interface (CGI)

CGI is one of the most common server-side solutions. Although widely used, CGI scripting technology has a number of shortcomings, including platform dependence and lack of scalability. A CGI application is an independent program that receives requests from the web server and sends it back to the web server. Some of the common problems of this technology are as follows:

  • A new process is created every time the web server receives a CGI request. Since a new process is created and initialized, it may result in considerable increase of response time. Servers may also run out of memory if not configured properly.
  • Although, a CGI application can be written in almost every language, most of them are not platform-independent. The common platform-independent language is Perl. Although Perl is a very powerful text processing language, for every request it requires a new interpreter to be started. This increases the overall response time.
  • Since a CGI application is a completely separate process, if it terminates abnormally before responding, the web server has no way to identify what happened there. Consequently, it fails to service the request made by the client.

3.2. Proprietary APIs

Many proprietary web servers have built-in support for server-side programming. Examples include Netscape’s NSAPI, Microsoft’s ISAPI, and O’Reilly’s WSAPI. However, none of these APIs is free and the newer versions may not be backward compatible. Most of these are developed in C/C++ languages and hence can contain memory leaks and core dumps that can crash the web server.

3.3. Active Server Pages (ASP)

Microsoft’s Active Server Pages (ASP) is another technology that supports server-side programming. Unfortunately, the only web server that supports this technology is Microsoft’s Internet Information Server (IIS), which is not free. Although some third-party products support ASP, they are not free either.

3.4. Server-side JavaScript

Server-side JavaScript is another alternative to servlets. However, the only known servers that support it are Netscape’s Enterprise and FastTrack servers. This ties you to a particular vendor and hence, if possible, should be avoided.


Java servlet technology has some distinct advantages over other competent technologies. Truly speaking, except JSP (which is, in fact, an extension to servlet), no technology can compete with servlet technology. The following are some advantages of Java servlet technology.

4.1. Efficient

When a servlet gets loaded in the server, it remains in the server’s memory as a single object instance. Each new request is then served by a lightweight Java thread spawned from the servlet. This is a much more efficient technique than creating a new process for every request, as done in CGI. Servlets also have more alternatives for optimizations, such as caching the previous computation and keeping database/socket connections open etc.

4.2. Persistent

Servlets can maintain the session by using the session tracking/cookies, a mechanism that helps them track information from request to request. Critical information can also be saved to a persistent storage and can be retrieved from it when the servlet is loaded the next time.

4.3. Portable

Servlets are written in Java and so they are portable across operating systems and server implementations. This allows servlets to be moved across new operating systems seamlessly. We can develop a servlet on a Windows machine running the Tomcat or any other server and later we can deploy that servlet effortlessly on any other operating system such as a Unix server running an iPlanet/ Netscape application server. So, servlets are truly Write Once Run Anywhere (WORA) programs.

4.4. Robust

Since servlets can use the entire rich Java library, they can provide extremely robust solutions. Java has a very powerful exception handling mechanism and provides a garbage collector to handle memory leaks. It also has a very large and rich class library with network and file support, database access, distributed object components, DOM support, security, utility packages, etc.

4.5. Extensible

Servlets are nothing but Java technology, which is popular for its well-known features such as platform independence, garbage collection, exception handling, and extremely powerful utility packages. Servlets can also make use of Java’s object orientation features, especially inheritance.

560 advanced java programminig

A sub class inherits all the features of its super class. Additional features and methods can be added and hence it is easily extendable.

4.6. Secure

Servlets run in a Java-enabled web server. So, they can use security mechanisms from both the web server and the Java Security Manager.

4.7. Cost-effective

There are a number of free web servers available [Table 20.1:] for personal and commercial use. Java Development Kit (JDK) is also free and can be downloaded from So, applications can be developed practically without any cost.

Table 20.2: also shows some other add-on software that support Java servlet technology.


Servlet architecture consists of two packages: javax.serviet and javax.serviet.http. The first package contains top-level interfaces and classes that are used and extended by all other servlets either directly or indirectly. The second package is provided for servlets that can handle HTTP requests. Figure 20.2: shows the Servlet architecture.

The top-level interface of the servlet architecture is javax.serviet.Serviet. It provides the basic functionalities of all the servlets that are created by implementing this interface directly or indirectly. For example, the init() method initializes the servlet, the service() method serves the client request, and the destroy() method shuts the servlet down.


The container in which the servlet has been deployed supervises and controls the life cycle [Figure 20.3: ] of a servlet. Typically, this container is nothing but a web server. When the container receives a request from a client and determines that the request should be handled by a servlet, it performs the following steps.

  • If an instance of the target servlet does not exist, the container does the following:
    • Finds and loads the servlet class
    • Creates an instance of the servlet class
    • Calls the init() method on this servlet instance to initialize it
  • The container then invokes the service() method on the servlet (newly created or existing servlet), passing a ServletRequest type object and a ServletResponse type object.
  • If the container decides that the servlet is no longer needed, it removes and finalizes the servlet by calling the servlet’s destroy()

A servlet, from its creation to destruction, undergoes a number of states [Figure 20.3:]:

  • Instantiated or born
  • Initialized
  • Ready to service
  • Servicing
  • Not ready to service
  • Dead or destroyed

The entire period when a servlet remains alive is called life cycle of the servlet. The class Servlet provides a framework where our servlets can run. It has a set of methods to control and supervise the smooth execution of sevlets [Figure 20.2:]. These methods (also called life cycle methods) are called in a specific order during a servlet’s entire life cycle. A servlet must override these methods to do a designated task.

Even though, life cycle methods are called automatically by the container, we should have sound knowledge about when they are called and what we can do with these methods. The following is a brief description of these life cycle methods.

6.1. init()

A servlet’s life begins here. This method is called only once by the web container, just after it instantiates and loads the servlet. So, it is a good idea to read the persistent configuration data, initialize resources that will be used during the rest of the time, and perform any other one-time activity by overriding the init() method. Once the servlet is initialized, it becomes ready to handle the client’s request. The prototype of the init() method is as follows:

void init(ServletConfig)

The web container passes a ServietConfig object, which contains the startup configuration for this servlet such as initialization parameters. To serve requests, this init() method must complete and return successfully.

6.2. service()

This is the most important method, whose signature is as follows:

void service(ServletRequest request, ServletResponse response)

This method gets called each time the web container receives a request intended for this servlet. The web container calls the serviced method on a servlet with two objects: a ServletRequest type object request and a ServletResponse type object response. The request object encapsulates the communication from the client to the server, while the response object encapsulates the communication from the servlet back to the client.

The ServletRequest interface provides methods to retrieve information sent by the clients. Similarly, the ServletResponse interface provides methods to send data to the clients.

6.3. destroy()

The method signature is as follows:

void destroy();

This method gets called when the web container uninstalls the servlet. This method is overridden to clean up the resources that were allocated to this servlet. It also makes sure that any persistent state is synchronized with the servlet’s current in-memory state.

6.4. Other Methods

The javax.serviet.Serviet interface also provides the following methods to inspect the properties of a servlet at runtime.

ServletConfig getServletConfig();

Returns a ServletConfig object, which contains the initialization parameters and startup configuration used for this servlet. The returned object is the object that was passed to the init() method during the servlets instantiation.

String getServletInfo();

Returns a String object containing information about the servlet, such as its version, author, copyright, etc.


The class javax.servlet.GenericServlet implements the javax.servlet.Servlet interface and, for convenience, the javax.servlet.ServletConfig interface. A servlet class is usually created by extending either the GenericServlet class or its descendant javax.servlet.http.HttpServlet class unless the servlet needs another class as a parent. If a servlet does need to be a subclass of another class, it must implement the Servlet interface directly. This would be necessary when, for example, RMI or CORBA objects act as servlets. In such a case, the servlet class must implement all the methods of the Servlet interface.

The GenericServlet class defines (as its name suggests) a generic protocol-independent servlet, in the sense that it can be extended to provide implementation of any protocol, such as HTTP, FTP, and SMTP.

The GenericServlet class was created to make writing servlets easier. It provides implementations of the life cycle methods init() and destroy(), as well as methods in the ServletConfig interface. The servlet writer has to implement only the serviced method. This is required because it is the method that is called every time a client requests for the servlet. The prototype of this method is shown as follows.

public void service(javax.servlet.ServletRequest request,

javax.servlet.ServletResponse response)

throws javax.servlet.ServletException,;

This method expects two arguments. The ServletRequest type object request encapsulates the client request and is used to extract information from the client’s request. On the other hand, ServletResponse type object response contains information to be sent back to the client.


The HttpServlet class extends GenericServlet and provides a framework for handling HTTP requests. Servlets that want to handle only HTTP requests are usually created by extending this class. It provides an implementation for the serviced method. So, you do not have to implement the serviced method if you extend the HttpServlet class. The serviced method in the HttpServlet class reads the method type stored in the HTTP request message and invokes a specific method based on this value. Specifically, if the method type is GET, it calls doGet(); if the method type is POST, it calls doPost(); and so on. These are the methods that we need to override. Default implementations of these methods are also provided. The list of all such methods is given in Figure 20.4:.

Each of these methods takes two arguments: an HttpServietRequest type object and an HttpServietResponse type object. The following is the prototype of the doGet() method:

void doGet(HttpServletRequest request, HttpServietResponse response)

The HttpServietRequest interface extends the ServietRequest interface and provides all the functionalities of the ServietRequest interface. Additionally, it provides methods to retrieve HTTP- specific information such as headers, method, URL, cookies sent, etc.

The HttpServietResponse interface extends the ServietResponse interface and provides all the functionalities of the ServietResponse interface. Additionally, it provides methods to send HTTP- specific information back to the client.

Servlets created by extending the HttpServiet class can handle multiple simultaneous requests. For each request, a thread is created, which runs its service() method. If you want to create a single-threaded servlet, your servlet must also implement the SingieThreadModei interface as follows:

pubiic ciass SimpieServiet extends HttpServiet implements SingieThreadModei {}

The interface SingieThreadModei does not define any method. It is used to merely declare that the servlet should use a single thread.

Source: Uttam Kumar Roy (2015), Advanced Java programming, Oxford University Press.

Leave a Reply

Your email address will not be published. Required fields are marked *