Vous êtes sur la page 1sur 20

Servlets

(Part-I)

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
A server is also the software that responds to these requests;
a client could be the browser or other software making these
requests
Typically, our little computer is the client, and someone elses
big computer is the server
However, any computer can be a server
It is not unusual to have server software and client software
running on the same computer

Apache
Apache is a very popular server
66% of the web sites on the Internet use Apache

Apache is:
Full-featured and extensible
Efficient
Robust
Secure (at least, more secure than other servers)

Up to date with current standards


Open source
Free

CGI (Common Gateway Interface)


CGI, was one of the first practical techniques for creating
dynamic content.
CGI is a language-independent interface that allows a
server to start an external process which gets information
about a request through environment variables, the
command line and its standard input stream and writes
response data to its standard output stream.
Each request is answered in a separate process by a separate
instance of the CGI program, or CGI script.

Client sends a request to the server.


Server starts a CGI script
Scripts compute result for server & quits
Server sends response to client.
Another client sends a request
Server starts the CGI script again.

client

client

Server

J2EE Architecture

What is a Servlet ?

Servlets are small programs that execute on the server side of a


Web connection and build Web pages.

A Servlet is a Java component that can be plugged into a Java-enabled


web server to provide custom services.

Java Servlet
is a simple, consistent mechanism for extending the
functionality of a web server
Are precompiled Java programs that are executed on the server
side.
Require a Servlet container to run in

Servlets are designed to work within a request/response processing


model.

Requests can come in the form of an HTTP, URL, FTP or a custom


protocol.

Servlets
A servlet is like an applet, but on the server side.
Unlike applets, servlets do not display GUI, its work is done
behind the scenes on the server and only the results of the
servlets processing are returned to the client.
Client sends a request to server

Server starts a servlet


Servlet computes a result for server and does not quit
Server returns response to client

Client

Another client sends a request


Server calls the servlet again
Etc.

Server

Client
Servlet

Why are Servlets better than CGI?

Advantages:
Efficient: Performance is better, as running a servlet doesnt require creating a separate
process each time. A servlet stays in memory, so it doesnt have to be reloaded each time.
There is only one instance handling multiple requests, not a separate instance for every
request.

Powerful: Java servlets let you easily do several things that are difficult or impossible with
regular CGI. Servlets can also share data among each other, making useful things like
database connection pools easy to implement.

Convenient. We already know Java. Why learn Perl too? Besides the convenience of
being able to use a familiar language, servlets have an extensive infrastructure for
automatically parsing and decoding HTML form data, reading and setting HTTP headers,
handling cookies, tracking sessions, and many other such utilities.
Portable. Servlets are written in Java and follow a well-standardized API.
Inexpensive: once you have a Web server, no matter the cost of that server, adding
servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or
cheap.
Security: Java security manager on the server enforces a set of restrictions to protect
resources on a server machine.

Disadvantage:
Less choice of languages (CGI scripts can be in any language)

When a user enters a URL to browser, the browser generates


an HTTP request to the appropriate Web Server.
The Web Server transfers the control to the servlet.
Now servlet deals with all the incoming request from various
clients.

Advantages of Servlets over competing technologies


Capable of running in the same process space as the Web ServerServlets are capable of doing this while CGI require programs to run as separate
process when servicing client request. The overhead involved with creating a new
process for every request incurs a large performance penalty.

Complied Servlets are complied into byte-code, thus can execute more quickly
than common scripting languages. Servlet -side just-in-time compliers also
dramatically improve the performance of the JVM. Complied code is more compact
and secure than non-complied options.

Crash-resistant - Nothing is total crash proof, but as they are written in Java and
complied on JVM, they are more crash-resistant. JVM does not allow servlets direct
access to memory locations, thereby eliminating crashes that result from invalid
memory access.

Cross-Platform As servlets are written completely in Java, thus they provide


platform independence.

Cross Server Servlets can run on virtually every popular server in use today.

Advantages of Servlets over competing technologies

Durable Servlets are durable objects. Durable means that they remain in the
memory until specifically instructed to be destroyed. Thus, servlets only need to be
instantiated a single time in order to service many requests.

Dynamic Loading Servlets can be dynamically loaded either locally or across


network. i.e. they are loaded only when needed and ensure that unused servlets do
not consume precious server resources. The ability to load servlets across network is
a great advantage for distributed computing environment.

Extensible As written in Java, there is a wealth of third-party support for writing


and extending them.

Multithreaded They support multithreaded functionality. With this feature they


allows clients request to be handled by separate threads within a single process.
Thus, require less resources and execute more quickly.

Protocol Independent Though servlets are commonly used to extend HTTP,


but they are completely protocol independent. Thus, they support FTP commands,
SMTP, Telnet sessions, newsgroup or any other protocol.

Written in Java

What can Servlets Do?


1. Dynamically built and return an HTML file based on the nature of the client
request.
2. Process user input passed by an HTML form and return an appropriate
response.
3. Provide user authentication and other security mechanisms
4. Interact with server resources such as databases, other applications and
network files to return useful information to the client.
5. Allow the server to communicate with a client applet via a custom protocol
and keep the connection open throughout the conversation.
6. Forward requests from one server to another for load balancing process.
7. Partition a single logical service across servers or between servlets in order
to process the task most efficiently.
8. Process input from many clients for interaction among peers for application
such as multiplayer games.

The Servlet Life Cycle


A Java servlet has a life cycle that defines how the servlet is loaded
and initialized, how it receives and responds to request and how it is
taken out of service.
The web server is responsible for initializing, invoking, and destroying
each servlet instance.
Each servlet has the same life cycle:
A server loads and initializes the servlet
The servlet handles zero or more client requests
The server removes the servlet
(some servers do this step only when they shut down)
The servlet lifecycle is defined by the interface, javax.servlet.Servlet.
This interface defines methods that are called at specific times in a
specific order during the servlet lifecycle. Its three main methods are :
init()
service()
destroy()

Servlet Life Cycle

Servlet Life Cycle


Initialization
(init method)
Ready
(Service method)

Instantiation and Loading


(Servlet engine can instantiate more
than one servlet instance)

Destruction
(Destroy method)
Servlet Class

Garbage Collection

What is preinitialization of a java servlet?


In the java servlet life cycle, the first phase is called Creation and
initialization.
The java servlet container first creates the servlet instance and then
executes the init() method.
This initialization can be done in following ways.
The default way is that, the java servlet is initialized when the servlet is
called for the first time. This type of servlet initialization is called lazy loading.
The other way is through the <load-on-startup>non-zero-integer</load-onstartup> tag using the deployment descriptor web.xml. This makes the java
servlet to be loaded and initialized when the server starts. This process of
loading a java servlet before receiving any request is called preloading or
preinitialization of a servlet.
Servlet are loaded in the order of number (non-zero-integer) specified.
That is, lower the load-on-startup value is loaded first and then servlet with
higher values are loaded.
Example usage:
<servlet>
<servlet-name>Servlet-URL</servlet-name>
<servlet-class>com.javapapers.Servlet-Class</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>

1. init()
When a server loads a servlet, it runs the servlet's init() method.
Even though most servlets are run in multi-threaded servers, there are no
concurrency issues during servlet initialization.
This is because the server calls the init method once, when it loads the
servlet, and will not call it again unless it is reloading the servlet.
The server can not reload a servlet until after it has removed the servlet by
calling the destroy method.
Initialization is allowed to complete before client requests are handled (that
is, before the service method is called) or the servlet is destroyed.

When a servlet is first started up, its init (ServletConfig config) method is
called
init should perform any necessary initializations
init is called only once, and does not need to be thread-safe

2. service()
The service() method is the heart of the servlet.
Each request message from a client results in a single call to the servlet's
service() method.

Servlet creates separate threads for each request.


The servlet container calls the service() method for servicing any request.

The service() method determines the kind of request and calls the
appropriate method (doGet() or doPost()) for handling the request and
sends response to the client using the methods of the response object.
Every servlet request results in a call to
service(ServletRequest request, ServletResponse response)
service calls another method depending on the type of service
requested
Usually you would override the called methods of interest, not service
itself
service handles multiple simultaneous requests, so it and the methods
it calls must be thread safe.

3. destroy()

When a server removes a servlet, it runs the servlet's destroy method.

The method is run once; the server will not run it again until after it reloads
and reinitializes the servlet.

The destroy() method is called to allow your servlet to clean up any


resources (such as open files or database connections) before the servlet
is unloaded. If you do not require any clean-up operations, this can be an
empty method.

Servlet instance is deleted or garbage collected by the container only


when the web server issues shut down or the instance is not used for a
long time.

When the servlet is shut down, destroy() is called


destroy is called only once, but must be thread safe (because other
threads may still be running)

Tomcat
Tomcat is the Servlet Engine than handles servlet
requests for Apache
Tomcat is a helper application for Apache
Its best to think of Tomcat as a servlet container

Apache can handle many types of web services


Apache can be installed without Tomcat
Tomcat can be installed without Apache

Its easier to install Tomcat standalone than as part of


Apache
By itself, Tomcat can handle web pages, servlets, and JSP

Apache and Tomcat are open source (and therefore


free)
It contains the class libraries, documentation and runtime support to create and test servlets.

Vous aimerez peut-être aussi