Вы находитесь на странице: 1из 4

Advanced Java Tutorial: Introduction to Servlets

A servlet is a Java programming language class that is used to extend the capabilities of servers that host
applications accessed by means of a request-response programming model. Although servlets can respond to any
type of request, they are commonly used to extend the applications hosted by web servers.
Servlet can be described as follows:

 Servlet is a technology which is used to create a web application.

 It is an API that provides many interfaces and classes including documentation.


 Servlet is an interface that must be implemented for creating any Servlet.
 It is also a class that extends the capabilities of the servers and responds to the incoming requests. It can
respond to any requests.

Advanced Java Tutorial: Servlet Life Cycle

The entire life cycle of a Servlet is managed by the Servlet container which uses the javax.servlet.Servlet interface
to understand the Servlet object and manage it.

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.
Let’s look at each of these stages in details:

1.Loading a Servlet: The first stage of the Servlet life cycle 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 :

1.Initializing the context, on configuring the Servlet with a zero or positive integer value.

2.If the Servlet is not preceding the stage, it may delay the loading process until the Web container
determines that this Servlet is needed to service a request.

2.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 a parameter.

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

1.It creates the ServletRequest and ServletResponse. In this case, if this is an HTTP request
then the Web container creates HttpServletRequest and HttpServletResponse objects which
are subtypes of the ServletRequest and ServletResponse objects respectively.

4.Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it performs the following
operations,

1.It allows all the threads currently running in the service method of the Servlet instance to
complete their jobs and get released.

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

Now that you have understood the basics of a servlet, let’s move further and understand what are the steps
involved to create a Servlet application.

Advanced Java Tutorial: Steps to create Servlet

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Add mappings to web.xml file
5. Start the server and deploy the project
6. Access the servlet

Now, based on the above steps let’s write a program and understand how servlet works.

Step 1: To run a servlet program, we should have Apache tomcat server installed and configured. Once the server
is configured, you can start with your program.

Step 2: For a servlet program, you need 3 files – index.html file, Java class file, and web.xml file. The very first
step is to create Dynamic Web Project and then proceed further

Step 3: Now let’s see how to add 2 numbers using servlets and display the output in the browser.
First, I will write index.html file

<!DOCTYPE html>
<html>
<body>
<form action ="add">
Enter 1st number: <input type="text" name="num1"><br>
Enter 2nd number: <input type="text" name="num2"><br>
<input type ="submit">
</form>
</body>
</html>
Above program creates a form to enter the numbers for the addition operation.

Step 4: Now without the Java class file, you can’t perform addition on 2 numbers. So let’s write a class file.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Add extends HttpServlet{
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException
{
int i = Integer.parseInt(req.getParameter("num1"));
int j = Integer.parseInt(req.getParameter("num2");
int k= i+j;
PrintWriter out = res.getWriter();
out.println("Result is"+k);
}
}

Step 5: After writing the Java class file, the last step is to add mappings to the web.xml file. Let’s see how to do
that.

Step 6: web.xml file will be present in the WEB-INF folder of your web content. If it is not present, then you can
click on Deployment Descriptor and click on Generate Deployment Descriptor Stub.

Step 7: After that, you can proceed further and add the mappings to it.

<?xml version="1.0" encoding="UTF-8"?>


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns=<"http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"</em>
version=<em>"3.0"</em>>
<display-name>Basic</display-name>
<servlet>
<servlet-name>Addition</servlet-name>
<servlet-class>edureka.Add</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Addition</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Step 8: After all this, you can run the program by starting the server. You will get the desired output on the
browser.

Basically, this is how servlet should be configured. Now let’s move further and understand the concept of session
tracking.

Session Tracking

Session simply means a particular interval of time. And session tracking is a way to maintain state (data) of a
user. It is also known as session management in servlet. We know that the Http protocol is stateless, so we need
to maintain state using session tracking techniques. Each time user requests to the server, the server treats the
request as the new request. So we need to maintain the state of a user to recognize a particular user.

You can see in the figure when you send a request it is considered as a new request.

In order to recognize the particular user, we need session tracking. So this was all about Servlets.

Now, let’s dive into the last section of our blog and understand what is JSP.

Вам также может понравиться