Chapter 3
Chapter 3
Servlets
What is a Servlet?
Servlet can be described in many ways, depending on the context.
•Servlet is a technology which is used to create a web application.
•Servlet is an API that provides many interfaces and classes including documentation.
•Servlet is an interface that must be implemented for creating any Servlet.
•Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
•Servlet is a web component that is deployed on the server to create a dynamic web page
Execution of Servlets :
Execution of Servlets involves six 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 web server.
6.The web server sends the response back to the client and the client browser displays it on the screen.
Servlet Architecture
The diagram shows the servlet architecture:
What is a web application?
A web application is an application accessible from the web. A web application is composed of
web components like Servlet, JSP, Filter, etc. and other elements such as HTML, CSS, and
JavaScript. The web components typically execute in Web Server and respond to the HTTP
request.
CGI (Common Gateway Interface)
CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a new
process.
Disadvantages of CGI
There are many problems in CGI technology:
1.If the number of clients increases, it takes more time for sending the response.
2.For each request, it starts a process, and the web server is limited to start processes.
3.It uses platform dependent language e.g. C, C++.
Advantages of Servlet
There are many advantages of
Servlet over CGI. The web
container creates threads for
handling the multiple requests to
the Servlet. Threads have many
benefits over the Processes such as
they share a common memory
area, lightweight, cost of
communication between the
The advantages of Servlet are as follows: threads are low
1.Better performance: because it creates a thread for each request, not process.
2.Portability: because it uses Java language.
3.Robust: JVM manages Servlets, so we don't need to worry about the memory leak,
garbage collection, etc.
4.Secure: because it uses java language.
Servlets API’s:
•javax.servlet(Basic)
Servlets are build from two packages:
•javax.servlet.http(Advance)
Various classes and interfaces present in these packages are
Component Type Package
Servlet Interface javax.servlet.*
Init() destroy()
Servlet is in service
Servlet to create
public void destroy()
{
//cleanup code
}
Types of servlet
servlet must implement the interface from javax.servlet.Servlet. There are 2 main types of servlet
1. Generic servlets
2. HTTP servlets
Generic servlets
• It extends javax.servlet.GenericServlet.
• Generic servlets are protocol independent, means that they contain no inherent support for HTTP
or any other transport protocol.
• Syntax:
class class_nm extends GenericServlet
{ }
HTTP servlets
• These extend javax.servlet.HttpServlet.
• These servlets have built-in support for the HTTP protocol and are much more useful in an
browser environment.
• All servlets extends from HttpServlet rather than from GenericServlet in order to take advantage
of this built-in HTTP support
Syntax : class class_nm extends HttpServlet{ }
It provides http specific methods such as doGet, doPost, doHead, doTrace etc.
ServletRequest Interface
An object of ServletRequest is used to provide the client request information to a servlet such
as content type, content length, parameter names and values, header informations, attributes
etc.
Method Description
public String getParameter(String name) is used to obtain the value of a parameter by name.
public String[] getParameterValues(String returns an array of String containing all values of given parameter
name) name. It is mainly used to obtain values of a Multi select list box.
getAttribute() Returns the value of Attributes
getProtocol() Return description about Protocol
public String getContentType() Returns the Internet Media Type of the request entity data, or null if
not known.
public ServletInputStream getInputStream() Returns an input stream for reading binary data in the request body.
throws IOException
public abstract String getServerName() Returns the host name of the server that received the request.
public int getServerPort() Returns the port number on which this request was received.
The ServletResponse represents the response which is sent back to the user. The servlet
container creates a ServletResponse object and passes it as an argument to the servlet’s
service method.
Important Methods of ServletResponse Interface
•public PrintWriter getWriter() : This method returns a PrintWriter object that can send
character text to the client.
•public ServletOutputStream getOutputStream() : This method returns a ServletOutputStream
suitable for writing binary data in the response.
•public void setContentType(String type) : Sets the content type of the response being sent as
response.
Web Terminology
Servlet Terminology Description
Website: static vs dynamic It is a collection of related web pages that may contain text, images, audio and
video.
Server: Web vs Application It is used to manage the network resources and for running the program or
software that provides services.
Content Type It is HTTP header that provides the description about what are you sending to
the browser.
Steps to create a servlet example
1.Steps to create the servlet using Tomcat server
1. Create a directory structure
2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the application
There are given 6 steps to create a servlet example. These steps are required for all the
servers.
The servlet example can be created by three ways:
2.By implementing Servlet interface,
3.By inheriting GenericServlet class, (or)
4.By inheriting HttpServlet class
The mostly used approach is by extending HttpServlet because it provides http request
specific method such as doGet(), doPost(), doHead() etc.
Execution Process of Servlet Application
Once Tomcat is installed and configured, user can put it to work. Six steps take user from writing
their servlet to running it. These steps are as follows:
Execution Process of Servlet Application
1) Step 1 - Create a Directory Structure under Tomcat:
When you install Tomcat, several subdirectories are automatically created under the Tomcat home directory
(%TOMCAT_HOME%). One of the subdirectories is webapps. The webapps directory is where you store your
web applications. A web application is a collection of servlets and other contents installed under a specific
subset of the server's URL namespace. A separate directory is dedicated for each servlet application.
2) Step 2 - Write the Servlet Source Code:
In this step, you prepare your source code. You can write the source code yourself using your favorite text
editor or copy it from the CD included with the book.
The code in Listing 1.1 shows a simple servlet called TestingServlet. The file, named TestingServlet.java, sends
to the browser a few HTML tags and some text. For now, don't worry if you haven't got a clue about how it
works.
3) Step 3 - Compile Your Source Code:
For your servlet source code to compile, you need to include in your CLASSPATH environment variable the path
to the servlet.jar file. The servlet.jar is located in the common\lib\ subdirectory under %CATALINA_HOME%.
If you are using Windows, remember that the new environment variable takes effect only for new console
windows. In other words, after changing a new environment variable, open a new console window for typing
your command lines.
4) Step 4 - Create the Deployment Descriptor:
A deployment descriptor is an optional component in a servlet application, taking the form of an XML
document called web.xml. The descriptor must be located in the WEB-INF directory of the servlet
application. When present, the deployment descriptor contains configuration settings specific to that
application. Deployment descriptors are discussed in detail in Chapter 16. "Application Deployment."
5) Step 5 - Run Tomcat:
If it is not already running, you need to start Tomcat. For information on how to do that, see Appendix
A, "Tomcat Installation and Configuration."
6) Step 6 - Call Your Servlet from a Web Browser:
You are ready to call your servlet from a web browser. By default, Tomcat runs on port 8080 in myApp
virtual directory under the servlet subdirectory. The servlet that you just wrote is named Testing. The
URL for that servlet has the following format:
http://domain-name/virtual-directory/servlet/servlet-name
Session Tracking in Servlets
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques.
Each time user requests to the server, server treats the request as the new request. So we need
to maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the
figure given below:
Once we provide the communication between html form and servlet, we can access html form
data in servlet.
• Declaration Tags:
This Tag is used for declare the variables. Along with this, Declaration Tag can also declare
method and classes. Jsp initializer scans the code and find the declaration tag and initialize all the
variables, methods and classes. JSP container keeps this code outside of the service method
(_JSPService()) to make them class level variables and methods.
Syntax of JSP declaration tag
e.g.
<%! field or method declaration %> <%!
String str=“Hello”;
Note: It is very important to place a semicolon at the end of int a=10; public int sum();
each code placed inside declaration tag. %>
Scriptlet Tag
Scriptlet Tag allows you to write java code inside JSP page. Scriptlet tag implements
the _jspService method functionality by writing script/java code.
Syntax of Scriptlet Tag is as follows :
<html>
<head>
<% JAVA CODE %>
<title>My First JSP Page</title>
</head>
<%! int count = 0;
%>
<body>
Page Count is <% out.println(++count);%>
</body>
</html>
expression tag
The code placed within JSP expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to print the values
of variable or method.
Syntax of JSP expression tag <html>
<%= statement %> <body>
<%= "welcome to jsp" %>
</body>
</html>
Note: Do not end your statement with semicolon in case of expression tag.
JSP Directives and it’s Attribute
The majore purpose of directives tag is
• Add the page specific attribute on jsp page.
• Include the another page content in jsp page.
• Use the external tag libraries in jsp page
General Syntax:
<%@ attribute subattribute=“value” %>
There are major 3 attribute of directives tag
1. Page attribute:
The page attribute is used for apply the page specific attribute on JSP. This attribute provides
the some sub attributes like as
import
contentType
isErrorPage
errorPage
session
bufferSize
autoFlush etc
• import
The import attribute is used to import class,interface or all the members of a package.It is
similar to import keyword in java class or interface.
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
• contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of
the HTTP response.The default value is "text/html;
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>
• isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.
<html>
<body>
<%@ page isErrorPage="true" %>
Sorry an exception occured!<br/>
The exception is: <%= exception %>
</body>
</html>
• errorPage
The errorPage attribute is used to define the error page, if exception occurs in the current page,
it will be redirected to the error page.
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>
2. Include Directive
The include directive is used to include the contents of any resource it may be jsp file, html
file or text file. The include directive includes the original content of the included resource at
page translation time (the jsp page is translated only once so it will be better to include static
resource).
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
Comment Tag
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is
useful when you want to hide or "comment out", a part of your JSP page.
Following is the syntax of the JSP comments −
<html> <%-- This is JSP comment --%>
<head>
<title>
A CommentTest </title>
</head>
<body> <h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
Step1 : create HTML page
Step2: create JSP page
Step 3: establish communication between JSP
and HTMl(include form tag in your Html form)