0% found this document useful (0 votes)
13 views35 pages

Lecture 3.1

The document provides an overview of servlets in Java, focusing on their lifecycle, types, and advantages over CGI. It explains the architecture of web applications, the role of web containers, and the servlet lifecycle methods including init, service, and destroy. Additionally, it includes a simple servlet example and deployment descriptor details.

Uploaded by

anuragjangid6373
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views35 pages

Lecture 3.1

The document provides an overview of servlets in Java, focusing on their lifecycle, types, and advantages over CGI. It explains the architecture of web applications, the role of web containers, and the servlet lifecycle methods including init, service, and destroy. Additionally, it includes a simple servlet example and deployment descriptor details.

Uploaded by

anuragjangid6373
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

INSTITUTE : UIE

DEPARTMENT : CSE
Bachelor of Engineering (Computer Science
& Engineering)
PROJECT BASED LEARNING IN JAVA WITH LAB
(22CSH-359/22ITH-359)

TOPIC OF PRESENTATION:
Servlet Lifecycle, Generic Servlet, Http
Servlet, Linking Servlet to HTML (CO 5)
DISCOVER . LEARN .
EMPOWER
Lecture Objectives

In this lecture, we will


discuss:
•Servlet Lifecycle, Generic
Servlet, Http Servlet, Linking
Servlet to HTML

2
Introduction to Servlets

3
Server-side Programming
• Static HTTP transaction - Browser requests for index.html,
and Server responds with HTML file

index.html
1. Browser Request 2. Server Finds File
Reads the File
<html> ….
</html>
4. Browser Displays Page 3. Server Response

HTTP (Hyper Text Transport Protocol) is the protocol


that clients and servers use on the web to communicate

4
Server-side Programming (Contd.).
• Dynamic HTTP transaction - Browser requests
OrderServlet.class, server runs program
that HTML, server returns HTML to browser creates
Web Server
.php /
.cgi
1. Browser Request 2. Executes server program
3. May communicate with Database
<html> ….
4. Creates HTML
</html> 5. Server returns HTML Response
6. Browser Displays Page
5
3

Database

5
Web Server
• A computer having server software installed within it which
serves up web pages
• A program that uses client/ server model and World Wide
Web’s Hypertext Transfer Protocol (HTTP)
• Responsible for accepting HTTP requests from clients
(web browsers) and serving HTTP responses which are
web pages such as HTML documents
• Popular web servers
– Apache HTTP Server (Apache)
– Microsoft Internet Information Server (IIS)
– Sun Java System Web Server

6
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++
, perl.
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 threads are low. The advantages of Servlet are as follows:
1.Better performance: because it creates a thread for each request,
not process.
2.Portability: because it uses Java language.
3.Robust: JVM
4.manages Servlets, so we don't need to worry about the memory
leak, garbage collection
5., etc.
Java server-side web components
• A web component is a software entity that runs on a web server
– Provides it with the capabilities needed for dynamically handling
client requests and generating web presentation content

• The J2EE specification defines two types of web components


– Servlets
– Java Server Pages(JSPs)

Database
Application Client EJB

Web Client JSP / Servlets EJB Database

Client Tier Web Tier Business Tier EIS Tier


Client Environment J2EE Server Database Server

J2EE Application N-Tiered Architecture

11
What are Servlets?
• A Java class that runs on a web server and dynamically
handles client requests

• It extends the functionality of a web server by


receiving client requests and dynamically generating a
response

• Since servlets are Java-based, they are


platform independent

12
Uses of Servlets
• Processing and/or storing data submitted by an HTML form
– Example: Processing data of a login form

• Providing dynamic content


– Example: Returning results of a database query to the
client

• Managing state information on top of the stateless HTTP


– Example: For an online shopping cart system which
manages shopping carts for many concurrent customers
and maps every request to the right customer

13
Servlet Architecture Overview
• Java Servlet API are in
packages javax.servlet and
javax.servlet.http
Servlet interface
– Provide interfaces and
classes for writing
servlets
GenericServlet class
• All servlets must implement
Servlet interface
– Defines life-cycle methods
HttpServlet class
• Extend GenericServlet
class
– To implement generic LoginServlet
services (a user-defined servlet)

14
• Extend HttpServlet class
Deploying a Simple Servlet

15
Directory Structure of a Web application
MyWebApplication

WEB-INF

jsp files html files

classes lib tags

web.xml
*.tld

All server-side Library All .tag files


.class files Archive files
14
Demo for a Simple Servlet
• A simple HTTP Servlet that displays a Welcome message
on the web page

• Files required:
– WelcomeServlet.java
– web.xml

15
Demo for a Simple Servlet (Contd.).
• An HTTP Servlet that displays a Welcome message

import java.io.*;
import javax.servlet.*;
import
javax.servlet.http.*;

public class
WelcomeServlet
extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html"); // set header field first
PrintWriter pw = res.getWriter(); // then get writer & write response data
pw.println("<HTML>");
pw.println("<HEAD><TITLE>Welcome</TITLE></HEAD>");
pw.println("<BODY>");
pw.println("<H3>” + “Welcome to Java Servlet Technology!!” + "</H3>");
pw.println("</BODY>");
pw.println("</HTML>"); pw.close();
//closes the 16
writer
The Web Deployment Descriptor – web.xml

• An XML file web.xml is a deployment descriptor that describes


– mapping from URIs to application resources
– initialization parameters
– security constraints
– registration of listeners and filters
• Example: web.xml

<web-app>
<display-name>A Small Web Application</display-name>
<servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/welcome.msg</url-pattern>
</servlet-mapping>
</web-app>
17
Web Container
Web components and their container run on J2EE server
• Provides execution environment for servlets and JSPs of
a
web application
• Manages execution of JSP and servlet components for J2EE
applications

Fig: J2EE Server and Container Types

18
Role of a Web Container
• Communication Support
– Provides an easy way for servlets to talk to web server

• Lifecycle Management
– Controls lifecycle of servlets

• Multithreading Support
– Automatically creates a new Java thread for every servlet request
it receives
• Declarative Security
– Enables to configure security in an XML deployment descriptor
thereby avoiding hard-coding it in servlet or any other class code
• JSP Support
– Does JSP processing

19
How web container handles Servlet requests

• Container creates 2 objects on receiving a request for a servlet:


HttpServletRequest and HttpServletResponse
• Finds right servlet based on URL in the request
• Creates a thread for that request
• Passes request and response objects to the servlet thread
• Calls servlet’s service() method
– The service() method in turn calls doGet or doPost based on
type of request (Assume request was an HTTP GET)
– The doGet method generates dynamic page and captures it
in response object
• Converts response object into an HTTP response on completion
of thread
• Sends this response to the client
• Finally deletes the request and response objects
20
Knowledge Checkpoint
1. Suppose you are a web developer working for an Online Movie Service.
You want to use a servlet called MovieServlet so that clients can access
the latest film shows for the day in a particular city from your movie
database. Determine the correct sequence of following steps carried out by
MovieServlet when processing a request from a client

Sl.No Description
1 Check information included in the Http request
2 Access any necessary business components or
data storage
3 Set the appropriate Http response parameters
4 Read data submitted by the client
5 Send the response to the client
6 Format the results in a response

21
Servlet Life Cycle

22
Life Cycle of a Servlet
• An HTTP servlet's life cycle is controlled by the
web container where it is deployed

Source: http://www.iam.ubc.ca/guides/javatut99/servlets/lifecycle/index.html

23
Servlet interface
• Provides methods that manage the servlet and its communications
with clients

– init(ServletConfig)
Initializes the servlet. Runs once before any requests can be serviced

– service(ServletRequest, ServletResponse)
Processes a single request from the client

– destroy()
This method releases all the resources

– getServletConfig()
Returns a servlet config object and this object contains any initialization
parameters and startup configuration information for this servlet

– getServletInfo()
Returns a string containing information about the servlet, such as its
author, version, and copyright
24
Lifecycle Methods
• Interaction between a web server, a servlet, and a client
is controlled using the life-cycle methods
• A servlet's life cycle methods are
– init()
– service()
– destroy()

• The init() and destroy() methods will be called only once


during the life time of your Servlet
• The service() and it's broken down methods ( doGet(),
doPost() etc ) will be called as many times as requests
are received for them by the web container

25
Initializing a servlet
• Web container initializes servlet after web container loads
and instantiates servlet class and before it delivers requests from
clients

• The init method is invoked only once during servlet's lifetime – when
servlet is first created

• Override init method of Servlet interface if you want the servlet to


– Read persistent configuration data
– Initialize resources
– Perform any other one-time activities

• Two versions of init method – one that takes no arguments and one
that takes a ServletConfig object as an argument
– init( ) - use this when your servlet does not need any
specific
initialization
– init(ServletConfig) - use this when your servlet needs
26
Servicing client requests
• Once servlet is loaded and initialized, the servlet is able to handle
client requests
• Web container processes the requests in servlet’s service method
• Every time the server receives an incoming request for a servlet, it
generates a new thread and calls the service method
• The service method then checks the HTTP request type and calls the
appropriate doXXX method
• Syntax: public void service(ServletRequest req,
ServletResponse
res)
• Role of service method
– To extract information from the request
– Access external resources
– Populate the response based on that information
27
Destroying a Servlet
• Server may unload a servlet instance
– If the servlet has been idle for some time (default is 30
minutes) or
– If the web application is undeployed or
– If server shuts down

• Before it removes the servlet, it calls destroy method only once

• Before servlets get destroyed, this method helps in


– Cleanup operations such as closing database
connections
– Halting background threads
– Releasing other resources such as IO streams
• Syntax: public void destroy()
28
Quiz
1. The doGet() or doPost() method of a Servlet are
invoked by
1. init() method
2. service() method
3. destroy() method

• --------------- is the deployment descriptor file for


Servlets
1. servlet-config.xml
2. web.xml
3. struts-config.xml

30
Summary:

In this session, you were able to :


• Servlet Lifecycle, Generic Servlet, Http
Servlet, Linking Servlet to HTML
References:
Books:
1. Balaguruswamy, Java.
2. A Primer, E.Balaguruswamy, Programming with Java, Tata McGraw Hill
Companies
3. John P. Flynt Thomson, Java Programming.

Video Lectures :
https://youtu.be/TrfqKn6vzAI
Reference Links:

https://www.javatpoint.com/life-cycle-of-a-servlet
https://www.javatpoint.com/HttpServlet-class
https://www.javatpoint.com/GenericServlet-class
https://www.javatpoint.com/Servlet-interface
https://beginnersbook.com/2014/04/genericservlet-class/
https://docs.oracle.com/javaee/7/tutorial/servlets002.htm
https://javaee.github.io/servlet-spec/downloads/servlet-3.1/Final/servlet-
3_1-final.pdf
THANK YOU

You might also like