SERVLETS
4/24/2025 1
Introduction to Servlet
Servlet is a small program that execute on the server side of a
web connection. It provides a powerful mechanism for
developing web applications.
Servlet receives and responds to requests from web clients.
Servlet runs entirely inside the JVM (Java Virtual Machine)
Just as applet extend the functionality of web browser, the
servlet extend the functionality of web server.
4/24/2025 2
Advantage of Servlet over "Traditional" CGI
Java Servlet is :
o more efficient
o easier to use
o more powerful
o more portable
o and cheaper than traditional CGI (Common Gateway
Interface – first technology used to generate dynamic
content)
4/24/2025 3
1. Efficient
With traditional CGI, a new process is started for each HTTP
request.
If the CGI program does a relatively fast operation, the
overhead of starting the process can dominate the execution
time.
With Servlet each request is handled by a lightweight Java
thread, not a heavyweight operating system process.
4/24/2025 4
Similarly, in traditional CGI, if there are N simultaneous
request to the same CGI program, then the code for the CGI
program is loaded into memory N times.
With Servlets, however, there are N threads but only a single
copy of the servlet class.
4/24/2025 5
2. Convenient
Besides the convenience of being able to use a familiar
language, Servlets have an extensive infrastructure for :
o automatically parsing and decoding HTML form data
o reading and setting HTTP headers
o handling cookies
o tracking sessions and many other such utilities
4/24/2025 6
3. Powerful
Servlets can communicate directly to the Web server (regular
CGI programs can't)
This simplifies operations that need to look up images and
other data stored in standard places
Servlets can also share data among each other, making
useful things like database connection pools easy to
implement.
4/24/2025 7
4. Portable
Servlets are written in Java and follow a well-standardized
API.
Consequently Servlets written for, say I-Planet Enterprise
Server can run virtually unchanged on Apache, Microsoft IIS,
or Web Star.
Servlets are supported directly or via a plug in on almost
every major Web server.
4/24/2025 8
5. Inexpensive
There are a number of free or very inexpensive Web servers
available that are good for "personal" use or low-volume Web
sites.
Apache, which is free, most commercial-quality Web servers
are relatively expensive.
Nevertheless, once you have a Web server, no matter the
cost of that server, adding servlet support to it is generally
free or cheap.
4/24/2025 9
Phases of Servlet life cycle (Anatomy of a Java Servlet)
1. Servlet class is loaded
◦ Servlet class is loaded when first request comes to web
container.
2. Servlet instance is created
◦ Web container creates the instance of servlet class only once.
3. Init() method is invoked
◦ It calls the init method automatically when the Java Servlet is
created.
◦ The statements in init() method are executed once during the life
of Java Servlet.
4/24/2025 10
Syntax of init() method is
public void init(ServletConfig config) throws ServletException
4/24/2025 11
4. Service method is invoked
◦ Web container calls service method each time when request for
the servlet is received.
◦ If servlet is not initialized it calls init() then it calls the service()
method.
◦ The service() method examines the HTTP request type and then
calls the appropriate request method such as doGet() and
doPost().
Syntax of service method is as follows:
public void service(ServletRequest request, ServletResponse
response) throws ServletException,IOException
4/24/2025 12
5. Destroy method is invoked
◦ The web container calls the destroy method before it removes
the servlet from service.
◦ It gives servlet an opportunity to clean up memory, resources
etc.
Servlet destroy method has following syntax:
public void destroy().
4/24/2025 13
There are three states of Servlet new, ready, end.
◦ The Servlet instance is created when it is in new state.
◦ After invoking the init () method Servlet comes to ready state.
◦ In ready state Servlet invokes destroy method it comes to end
state.
4/24/2025 14
Using Tomcat for Servlet development
Apache Tomcat, often referred to as Tomcat Server, is an open-
source Java Servlet Container developed by the Apache
Software Foundation (ASF).
Tomcat implements several Java EE specifications
including Servlet, JSP etc.
Seven Steps to Run Servlet
1. Create a directory structure under Tomcat for your
application.
15
2. Write the servlet source code.
3. Import the javax.servlet package and the javax.servlet.http
package in your source file.
4. Compile your source code.
5. Create a deployment descriptor.
6. Run Tomcat.
7. Call your servlet from a web browser.
16
Program to print “HelloWorld” on Web server (static web page)
File→New→ Dynamic Web Project→ specify project name (Eg:-
DemoHelloWorld)→ Next→Next→ tick the check box (Generate web.xml
deployment descriptor)→Finish
Right click on HelloWorld→ New→ HTML file→ specify file name (index.html)
<!DOCTYPE html>
<html>
<body>
<h2>Hello World</h2>
</body>
</html>
Right click on the html file → Run As → Run on Server
4/24/2025 17
Program Execution Procedure
File→New→ Dynamic Web Project→ specify project name
(Eg:- DemoApp)→Next→Next→ tick the check box
(Generate web.xml deployment descriptor)→Finish
Right click on DemoApp→New→ HTML file→ specify file
name (index.html)
Right click on DemoApp→New→class file→ specify file Name
AddServlet and Package → servletpgms
Click on main→ click on webapp→click on WEB-INF →
web.xml file
4/24/2025 18
Reading Data from a Client
A client uses either the GET or POST method to pass
information to a java servlet.
Depending on the method used by the client either doGet() or
doPost() method is called in servlet.
Data sent by a client is read into java servlet by calling
getParameter() method of HttpservletRequest() object that
instantiated in the argument list of doGet() method and
doPost() method.
4/24/2025 19
getParameter() requires one argument, which is the name of
parameter that contains the data sent by the client.
getParameter() returns the String object.
String object contains the value assigned by the client. An
empty string object is returned when it does not assign a
value to the parameter. Also a null is returned when
parameter is not returned in the client.
getParameterValues() used to return the array of string
objects.
4/24/2025 20
Sending Data to a Client
A java servlet responds to a client’s request by reading client
data and HTTP request headers, and then processing
information based on the nature of the request.
Explicit data are sent by creating an instance of the
PrintWriter object and then using println() method to transmit
the information to the client.
4/24/2025 21
Lab Program: 1
A program to display greeting message on the browser “ Hello
UserName”, “How are you”, accept username from the client using
servlet.
index.html
<!DOCTYPE html>
<html>
<body>
<form action="greet">
Enter User Name:<input type="text" name="uname"><br>
<input type="submit">
</form>
</body>
</html>
4/24/2025 22
HelloUserName.java
package rachana;
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 HelloUsername extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException
{
String name= req.getParameter("uname");
PrintWriter out= res.getWriter();
out.println("Hello "+name+", How are you?");
}
}
4/24/2025 23
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<servlet>
<servlet-name>GreetingServlet</servlet-name>
<servlet-class>rachana.HelloUsername</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GreetingServlet</servlet-name>
<url-pattern> /greet</url-pattern>
</servlet-mapping>
</web-app>
4/24/2025 24
Lab Program: 2
A program to display the name, USN and total marks by accepting
student detail
index.html
<!DOCTYPE html>
<html>
<body>
<form action="student">
Enter Name:<input type="text" name="name"><br>
Enter USN:<input type="text" name="usn"><br>
Total marks:<input type="text" name="marks"><br>
<input type="submit">
</form>
</body>
</html>
4/24/2025 25
StudentServlet.java
package rachana;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class StudentServlet extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse
res) throws IOException
{
String i=req.getParameter("name");
String j=req.getParameter("usn");
int k=Integer.parseInt(req.getParameter("marks"));
PrintWriter out= res.getWriter();
out.println("Nmae: "+i+" USN: "+j+" and total marks="+k);
}
4/24/2025 26
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<servlet>
<servlet-name>display</servlet-name>
<servlet-class>rachana.StudentServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>display</servlet-name>
<url-pattern>/student</url-pattern>
</servlet-mapping>
</web-app>
4/24/2025 27
Program to receive two numbers and print the sum of it on web server.
index.html
<!DOCTYPE html>
<html>
<body>
<form action="add“ method=“post”>
Enter first number:<input type="text" name="num1"><br>
Enter second number:<input type="text" name="num2"><br>
<input type="submit">
</form>
</body>
</html>
4/24/2025 28
AddServlet.java
package DemoAdd;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class AddServlet 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);
}
}
4/24/2025 29
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID" version="4.0">
<servlet>
<servlet-name>abc</servlet-name>
<servlet-class>sevletpgms.AddServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abc</servlet-name>
<url-pattern>/add</url-pattern>
</servlet-mapping>
</web-app>
4/24/2025 30
Explanation
The Java class must extend HttpServlet and override the
HttpServlet’s service()/ or doGet() and / or doPost() methods.
The doGet() method is used to interact with a request sent
using the METHOD=“GET” attribute from an HTML form or
when passing parameters on the URL like a hyperlink.
The doPost() method is used for requests sent using the
METHOD=“POST”.
Both the doGet() and doPost() methods require two arguments.
4/24/2025 31
◦ HttpservletRequest object → contains incoming information
◦ HttpservletResponse object → send outgoing information to
the client
◦ It throw a ServletException & IOException
Incoming data includes explicit data and implicit data.
◦ Explicit data is supplied by a user and is contained in a query
string that contains data from a form.
◦ Implicit data is HTTP information such as request headers.
4/24/2025 32
Outgoing data is sent by using a PrintWriter object using the
println() method and is forwarded to the client that made the
request.
The format of the data sent to the client is client dependent.
The println() method is used in conjunction with a PrintWriter
to send outgoing explicit data such as text that appears on
the web page.
4/24/2025 33
Deployment Descriptor
Deployment descriptor is a file located in the WEB-INF
directory that controls the behavior of a java Servlet.
The file is called the web.xml file and contains the header,
DOCTYPE, and web app element.
The web app element should contain three elements.
1. servlet name
2. servlet class
3. servlet mapping
4/24/2025 34
The servlet name elements contain the name used to access
the java servlet.
The servlet class is the name of the java servlet class.
The Servlet-mapping – specify the url here, which will be
printed along with package name.
Eg:- localhost:8080/DemoApp/add?num1=10&num2=10
4/24/2025 35
Example file
<?xml version=”1.0” encoding-“ISO-8859=1”?>…..XML header
< !DOCTYPE web-app PUBLIC “~//Sun Microsystems, Inc.??
DTD Web
Application2.2//EN”> ..doctype
<web-app>
<servlet>
<servlet-name>MyJavaservlet</servlet-name>
<servlet-class>myPackage.MyJavaservletClass</servlet-class>
4/24/2025 36
<servlet -mapping>
<servlet-name> MyJavaservlet </servlet-name>
<url-pattern> /abc</url-pattern>
</servlet -mapping>
</servlet>
</web-app>
4/24/2025 37
The Servlet API
Two packages javax.servlet and javax.servlet.http contain
classes and interfaces required for servlet building.
These are not part of Java SE and are provided by
standard extensions of Tomcat.
38
javax.servlet package- core interfaces
Interface Description
Servlet Declares life cycle methods for a servlet.
ServletConfig Allows servlets to get initialization parameters.
ServletContext Enables servlets to log events and access
information about their environment.
ServletRequest Used to read data from a client request.
ServletResponse Used to write data to a client response.
39
javax.servlet package- core classes
Class Description
GenericServlet Implements the Servlet and ServletConfig
interfaces.
ServletInputStream Provides an input stream for reading requests
from a client.
ServletOutputStream Provides an output stream for writing responses
to a client.
ServletException Indicates that a servlet error occurred.
UnavailableException Indicates that a servlet is permanently or
temporarily unavailable.
40