Servlets
Servlets
SERVLETS
9/15/20
Servers
A server is a computer that responds to requests from a
client.
Typical requests: provide a web page, upload or download a file,
send email
Web server maps HTTP request to the corresponding servlet.
2
EX:
Apache Tomcat web server
Internet Information services
Google web server
PWS(personal web server)
3
Client & Server
4
HTTP
HTTP is a protocol that clients and servers use on the
web to communicate.
HTTP is a stateless protocol
The client sends an HTTP request and the server
answers with an HTML page to the client, using
HTTP.
5
CGI Scripts
CGI stands for “Common Gateway Interface”
6
CGI
7
Servlets
A servlet is like an applet, but on the server side
8
servlet
9
Servlets vs. CGI scripts
Advantages:
◦ Running a servlet doesn’t require creating a separate
process each time
◦ A servlet stays in memory, so it doesn’t have to be
reloaded each time
◦ Performance is significantly better.
◦ Servlets are platform-independent because they are
written in Java.
Disadvantage:
◦ Less choice of languages (CGI scripts can be in any
language)
10
How a Servlet works
1.User sends request for a servlet by clicking a link that has URL to a servlet.
11
2. The container finds the servlet using deployment descriptor and
creates two objects :HttpServletRequest
HttpServletResponse
12
3.Then the container creates or allocates a thread for that request and
calls the Servlet's service()method and passes the request,
response objects as arguments.
13
4.The service() method, then decides which servlet
method, doGet() or doPost() to call, based on HTTP Request
Method(Get, Post etc) sent by the client. Suppose the client
sent an HTTP GET request, so the service() will call
Servlet's doGet() method.
14
5.Then the Servlet uses response object to write the
response back to the client.
15
6.After the service() method is completed the thread dies.
And the request and response objects are ready
for garbage collection.
16
How container handles the request
Life cycle of a servlet
The servlet loads & initializes it using the init( )
method.
The servlet handles one or more client requests using
service ( ) methods.
The servlet is deactivated when the destroy( )
method is called or when the server is terminated.
20
Call to the service() method : The containers call
the service() method each time the request for
servlet is received. The service() method will then
call the doGet() or doPost() methods based on the
type of the HTTP request.
Call to destroy() method: The Web Container call
the destroy() method before removing servlet
instance, giving it a chance for cleanup activity.
21