Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

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

Updated on 09 August, 2024

11.1K+ views
16 min read

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. 

The Servlet container manages the whole Servlet life, and it uses the javax.servlet.Servlet interface. This interface understands the Servlet object and also manages it. Hence, before creating a Servlet object, it is vital to understand the servlet life cycle that explains how the Servlet container handles the Servlet object.

Check out our free courses to get an edge over the competition.

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.

Check out upGrad’s Java Bootcamp

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.

Check out upGrad’s Full Stack Development Bootcamp (JS/MERN)

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

Stages of the Servlet Life Cycle:

The servlet life cycle chiefly goes through the following stages:

 Loading a Servlet

  1. Initializing the Servlet

 Request handling

  1. Destroying the Servlet

 Let’s go through the details of these stages:

 Loading a Servlet:

The first stage of the life cycle of servlet loads and initializes the Servlet using the Servlet container. The Servlet Container or Web container can load the Servlet at any of these two stages:

  1. a) Initializes the context on configuring Servlet using a zero or positive integer value.
  2. b) If the Servlet doesn’t exist in the stage, it might delay the loading procedure until the Web container decides that the particular Servlet is required to serve a request.

At this stage, the Servlet container does two operations:

  • Loading: This stage of the life cycle of servlet in java loads the Servlet class.
  • Instantiation: This stage creates the Servlet instance. The container uses the no-argument constructor to create the Servlet’s new instance in the life cycle of servlet.

 Initializing a Servlet: Once the Servlet is instantiated, the Servlet container will initialise the instantiated Servlet object. It does this by calling the Servlet.init(ServletConfig) method that accepts ServletConfig object reference in the form of parameter.

The Servlet container calls the Servlet.init(ServletConfig) method only once, instantly after the Servlet.init(ServletConfig) object is successfully instantiated. Moreover, this method can initialize the resources like the JDBC data source.

If the Servlet fails to initialize, it notifies the Servlet container by raising the ServletException or UnavailableException.

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.

Servlet container calls the Servlet.init() method to denote that this Servlet instance is successfully instantiated and is ready for the service.

  Syntax of init() method is given as :

public void init(ServletConfig config) throws ServletException {

           //initialization code

}

Handling request: After initializing a Servlet, the Servlet instance is prepared to handle the client requests. When the Servlet instance is found to serve a request, the Servlet container does the following operations:

It creates the ServletResponse and ServletRequest objects. If this is found as an HTTP request, the Web container creates HttpServletResponse and HttpServletRequest objects which are the subtypes of the ServletResponse and ServletRequest objects, respectively.

After making the request and response objects, the Servlet.service(ServletRequest, ServletResponse) method is called by passing the request and response objects.

When processing the request, the service() method may raise the IOException, ServletException, or UnavailableException.

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.
  • To inform the Servlet regarding the client’s requests.

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.

  • Using the ServletRequest object in servlet life cycle in java, this method collects the data requested by the client.
  • Using the ServletResponse object, this method produces the output content.
  1. Destroying a Servlet: When a Servlet container agrees to destroy the Servlet, it does the following operations:

It allows all the currently operating threads in the service method of the Servlet instance to accomplish their jobs.

After operating threads have finished their jobs, the Servlet container invokes the destroy() method located on the Servlet instance.

When the execution of destroy() method completes, the Servlet container frees up this Servlet instance’s all references. Hence, it becomes qualified for garbage collection.

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.

What makes the destroy() method stand out from other servlet life cycle methods is that it operates only once throughout the Servlet’s lifetime. Moreover, it indicates the Servlet instance’s termination. When the destroy() method is triggered, the Servlet container frees up the Servlet instance.

The signature of the destroy() method  is

public void destroy(){

      // Finalization code

}

Also Read: Servlet vs JSP

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

How are Servlet Life Cycle Methods called?

The method that servlet containers implement for servlet life-cycle events is called servlet life cycle methods (also called container callback methods).

In servlet workflow and architecture, we discussed how the servlet containers perform different operations on the servlet components. Let’s check what happens when the first request is provided to the servlet component with reference to the servlet life cycle methods.

  • The Servlet container prepares one set of ServletResponse and ServletRequest objects for the current request.
  • The Servlet container loads the Servlet class from the WEB-INF/classes folder and instantiates that object through the 0-param constructor.
  • The Servlet container creates an instantiation event and calls init(ServletConfig cg) method on the servlet class object. This servlet class object will be assigned with the ServletConfig object.
  • Servlet container starts/create one thread specifying the current request and raises “request processing event”.
  • Servlet container calls the service(ServletRequest req, ServletResponse resp) method on the servlet class object.
  • The service(-,-) method delivers the generated output to the browser using the web server and response object.
  • The Servlet container destroys the thread which was created for the current request. Also, it destroys the ServletRequest, ServletResponse objects of the current request.

Servlet Life Cycle Events:

The life cycle of servlet in java has the following events:

 Servlet Instantiation Event:

This event is raised when the servlet container creates the servlet class object. It is only raised once for a servlet component.

Request Processing Event:

It is raised when the servlet container prepares the servlet class object to process the request. Moreover, it is raised for every request.

Destruction Event:

It is raised when the servlet container is ready to destroy a servlet class object. It is raised only once for a servlet component.

 What happens if the main(-) method is placed in the servlet component?

The Servlet container implements the servlet component using the methods of the servlet life cycle in java. The main(-) method is not a life cycle method. Hence, it will not be executed in the servlet life cycle. But it will be executed only if it is explicitly called from any servlet life cycle method; otherwise, it will be considered an ordinary method.

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  

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

Source

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

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

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 Executive PG Program 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.

Frequently Asked Questions (FAQs)

1. What are servlets in Java?

The servlet API is the foundation for server-side Java. It enables Java code to run on the server (as opposed to the browser) and interact with HTTP requests to deliver content and manipulate data, much like a CGI script. In other words, they are just chunks of code that your web server can run to provide dynamic content. Servlets are typically used to provide dynamic content, such as a page of search results or a chat room. Servlets are Java objects which extend the HttpServlet class. They are used to build web applications and the HttpServlets are the ones which are used by the web server to deliver JavaServer Pages.

2. What is a servlet life cycle in Java?

The Servlet life cycle is divided into four distinct phases: 1. init() - This is a special method where initialization can be done. For example, you can create database connections, fetch information from your database during this phase. When you do this, you're doing a little bit of bootstrapping. This is a safe place to do this since you don't want to do any initialization more than once (since the container will destroy the servlet if it starts a new instance). 2. service() - This is the phase where you do the work. In a servlet, you can do get requests, generate dynamic content and send it back to the user. This is the phase where you process the request and write your response back to the user. 3. destroy() - This is where the servlet is going to be destroyed. This is where you need to do any cleanup. For instance, you might want to close your database connections in this phase. 4. shutdown() - This is the last phase where you can close everything else. For instance, you can stop a timer, release any other resources, etc.

3. What is the servlet architecture?

In the servlet architecture, a servlet is an application component that generates dynamic content for an HTTP web server and an HTTP browser. A servlet is a Java program that receives requests from the HTTP server and sends back responses. A servlet is a small program that runs within the container and provides various services to the applications. A servlet can be written in Java or in JSP and it is with the help of a servlet that the JSP technology works. A servlet can be considered as the heart of a Java based web application.

RELATED PROGRAMS