Programs

Servlet Life Cycle in Java: Methods, Architecture, Comparison & Setup

Introduction  

Servlets yield a method that is not only component-based and platform-independent but is also very much supportive for building web-based applications. Servlets have access to the java APIs and JDBC API to access databases. In the case of Java Servlets, although there are no restrictions in terms of the performance of the CGI (Common Gateway Interface) program, there still exist some disadvantages. 

What is Servlet?

Servlet is a technology that is very much beneficial for creating dynamic web pages. It acts as an intermediate layer between the web browser and HTTP clients or servers. With the help of servlets, at first, we collect the inputs from the users and then create web pages dynamically. Servlet extends the capabilities of servers and host applications. Servlets extend the capabilities of the servers and also respond to any type of requests for users.

Source

CGI vs Servlets

Before servlets, CGI was used broadly. CGI is a way to pass the request received from the user to an application program. Although CGI is a way for a web server, it also gets the response from the browser (client). When the user requests a web page to the browser, the server sends it back to them.

When a client wants to fill out a form on a web page and try to send it again, it gets processed by the application program. The server passes the information to a small web application program. This program first processes the data and then sends it back via a confirmation message.

Servlet Life Cycle Methods in Brief

There are mainly three life cycle methods of a servlet, which we can describe as:

  1. init()
  2. service()
  3. destroy()

Source

Servlet Architecture

  • Firstly, it reads the data sent by clients. Then, it inserts an HTML form in a web page and then sends the requests sent by clients.
  • After that, the servlet processes the data and connects to a database management system, executing RMI by invoking web services.
  • After processing, the documents can be sent in text and gif formats.
  • Finally, it sends the HTTP to the client.

Source

Now we will discuss these methods in details

1. init()

The init() method is called only once after the servlet instance is created. At first, it initialises the servlet. Servlet.init() indicates that the servlet instance was created successfully.

 Syntax of init() method is given as :

public void init(ServletConfig config) throws ServletException {

           //initialization code

}

2. service()

Whenever the servlet receives the request, the web container calls the service() method.

  • To collect the data requested b
  • y the client, the service request object is used.
  • To generate the output content, the ServletResponse object is used.

Signature of service() method is given as:

public void service(ServletRequest request , ServletREsponse response)

            throws ServletEXception , IOException {

          //request handling code

}

The service() method uses doGet, doPost, doPut, doDelete and many other methods.

3. destroy()

The user calls the destroy() method at least once in a life cycle of a servlet. It is used to terminate database connection, to release the allocated memory and resources. It also helps in clean-up purposes, and garbage collection is associated with this.

The signature of the destroy() method  is

public void destroy(){

      // Finalization code

}

Also Read: Servlet vs JSP

Environment Setup of a Servlet

To create a Servlet application, at first, we need to follow some steps like installing Tomcat Server, which gets described below-

1. Creating a Directory Structure 

Source

First, we need to create the above directory structure inside a directory named Apache – Tomcat\webapps directory. We need to keep all HTML, static files, images under the web application creating a folder. The servlets must be kept in the class folder. Lastly, the web.xml file should be under the WEB-INF folder.

2. Creating a Servlet

There are three different ways by which we can create a servlet.

  1. By implementing the Servlet interface.
  2. By extending the GenericServlet class.
  3. It is necessary to extend the HTTP servlet class.

A servlet can be mainly formed if we can extend the httpServlet abstract class.

3. Compiling the Servlet

For compiling the servlet, a JAR file is required –

  1. By setting the classpath.
  2. By pasting the jar in JRE/lib/ext folder.

4. Create Deployment Descriptor

DD can be defined as an XML file that is used by web-based servers so that

they can run servlets with ease. DD is used for several important purposes.

  1. By mapping the URL to the Servlet class.
  2. By initialising parameters.
  3. By defining the Error page.
  4. By security roles.
  5. By declaring tag libraries.

5. Start the Server

To start the Apache Tomcat server, we need to double click on the startup.bat file under apache-tomcat/bin directory, and it will start working.

6. Starting Tomcat Server for the First Time

To start Tomcat Server for the first time, we need to set JAVA_HOME in the Environment variable. The following steps are mentioned below. Right Click on My Computer, and we need to go to Properties.

Source

  1. Next, we will go to Advanced Tab, and we need to click on the Environment Variables button.

Source

  1. Therefore, we will click on the New button and enter JAVA_HOME inside the Variable name text field and the path of JDK inside the Variable value text field. Then, we need to save it by clicking, OK.

Source

7. Running the Servlet Application

When we run the servlet button, it will look like –

After opening the browser, we need to type http:localhost:8080/First/hello

Checkout: Java Developer Salary in India

Servlet Request Interface

ServletRequest aims to supply the client with authentic pieces of information about a servlet that

includes content type, length, parameter values, and many more.

Methods 

1. getAttribute(String)

Returns the value of attributes as requested, if attributes have no existence

then returns NULL.

2. getAttributeNames()

It returns the names of the present attributes that are requested by the clients.

3. getCharacterEncoding()

Returns some set of characters.

4. getContentLength()

Returns the requested data entity size.

5. getContentType()

At first, it requests the object’s identity. If not found, it returns a NULL value.

6. getInputStream()

Returns a binary stream of data received by the client and then returns the strings.

7. getParameter(String)

Returns a string of the parameters.

8. getParameterNames()

It returns the parameter names.

9. getParameterValues(String)

It returns the values of the parameters. They always exist in the form of a string.

10. getProtocol()

It returns the protocol and version in the form <protocol>/<major version>.<minor version>.

11. getReader()

It returns a buffered reader to read the text in the request body.

12. getRealPath(String)

avoids the virtual path and returns the real path.

13. getRemoteAddr()

It returns the IP address.

14. getRemoteHost()

It returns the completely structured hostname of the agent.

15. getScheme()

It returns the URL used in the request.

16. getServerName()

It returns the hostname of the server.

17. getServerPort()

It returns the port number.

18. setAttribute(String, Object)

This method accumulates an attribute for any kind of requests.

Servlet Response

ServletResponse invokes an object, and the response of various users is recorded. The web container is responsible for all these activities. The step to create this is very much important. The step is to create an object.

Now let us talk aboutServletConfig and ServletContext below in detail.

ServletConfig

1. Web container creates the config object based on the initialisation parameters.

2. One ServletConfig per Servlet must be present.

Methods

1. Equals(Object)

checks if the current object has equal value with the given object.

2. GetHashCode()

Works as the default hash function.

3. GetType()

Returns the Type of the current instance.

4. MemberwiseClone()

If we invoke this object, a shallow copy can be created. It refers to the present object by default.

5. ToString()

Returns a string, which represents the current object.

ServletContext

Let us discuss ServletContext below:

  1. It is very much necessary to make the reference object accessible to each and every Servlet of the web application.
  2. The reference object is actually the runtime implementation of these.

The two types of servlets can be defined as:

1. Generic Servlets 

We refer to the Generic servlets as independent of protocols, and also, it is required to invoke it by overriding. We can invoke generic servlets in three ways –

  • HTML File 

    We can create a very uncomplicated HTML file that can look like WebContent/index.html.

  • Java Class File 

A generic servlet can be created by extending the GenericServlet class. If we can create a simple new class file, then we can rename it as generic. The file path looks like:/  javaResouces/src/default package/generic.java.

  • XML File 

    We can find this file in the path WebContent/WEB-INF/web.xml. We can map the servlet with a specific URL.

2. HTTP servlet 

This type of servlets is nothing but an extension of Servlet classes. Though it is HTTP dependent, it sets some rules which help the web browser and servers to communicate, and the HTTP servlet can also override doGet() or doPost() methods. Also, it can override both methods.

Advantages of Servlets

Now let us see some advantages of servlets –

  1. Performance is outstanding.
  2. Servlets can execute within the address space of a server. As a result, we can say that it is unnecessary to create a separate address space to handle the client request.
  3. They are platform-independent and mainly component-based.
  4. Servlets are secured as the security manager sets some restrictions to protect the resources and data.
  5. While working, users don’t need to worry about freeing memory as a garbage allocation technique.
  6. Servlets provide full functionality as all the libraries are available. It can easily communicate with applets and other mechanisms.

Source

Disadvantages of Servlets

The limitations of servlets are discussed as –

  1. Only one servlet can be loaded in the JVM at a time. So, we can say that it matters about the number of requests.
  2. When there is a request, there can be a thread only. No process should be present there.
  3. Designing a servlet is costly, and sometimes, it is quite problematic.
  4. We need other setups in the browser like JRE (Java Runtime Environment) on the server to run servlets.

Also Read: Java Project Ideas & Topics

Conclusion

In this modern era of the digital world, technology and the internet have become the driving force of all. The internet is restless. Each and every second, it is busy to transfer large amounts of data.

But due to the bulk transfer of data, the internet slows down, as we need speed also. So, the dynamic sites get created by software developers. These sites get changed and updated at every moment. To know further about the Servlets in Java and development, check out upGrad’s PG Diploma in Full-stack Software Development and kick start your journey.

The main motive of this article is to provide the readers with a basic concept of servlets so that they can obtain a fundamental idea about servlets.

Land on Your Dream Job

UPGRAD AND IIIT-BANGALORE'S PG DIPLOMA IN FULL STACK DEVELOPMENT
APPLY NOW

Leave a comment

Your email address will not be published.

Accelerate Your Career with upGrad

Our Popular Software Engineering Courses

×