Table of Contents
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver.
Learn Coding in your Language! Enroll Here!
Properties of Servlets are as follows
- Servlets work on the server-side.
- Servlets are capable of handling complex requests obtained from the webserver.
Servlet Architecture
1: What is the default value of a boolean in Java?
Execution of Servlets basically involves six basic steps:
- The clients send the request to the webserver.
- The web server receives the request.
- The web server passes the request to the corresponding servlet.
- The servlet processes the request and generates the response in the form of output.
- The servlet sends the response back to the webserver.
- The web server sends the response back to the client and the client browser displays it on the screen.
Stages of the Servlet Life Cycle
The Servlet life cycle mainly goes through four stages,
- Loading a Servlet.
- Initializing the Servlet.
- Request handling.
- Destroying the Servlet.
- Loading a Servlet: The first stage of the Servlet lifecycle involves loading and initializing the Servlet by the Servlet container. The Web container or Servlet Container can load the Servlet at either of the following two stages :
- Initializing the context, on configuring the Servlet with a zero or positive integer value.
- If the Servlet is not preceding stage, it may delay the loading process until the Web container determines that this Servlet is needed to service a request.
The Servlet container performs two operations in this stage :
- Loading :Loads the Servlet class.
- Instantiation :Creates an instance of the Servlet. To create a new instance of the Servlet, the container uses the no-argument constructor.
- Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet container initializes the instantiated Servlet object. The container initializes the Servlet object by invoking the init(ServletConfig)method which accepts ServletConfig object reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only once, immediately after the Servlet.init(ServletConfig) object is instantiated successfully. This method is used to initialize the resources, such as JDBC datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing the ServletException or UnavailableException.
- Handling request: After initialization, the Servlet instance is ready to serve the client requests. The Servlet container performs the following operations when the Servlet instance is located to service a request :
- It creates the ServletRequestand ServletResponse In this case, if this is a HTTP request, then the Web container creates HttpServletRequest and HttpServletResponse objects which are subtypes of the ServletRequest and ServletResponse objects respectively.
- After creating the request and response objects it invokes the Servlet.service(ServletRequest, ServletResponse) method by passing the request and response objects.
The service() method while processing the request may throw the ServletException or UnavailableException or IOException.
- Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it performs the following operations,
- It allows all the threads currently running in the service method of the Servlet instance to complete their jobs and get released.
- After currently running threads have completed their jobs, the Servlet container calls the destroy()method on the Servlet instance.
After the destroy() method is executed, the Servlet container releases all the references of this Servlet instance so that it becomes eligible for garbage collection.
Learn to code from industry experts! Enroll here
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet :
- init()
- service()
- destroy()
Let’s look at each of these methods in details:
init() method: The Servlet.init() method is called by the Servlet container to indicate that this Servlet instance is instantiated successfully and is about to put into service.
//init() method
public class MyServlet implements Servlet{
public void init(ServletConfig config) throws ServletException {
//initialization code
}
//rest of code
}
service() method: The service() method of the Servlet is invoked to inform the Servlet about the client requests.
- This method uses ServletRequestobject to collect the data requested by the client.
- This method uses ServletResponseobject to generate the output content.
// service() method
public class MyServlet implements Servlet{
public void service(ServletRequest res, ServletResponse res)
throws ServletException, IOException {
// request handling code
}
// rest of code
}
destroy() method: The destroy() method runs only once during the lifetime of a Servlet and signals the end of the Servlet instance.
//destroy() method
public void destroy()
As soon as the destroy() method is activated, the Servlet container releases the Servlet instance.
Servlet Life Cycle
Servlet life cycle can be defined as the stages through which the servlet passes from its creation to its destruction.
The servlet life cycle consists these stages:
- Servlet is borned
- Servlet is initialized
- Servlet is ready to service
- Servlet is servicing
- Servlet is not ready to service
- Servlet is destroyed
Life cycle methods
Life cycle methods are those methods which are used to control the life cycle of the servlet. These methods are called in specific order during the servlets’s entire life cycle.
The class Servlet provides the methods to control and supervise the life cycle of servlet. There are three life cycle methods in the Servlet interface. There are as follows:
- init() method :
- A servlet’s life begins here .
- This method is called only once to load the servlet.Since it is called only once in it’s lifetime,therefore “connected architecture” code is written inside it because we only want once to get connected with the database.
Now Question Arises is that:-
Why can’t we write connected architecture code inside the constructor, since constructor also run only once in it’s entire life?
Ans. Suppose if the connection doesn’t get established, then we can throw an exception from init() and the rest of the steps stop executing. But in the constructor we can’t use, throw in it’s prototype otherwise it is an error. - This method receives only one parameter, i.e ServletConfig
- This method has the possibility to throw the ServletException.
- Once the servlet is initialized, it is ready to handle the client request.
- The prototype for the init() method:
public void init(ServletConfig con)throws ServletException{ }
Below is a sample program to illustrate Servlet in Java:
// Java program to show servlet example
// Importing required Java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
// Extend HttpServlet class public class AdvanceJavaConcepts extends HttpServlet { private String output;
// Initializing servlet public void init() throws ServletException { output = “Advance Java Concepts”; }
// Requesting and printing the output public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType(“text/html”); PrintWriter out = resp.getWriter(); out.println(output); }
public void destroy() { System.out.println(“Over”); } } |
Grab the opportunity to learn Python with Entri! Click Here
Why is it important to choose Entri?
- Excellent online platform for all the Competitive Exams.
- Provides updated materials created by the Entri Experts.
- Entri provides a best platform with full- length mock tests including previous year question papers.
- You can download the app for free and join the required classes.
- Entri wishes you all the best for your examinations and future endeavours.
“YOU DON’T HAVE TO BE GREAT TO START, BUT YOU HAVE TO START TO BE GREAT.”