Module-3
Servlets
INTRODUCTION
• Servlets are small programs that execute on the server side of a web
connection.
• Applets dynamically extend the functionality of a web browser.
• Servlets dynamically extend the functionality of a web server.
• Java Servlet is a Java program that runs on a Java-enabled web server or
application server.
• It handles client requests, processes them, and generates responses
dynamically.
• Servlets are the backbone of many server-side Java applications due to
their efficiency and scalability.
• Servlets work on the server side.
• Servlets are capable of handling complex requests obtained from the web
server.
• Benefits of Java Servlets:
1. Performance: Faster execution as Servlets do not create
new processes for each request.
2. Portability: Write-once, run-anywhere feature of Java.
3. Memory: Single instance handles multiple requests.
4. Integration: Easily integrates with databases using JDBC.
5. Security: Inherits robust security features from web servers.
6. Cost-Effective: Many web servers like Apache Tomcat are
free to use with Java Servlets.
Java Servlets Architecture
• Servlet Architecture can be depicted from the image
itself as provided below as follows:
Execution of Java Servlets
• Execution of Servlets basically involves 6 basic steps:
1. The Clients send the request to the Web Server.
2. The Web Server receives the request.
3. The Web Server passes the request to the corresponding servlet.
4. The Servlet processes the request and generates the response in
the form of output.
5. The Servlet sends the response back to the webserver.
6. The Web Server sends the response back to the client and the
client browser displays it on the screen.
• Consider a request for a static web page.
• A user enters a Uniform Resource Locator (URL) into a browser.
• The browser generates an HTTP request to the appropriate web
server.
• The web server maps this request to a specific file.
• That file is returned in an HTTP response to the browser.
• The HTTP header in the response indicates the type of the
content.
• The Multipurpose Internet Mail Extensions (MIME) are used for
this purpose.
• For example, ordinary ASCII text has a MIME type of text/plain.
• The HTML source code of a web page has a MIME type of
text/html.
• Now consider dynamic content.
• Assume that an online store uses a database
to store information about its business.
• This would include items for sale, prices,
availability, orders, and so forth.
• It wishes to make this information accessible
to customers via web pages.
• The contents of those web pages must be
dynamically generated to reflect the latest
information in the database.
• In the early days of the Web, a server could dynamically construct a
page by creating a separate process to handle each client request.
• The process would open connections to one or more databases in
order to obtain the necessary information.
• It communicated with the web server via an interface known as the
Common Gateway Interface (CGI).
• CGI allowed the separate process to read data from the HTTP request
and write data to the HTTP response.
• A variety of different languages were used to build CGI programs.
• These included C, C++, and Perl.
• CGI suffered serious performance problems.
1. It was expensive in terms of processor and memory resources to create
a separate process for each client request.
2. It was also expensive to open and close database connections for each
client request.
3. In addition, the CGI programs were not platform-independent.
• Therefore, other techniques were introduced.
• Among these are Servlets.
• Servlets offer several advantages in comparison with CGI.
1) Performance is significantly better.
• Servlets execute within the address space of a web server.
• It is not necessary to create a separate process to handle each client
request.
2) Servlets are platform-independent because they are written in Java.
3) The Java security manager on the server enforces a set of restrictions to
protect the resources on a server machine.
4) The full functionality of the Java class libraries is available to a servlet.
• It can communicate with applets, databases, or other software via the
sockets and RMI mechanisms.
Life Cycle of a Servlet
1. init(): This method itializes the Servlet instance.
@Override
public void init() throws ServletException {
// Initialization: Called once when the servlet is loaded into memory
System.out.println("Servlet initialized");
}
2. service(): This method Processes requests and invokes either
doGet() and doPost() based on the request type.
@Override
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Request handling: Called each time a request is made
String method = request.getMethod();
if ("GET".equalsIgnoreCase(method)) {
doGet(request, response);
} else if ("POST".equalsIgnoreCase(method)) {
doPost(request, response);
}
}
3. destroy(): This method cleans up resources when the
servlet is terminated.
@Override
public void destroy() {
// Cleanup: Called once when the servlet is being destroyed
System.out.println("Servlet destroyed");
}
Servlet Development Options
• To create servlets, you will need access to a servlet container/server.
• 2 popular ones are Glassfish and Tomcat.
• Glassfish is from Oracle and is provided by the Java EE SDK.
• It is supported by NetBeans.
• Tomcat is an open-source product maintained by the Apache Software
Foundation.
• It can also be used by NetBeans.
• Both Tomcat and Glassfish can also be used with other IDEs, such as Eclipse.
How to Run Servlet in Tomcat?
• In this example, we will create a basic servlet that displays a
Hello World message from a Java program to the user in the
browser without using any Java IDE like Eclipse
Basic Terms
GenericServlet
• A servlet class is usually created by extending either the
GenericServlet class or its descendant
javax.servlet.http.HttpServlet class.
• The GenericServlet class defines a generic protocol-
independent servlet, in the sense that it can be extended to
provide
implementation of any protocol, such as HTTP, FTP, and SMTP.
• It provides implementations of the life cycle methods init() and
destroy(), as well as methods in the ServletConfig interface.
HttpServlet
• Provides a framework for handling HTTP requests.
• It provides an implementation for the service() method.
• The service() method in the HttpServlet class reads the
method type stored in the HTTP request message and invokes
a specific method based on this value.
• If the method type is GET, it calls doGet();
• If the method type is POST, it calls doPost()
• These are the methods that we need to override.
Steps For Creating Servlet
• Servlet is a simple servlet designed to handle the HTTP GET
method.
• Create the following servlet HelloWorldServlet.java using
any text editor like Notepad.
import java.io.*;
import javax.servlet.*; out.println(
import javax.servlet.http.*;
"<html><head><title> Hello
public class HelloWorldServlet extends World Servlet</title></head>");
HttpServlet out.println("<body>");
{ out.println("<h1>Hello World!</h1>");
public void doGet(HttpServletRequest out.println("</body></
request, HttpServletResponse response) html>");
throws IOException, out.close();
ServletException }
{ }
response.setContentType("text/html");
PrintWriter out = response.getWriter();
• The class HelloWorldServlet extends the HttpServlet class.
• It is written to handle only the GET method.
• Therefore, only the doGet() method is overridden.
• Finally, it sends the following HTML document.
<html>
<head>
<title>Hello World Servlet</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
• Here we are assuming we have installed Tomcat in the D
directory of our computer.
Building and Installing Servlet
• To compile our HelloWorldServlet.java file, servlet class files
are required.
• Tomcat comes with a .jar file (servlet-api.jar) that contains
necessary class files
• Find this jar file usually in the TOMCAT_HOME\lib directory
• Compile the HelloWorldServlet.java using the following
command in the Command Prompt and press enter:
javac HelloWorldServlet.java
•This generates the file HelloWorldServlet.class that contains the byte
code for our servlet.
•Create the following directory structure under the webapps subdirectory.
• Put the HelloWorldServlet.class file in the
TOMCAT_HOME\webapps\net\WEB-INF\classes directory.
• Inform the web server about the existence of this
servlet and the URL that will be used to refer to this
servlet
• Specify in the TOMCAT_HOME\net\WEB-INF\web.xml file.
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>
Accessing the servlet
•The complete URL of this servlet will be
http://172.16.5.81:8080/net/servlet/HelloWorld
where 8080 is the port number.
•Type the following URL in the address bar of your web
browser and press enter
http://172.16.5.81:8080/net/servlet/HelloWorld
Refer using Tomcat in Complete
reference
A Simple Servlet
The basic steps are the following:
1. Create and compile the servlet source code. Then, copy the
servlet’s class file to the proper directory, and add the
servlet’s name and mappings to the proper web.xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.
Create and Compile the Servlet Source Code
To begin, create a file named HelloServlet.java that contains the following program:
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request,ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
• It imports the javax.servlet package.
• This package contains the classes and interfaces required to build servlets.
• The program defines HelloServlet as a subclass of GenericServlet.
• The GenericServlet class provides functionality that simplifies the creation of a servlet.
• For example, it provides versions of init( ) and destroy( ), which may be used as it is.
• You need supply only the service( ) method.
• Inside HelloServlet, the service( ) method (which is inherited from GenericServlet) is overridden.
• This method handles requests from a client.
• The 1st argument is a ServletRequest object. ( This enables the servlet to read data that is provided via
the client request. )
• The 2nd argument is a ServletResponse object. (This enables the servlet to formulate a response for the
client.)
• The call to setContentType( ) establishes the MIME type of the HTTP response.
• In this program, the MIME type is text/html.
• This indicates that the browser should interpret the content as HTML source code.
• The getWriter( ) method obtains a PrintWriter.
• Anything written to this stream is sent to the client as part of the HTTP response.
• Then println( ) is used to write some simple HTML source code as the HTTP response.
• Compile this source code and place the HelloServlet.class file in the proper Tomcat directory .
Starting with first Servlet
Application
• To get started with Servlets, let’s first start with a simple Servlet
application i.e LifeCycle application, that will demonstrate the
implementation of the init(), service() and destroy() methods.
• It is important to understand that if we are developing any Servlet
application, it will handle some client’s request so, whenever we
talk about Servlets, we need to develop a filename.html page
which will request a particular Servlet to handle the request made
by the client.
• Steps to develop the LifeCycle application :
• Creating the filename.html page
• Creating the LifeCycle Servlet
• Creating deployment descriptor
Creating the index.html page
• For the sake of simplicity, this page will just have a
button invoke life cycle.
• When you will click this button it will
call LifeCycleServlet (which is mapped according to the
entry in web.xml file).
<html>
<form action="LifeCycleServlet">
<input type="submit" value="invoke life cycle servlet">
</form>
</html>
• The name of the Servlet is given in action attribute of
form tag to which the request will be send on clicking
the button, in this case FirstServlet.
Creating the Servlet (FirstServlet)
• Create the LifeCycleServlet which implements
• init()
• service()
• destroy()
• methods to demonstrate the lifecycle of a Servlet.
// importing the javax.servlet package & importing java.io pw.println("<h2>hello from life cycle servlet</h2>");
package for PrintWriter System.out.println("in service");
import javax.servlet.*; }
import java.io.*;
// now creating a servlet by implementing Servlet interface // destroy method
public class LifeCycleServlet implements Servlet { public void destroy()
{
ServletConfig config = null; System.out.println("in destroy");
}
// init method public String getServletInfo()
public void init(ServletConfig sc) {
{ return "LifeCycleServlet";
config = sc; }
System.out.println("in init"); public ServletConfig getServletConfig()
} {
// service method return config; // getServletConfig
public void service(ServletRequest req, ServletResponse res) }
throws ServletException, IOException }
{
res.setContenttype("text/html");
PrintWriter pw = res.getWriter();
Creating deployment descriptor(web.xml)
<?xml version="1.0" encoding="UTF=8"?>
<web-app>
<servlet>
<servlet-name>LifeCycleServlet</servlet-name>
<servlet-class>LifeCycleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LifeCycleServlet</servlet-name>
<url-pattern>/LifeCycleServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-config>
</web-app>
How to run the above program ?
• It is important to make sure that you have some server
like Apache Tomcat installed and configured with the IDE of
your choice like Netbeans.
• If the above condition is fulfilled then you can simply create
the above files under Web application project and then
simply run the above application.
• First of all, the index.html file gets executed and then when
the button is clicked the request goes to the Servlet, in this
case LifeCycleServlet and the service() method handles the
request.
• When the above invoke life cycle servlet button is
clicked the code under service() method of
LifeCycleServlet is executed and the below output is
obtained :
start tomcat
• Tomcat is a free and open-source web server.
• It was developed at Sun Microsystems (an American technology
company, currently acquired by Oracle).
• Tomcat is the implementation of Java EE (Java Enterprise Edition)
in the newer version of Jakarta Package (Jakarta EE).
• It supports Jakarta Servlet, Jakarta Server Page, Jakarta
Expression Languages, Jakarta WebSockets, etc.
• It provides a "JAVA HTTP" web server.
How to Install Apache Tomcat and Setup the
Environment?
The following are the steps that helps in guiding how to install
the apache tomcat in windows and setup its environment:
Step 1:Download the Windows Service Installer from their
official website using the Windows Tomcat Binary Distribution.
Step 2: The following screenshot illustrates on the setup of tomcat, it will go
through asking for value definition regarding setup.
• Step 3: You need to click on next button.
Step 4: Then agreed for installation.
Step 5: Then next -> next-> Finish.
Step 6: Now Your server is running on port
"http://localhost/8080".
Restart or Running of
Tomcat Server
If you want to stop the server
then you need to go to the
folder name "Program Files"
like in my system "C:\Program
Files\Apache Software
Foundation" >> "C:\Program
Files\Apache Software
Foundation\Tomcat 9.0\bin".
Step 1: Then go inside bin
folder
Step 2: Right click on Tomcat9 and then click on stop and
similar you can again re-start from here.
Start a Web Browser and Request the Servlet
• Start a web browser and enter the URL shown here:
• http://localhost:8080/examples/servlets/servlet/HelloServlet
• Alternatively, you may enter the URL shown here:
• http://127.0.0.1:8080/examples/servlets/servlet/HelloServlet
• This can be done because 127.0.0.1 is defined as the IP
address of the local machine.
• You will observe the output of the servlet in the browser
display area.
• It will contain the string Hello! in bold type.
The Servlet API
• 2 packages contain the classes and interfaces that are required
to build the servlets
• These are javax.servlet and javax.servlet.http.
• They constitute the core of the Servlet API.
• These packages are not part of the Java core packages.
• Therefore, they are not included with Java SE.
• Instead, they are provided by Tomcat.
• They are also provided by Java EE.
• The Servlet API has been in a process of ongoing development
and enhancement.
• The current servlet specification is version 3.1.
The GenericServlet Class
• The GenericServlet class provides implementations of the basic life cycle methods for a servlet.
• GenericServlet implements the Servlet and ServletConfig interfaces.
• In addition, a method to append a string to the server log file is available.
• The signatures of this method are shown here:
void log(String s)
void log(String s, Throwable e)
• Here, s is the string to be appended to the log, and e is an exception that occurred.
The ServletInputStream Class
• The ServletInputStream class extends InputStream.
• It is implemented by the servlet container and provides an input stream that a servlet developer
can use to read the data from a client request.
• In addition to the input methods inherited from InputStream, a method is provided to read bytes
from the stream.
• It is shown here:
int readLine(byte[ ] buffer, int offset, int size) throws IOException
• Here, buffer is the array into which size bytes are placed starting at offset.
• The method returns the actual number of bytes read or –1 if an end-of-stream condition is
encountered.
The ServletOutputStream Class
• The ServletOutputStream class extends OutputStream.
• It is implemented by the servlet container and provides an output
stream that a servlet developer can use to write data to a client
response.
• In addition to the output methods provided by OutputStream, it also
defines the print( ) and println( ) methods, which output data to the
stream.
The Servlet Exception Classes
• javax.servlet defines 2 exceptions.
• The 1st is ServletException, which indicates that a servlet problem
has occurred.
• The 2nd is UnavailableException, which extends ServletException.
• It indicates that a servlet is unavailable.
Reading Servlet Parameters
• The ServletRequest interface includes methods that allow
you to read the names and values of parameters that are
included in a client request.
• The example contains 2 files.
• A web page is defined in PostParameters.html, and a servlet
is defined in PostParametersServlet.java.
• The HTML source code for PostParameters.html is shown in
the following listing.
• It defines a table that contains 2 labels and 2 text fields.
• One of the labels is Employee and the other is Phone.
• There is also a submit button.
• The action parameter of the form tag specifies a URL.
• The URL identifies the servlet to process the HTTP POST request.
<html>
<body>
<center>
<form name="Form1“ method="post"
action="http://localhost:8080/examples/servlets/servlet/PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>
• The source code for PostParametersServlet.java is shown in the
following listing.
• The service( ) method is overridden to process client requests.
• The getParameterNames( ) method returns an enumeration of the
parameter names.
• These are processed in a loop.
• The parameter name and value are output to the client.
• The parameter value is obtained via the getParameter( ) method.
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet {
public void service(ServletRequest request,ServletResponse response)
throws ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}
• Compile the servlet.
• Next, copy it to the appropriate directory, and update the web.xml file.
• Then, perform these steps to test this example:
1. Start Tomcat (if it is not already running).
2. Display the web page in a browser.
3. Enter an employee name and phone number in the text fields.
4. Submit the web page.
• After following these steps, the browser will display a response that is
dynamically generated by the servlet.
Handling HTTP Requests and Responses
• The HttpServlet class provides specialized methods that
handle the various types of HTTP requests.
• A servlet developer typically overrides one of these methods.
• These methods are doDelete( ), doGet( ), doHead( ),
doOptions( ), doPost( ), doPut( ) and doTrace( ).
• The GET and POST requests are commonly used when
handling form input.
Handling HTTP GET Requests
• Develop a servlet that handles an HTTP GET request.
• The servlet is invoked when a form on a web page is submitted.
• This example contains 2 files.
• A web page is defined in ColorGet.html, and a servlet is defined in
ColorGetServlet.java.
• The HTML source code for ColorGet.html is shown in the following listing.
• It defines a form that contains a select element and a submit button.
• The action parameter of the form tag specifies a URL.
• The URL identifies a servlet to process the HTTP GET request.
• The source code for ColorGetServlet.java is shown in the
following listing.
• The doGet( ) method is overridden to process any HTTP
GET requests that are sent to this servlet.
• It uses the getParameter( ) method of
HttpServletRequest to obtain the selection that was
made by the user.
• A response is then formulated.
• Compile the servlet.
• Copy it to the appropriate directory, and update the
web.xml file.
• Perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the web page in a browser.
3. Select a color.
4. Submit
• After completing these steps, the browser will display the response
that is dynamically generated by the servlet.
• Parameters for an HTTP GET request are included as part of the URL
that is sent to the web server.
• Assume that the user selects the red option and submits the form.
• The URL sent from the browser to the server is
http://localhost:8080/examples/servlets/servlet/ColorGetServlet?color
=Red
• The characters to the right of the question mark are known as the
query string.
Handling HTTP POST Requests
• Develop a servlet that handles an HTTP POST request.
• The servlet is invoked when a form on a web page is submitted.
• The example contains 2 files.
• A web page is defined in ColorPost.html, and a servlet is defined in
ColorPostServlet.java.
• The HTML source code for ColorPost.html is shown in the following listing.
• It is identical to ColorGet.html except that the method parameter for the
form tag explicitly specifies that the POST method should be used, and the
action parameter for the form tag specifies a different servlet.
• The source code for ColorPostServlet.java is
shown in the following listing.
• The doPost( ) method is overridden to process any
HTTP POST requests that are sent to this servlet.
• It uses the getParameter( ) method of
HttpServletRequest to obtain the selection that
was made by the user.
• A response is then formulated.
• Compile the servlet and perform the same steps.
NOTE Parameters for an HTTP POST request are not included as part of the
URL that is sent to the web server.
In this example, the URL sent from the browser to the server is
http://localhost:8080/examples/servlets/servlet/ColorPostServlet
• The parameter names and values are sent in the body of the HTTP request.
Using Cookies
• Now, let’s develop a servlet that illustrates how to use cookies.
• The servlet is invoked when a form on a web page is submitted.
• The example contains 3 files as summarized here:
• The HTML source code for AddCookie.html is shown in the
following listing.
• This page contains a text field in which a value can be
entered.
• There is also a submit button on the page.
• When this button is pressed, the value in the text field is sent
to AddCookieServlet via an HTTP POST request.
• The source code for AddCookieServlet.java is shown in the following
listing.
• It gets the value of the parameter named "data".
• It then creates a Cookie object that has the name "MyCookie" and
contains the value of the "data" parameter.
• The cookie is then added to the header of the HTTP response via the
addCookie( ) method.
• A feedback message is then written to the browser.
• The source code for GetCookiesServlet.java is shown in the
following listing.
• It invokes the getCookies( ) method to read any cookies that
are included in the HTTP GET request.
• The names and values of these cookies are then written to the
HTTP response.
• The getName( ) and getValue( ) methods are called to
obtain this information.
• Compile the servlets.
• Copy them to the appropriate directory, and update the web.xml file.
• Then, perform these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display AddCookie.html in a browser.
3. Enter a value for MyCookie.
4. Submit the web page.
• After completing these steps, you will observe that a feedback message is displayed by the browser.
• Next, request the following URL via the browser:
http://localhost:8080/examples/servlets/servlet/GetCookiesServlet
• The name and value of the cookie are displayed in the browser.
• In this example, an expiration date is not explicitly assigned to the cookie via the setMaxAge( ) method
of Cookie.
• Therefore, the cookie expires when the browser session ends. You can experiment by using
setMaxAge( ) and observe that the cookie is then saved on the client machine.
Session Tracking
• HTTP is a stateless protocol.
• Each request is independent of the previous one.
• In some applications, it is necessary to save state information so that information can be collected from
several interactions between a browser and a server.
• Sessions provide such a mechanism.
• A session can be created via the getSession( ) method of HttpServletRequest.
• An HttpSession object is returned.
• This object can store a set of bindings that associate names with objects.
• The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of
HttpSession manage these bindings.
• The following servlet illustrates how to use session state.
• The getSession( ) method gets the current session.
• A new session is created if one does not already exist.
• The getAttribute( ) method is called to obtain the object that is bound to the
name "date".
• That object is a Date object that encapsulates the date and time when this page
was last accessed.
• A Date object encapsulating the current date and time is then created.
• The setAttribute( ) method is called to bind the name "date" to this object.
• When you first request this servlet, the browser displays
one line with the current date and time information.
• On subsequent invocations, two lines are displayed.
• The first line shows the date and time when the servlet
was last accessed.
• The second line shows the current date and time.