U 5 Servlet
U 5 Servlet
U 5 Servlet
(KIT-501)
Unit-5
Servlet
Dr. Ruchi Gupta
Department of Information Technology
AKGEC, Ghaziabad
Course Outline:-
UNIT-5
• Servlets: Servlet Overview and Architecture, Interface Servlet and the
Servlet Life Cycle, Handling HTTP get Requests, Handling HTTP post
Requests, Redirecting Requests to Other Resources, Session Tracking,
Cookies, Session Tracking with Http Session.
• Java Server Pages (JSP): Introduction, Java Server Pages Overview, A
First Java Server Page Example, Implicit Objects, Scripting, Standard
Actions, Directives, Custom Tag Libraries.
Servlet basic
• Servlet technology is used to create web application (resides at server
side and generates dynamic web page).
• Servlet technology is robust and scalable because of java language.
• Before Servlet, CGI (Common Gateway Interface) scripting language
was popular as a server-side programming language. But there were
many disadvantages of this technology.
Servlets
• 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.
• Properties of Servlets are as follows:
• Servlets work on the server-side.
• Servlets are capable of handling complex requests obtained from the
webserver.
Servlet
• Servlet can be described in many ways, depending on the context.
• Servlet is a technology i.e. used to create web application.
• Servlet is an API that provides many interfaces and classes including documentations.
• Servlet is an interface that must be implemented for creating any servlet.
• Servlet is a class that extend the capabilities of the servers and respond to the incoming
request. It can respond to any type of requests.
• Servlet is a web component that is deployed on the server to create dynamic web page.
Servlet Architecture
• Execution of Servlets basically involves six basic steps:
1. The clients send the request to the webserver.
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.
Advantage 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 a lot of benefits over the
Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low. The basic benefits of servlet are as follows:
• better performance: because it creates a thread for each request not process.
• Portability: because it uses java language.
• Robust: Servlets are managed by JVM so no need to worry about memory leak,
garbage collection etc.
• Secure: because it uses java language..
• The server-side extensions are nothing but the technologies that are used to create
dynamic Web pages.
• Actually, to provide the facility of dynamic Web pages, Web pages need a container or
Web server.
• To meet this requirement, independent Web server providers offer some proprietary
solutions in the form of APIs(Application Programming Interface).
• These APIs allow us to build programs that can run with a Web server. In this case, Java
Servlet is also one of the component APIs of Java Platform Enterprise Edition which
sets standards for creating dynamic Web applications in Java.
• Before learning about something, it’s important to know the need for that something, it’s
not like that this is the only technology available for creating dynamic Web pages.
• The Servlet technology is similar to other Web server extensions such as Common
Gateway Interface(CGI) scripts and Hypertext Preprocessor (PHP). However, Java
Servlets are more acceptable since they solve the limitations of CGI such as low
performance and low degree scalability.
CGI (Common Gateway Interface)
• CGI is actually an external application that is written by using any of the
programming languages like C or C++ and this is responsible for processing
client requests and generating dynamic content.
In CGI application, when a client makes a request to access dynamic Web
pages, the Web server performs the following operations :
• It first locates the requested web page i.e the required CGI application using
URL.
• It then creates a new process to service the client’s request.
• Invokes the CGI application within the process and passes the request
information to the application.
• Collects the response from the CGI application.
• Destroys the process, prepares the HTTP response, and sends it to the client.
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:
• If number of clients’ increases, it takes more time for sending response.
• For each request, it starts a process and Web server is limited to start processes.
• It uses platform dependent language e.g. C, C++, perl.
Servlet CGI(Common Gateway Interface)
Servlets can directly communicate with the CGI cannot directly communicate with the
webserver. webserver.
Servlets are less expensive than CGI. CGI is more expensive than Servlets.
Servlets can handle the cookies. CGI cannot handle the cookies.
Servlet Terminology
There are some key points that must be known by the servlet programmer
like server, container, get request, post request etc. Let's first discuss these
points before starting the servlet technology.
The basic terminologies used in servlet are given below:
▪ HTTP
▪ HTTP Request Types
▪ Difference between Get and Post method
▪ Container
▪ Server and Difference between web server and application server
▪ Content Type
▪ Introduction of XML
▪ Deployment
1. HTTP (Hyper Text Transfer Protocol)
• Http is the protocol that allows web servers and browsers to exchange data over the
web.
• It is a request response protocol.
• Http uses reliable TCP connections by default on TCP port 80.
• It is stateless means each request is considered as the new request. In other words,
server doesn't recognize the user by default.
2. Http Request Methods
Every request has a header that tells the status of the client. There are many request
methods. Get and Post requests are mostly used.
The http request methods are:
✔ GET
✔ POST
✔ HEAD
✔ PUT
✔ DELETE
✔ OPTIONS
✔ TRACE
Http Request Methods
HTTP Request Description
GET Asks to get the resource at the requested URL.
POST Asks the server to accept the body info attached. It is like GET request with extra
info sent with the request.
HEAD Asks for only the header part of whatever a GET would return. Just like GET but
with no body.
TRACE Asks for the loopback of the request message, for testing or troubleshooting.
PUT Says to put the enclosed info (the body) at the requested URL.
DELETE Says to delete the resource at the requested URL.
OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can
respond
3. Get vs. Post
There are many differences between the Get and Post request. Let's see these
differences:
GET POST
1) In case of Get request, only limited amount of In case of post request, large amount of data can be
data can be sent because data is sent in header. sent because data is sent in body.
2) Get request is not secured because data is exposed in Post request is secured because data is not exposed
URL bar. in URL bar.
3) Get request can be bookmarked. Post request cannot be bookmarked.
4) Get request is idempotent. It means second request Post request is non-idempotent.
will be ignored until response of first request is delivered
5) Get request is more efficient and used more than Post. Post request is less efficient and used less than get.
4. Container
• It provides runtime environment for JavaEE (j2ee) applications.
It performs many operations that are given below:
• Life Cycle Management
• Multithreaded support
• Object Pooling
• Security etc.
5. Server
• It is a running program or software that provides services.
There are two types of servers:
• Web Server
• Application Server
Web Server
• Web server contains only web or servlet container.
• It can be used for servlet, jsp, struts, jsf etc.
• It can't be used for EJB.
• Examples of Web Servers are: Apache Tomcat and Resin.
Application Server
• Application server contains Web and EJB containers. It can be used for servlet,
jsp, struts, jsf, ejb etc.
Examples of Application Servers are:
• JBoss Open-source server from JBoss community.
• Glassfish provided by Sun Microsystem. Now acquired by Oracle.
• Weblogic provided by Oracle. It more secured.
• Websphere provided by IBM.
6. Content Type
• Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a HTTP
header that provides the description about what are you sending to the browser.
There are many content types:
• text/html
• text/plain
• application/msword
• application/vnd.ms-excel
• application/jar
• application/pdf
• application/octet-stream
• application/x-zip
• images/jpeg
• video/quicktime etc.
7. XML: CREATE THE DEPLOYMENT DESCRIPTOR (WEB.XML FILE)
web.xml file
<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Servlet API
• The javax.servlet and javax.servlet.http packages represent interfaces
and classes for servlet API.
• The javax.servlet package contains many interfaces and classes that
are used by the servlet or web container. These are not specific to any
protocol.
• The javax.servlet.http package contains interfaces and classes that are
responsible for http requests only.
Interfaces in javax.servlet package
There are many interfaces in javax.servlet package. They are as follows:
• Servlet
• ServletRequest
• ServletResponse
• RequestDispatcher
• ServletConfig
• ServletContext
• SingleThreadModel
• Filter
• FilterConfig
• FilterChain
• ServletRequestListener
• ServletRequestAttributeListener
• ServletContextListener
• ServletContextAttributeListener
Classes in javax.servlet package
There are many classes in javax.servlet package. They are as follows:
• GenericServlet
• ServletInputStream
• ServletOutputStream
• ServletRequestWrapper
• ServletResponseWrapper
• ServletRequestEvent
• ServletContextEvent
• ServletRequestAttributeEvent
• ServletContextAttributeEvent
• ServletException
• UnavailableException
Interfaces in javax.servlet.http package
There are many interfaces in javax.servlet.http package. They are as
follows:
• HttpServletRequest
• HttpServletResponse
• HttpSession
• HttpSessionListener
• HttpSessionAttributeListener
• HttpSessionBindingListener
• HttpSessionActivationListener
• HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as
follows:
• HttpServlet
• Cookie
• HttpServletRequestWrapper
• HttpServletResponseWrapper
• HttpSessionEvent
• HttpSessionBindingEvent
• HttpUtils (deprecated now)
Life Cycle of a Servlet
• 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. So, before creating a Servlet object,
let’s first understand the life cycle of the Servlet object which is
actually understanding how the Servlet container manages the Servlet
object.
• 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.
Life Cycle of a Servlet
1. 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 object of the Servlet. To create a new
instance of the Servlet, the container uses the no-argument constructor.
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 Servlet.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.
1. Now, if the Servlet fails to initialize, then it informs the Servlet
container by throwing
the ServletException or UnavailableException.
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 objects. 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.
2. 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.
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.
There are three life cycle
methods of a Servlet :
• init()
• service()
• destroy()
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.
• The init method is designed to be called only once. If an instance of the servlet does not exist, the web
container:
1. Loads the servlet class
2. Creates an instance of the servlet class
3. Initializes it by calling the init method
• The init method must complete successfully before the servlet can receive any requests. The servlet
container cannot place the servlet into service if the init method either throws a ServletException or does
not return within a time period defined by the Web server.
//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 is only called after the servlet’s init() method has completed successfully.
• The Container calls the service() method to handle requests coming from the client, interprets the HTTP
request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as
appropriate.
This method uses ServletRequest object to collect the data requested by the client.
This method uses ServletResponse object to generate the output content.
// service() method
• //destroy() method
• A session is a conversation between the server and a client .We all know that
HTTP protocol is a stateless protocol which means no user information is
pertained and server considers every request as a new request.
• Why do we need session tracking? Think of the scenario where a series of
request and response takes place between same client and a server (for
example online shopping system ) so to maintain the conversational state ,
session tracking is needed.
• 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:
Session Tracking Techniques