0% found this document useful (0 votes)
9 views5 pages

Java Servlets and Web Containers Explained

A Java Servlet is a class that extends server capabilities using a request-response model, commonly deployed in a Web container that manages its lifecycle. Servlet containers, both commercial and non-commercial, implement the Java Servlet specification and provide essential services like security and concurrency. The servlet lifecycle includes initialization, request handling, and destruction, with servlets offering advantages over traditional CGI scripts in terms of performance and resource management.

Uploaded by

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

Java Servlets and Web Containers Explained

A Java Servlet is a class that extends server capabilities using a request-response model, commonly deployed in a Web container that manages its lifecycle. Servlet containers, both commercial and non-commercial, implement the Java Servlet specification and provide essential services like security and concurrency. The servlet lifecycle includes initialization, request handling, and destruction, with servlets offering advantages over traditional CGI scripts in terms of performance and resource management.

Uploaded by

Martin Mulwa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

 Java Servlet

-A servlet is a Java programming language class used to extend the capabilities of servers that host applications
accessed via a request-response programming model. Although servlets can respond to any type of request, they
are commonly used to extend the applications hosted by Web servers. Thus, it can be thought of as a Java
Applet that runs on a server instead of a browser.

-To deploy and run a Servlet, a Web container must be used. A Web container is essentially the component of a
Web server that interacts with the servlets. The Web container is responsible for managing the lifecycle of
servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access
rights.

 Web container
Web container (also known as a Servlet container) is the component of a web server that interacts with the
servlets. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular
servlet and ensuring that the URL requester has the correct access rights.

-A web container implements the web component contract of the Java EE architecture, specifying a runtime
environment for web components that includes security, concurrency, lifecycle management, transaction,
deployment, and other services. A web container provides the same services as a JSP container as well as a
federated view of the Java EE platform APIs.
o
 List of Servlet containers
-The following is a list of software programs that implement the Java Servlet specification from Sun
Microsystems, divided depending on whether they are directly sold or not.

a) Non-commercial Web containers


 Apache Tomcat (formerly Jakarta Tomcat) is an open source web container available under the Apache
Software License.
 Apache Geronimo is a full Java EE implementation by Apache.
 GlassFish (open source), from Sun Microsystems
 JBoss Application Server (open source) is a full Java EE implementation by Red Hat inc., division
JBoss.
 Jetty
 Jaminid contains a higher abstraction than servlets.
 Enhydra
 Winstone supports specification v2.5 as of 0.9, has a focus on minimal configuration and the ability to
strip the container down to only what you need.
 Tiny Java Web Server (TJWS) 2.5 [1], small footprint, modular design

b) Commercial Web containers


 BEA WebLogic Server or Weblogic Express, from BEA Systems
 Borland Enterprise Server
 Sun GlassFish Enterprise Server, from Sun Microsystems
 Sun Java System Web Server, from Sun Microsystems
 Sun Java System Application Server (is an Application Server, but includes a web container)
 JBoss Enterprise Application Platform (open source)
 JRun, from Adobe Systems (formerly developed by Allaire Corporation)
 LiteWebServer (open source)
 Oracle Application Server, from Oracle Corporation
 Orion Application Server, from IronFlare
 Caucho's Resin Server (open source)
 ServletExec, from New Atlanta Communications
 WebSphere, from IBM
 NetWeaver, from SAP
 tc Server (SpringSource)

-The servlet API, contained in the Java package hierarchy [Link], defines the expected interactions of the
Web container and a servlet.

A Servlet is an object that receives a request and generates a response based on that request. The basic servlet
package defines Java objects to represent servlet requests and responses, as well as objects to reflect the servlet's
configuration parameters and execution environment. The package [Link] defines HTTP-specific
subclasses of the generic servlet elements, including session management objects that track multiple requests
and responses between the Web server and a client. Servlets may be packaged in a WAR file as a Web
application.

-Servlets can be generated automatically from JavaServer Pages (JSP) by the JavaServer Pages compiler. The
difference between Servlets and JSP is that Servlets typically embed HTML inside Java code, while JSPs
embed Java code in HTML.

-A servlet is a Java component that can be plugged into a Java-enabled web server to provide custom services.
--These services can include:
New features
Runtime changes to content
Runtime changes to presentation
New standard protocols (such as FTP)
New custom protocols

Advantages over CGI


-Servlets are effectively a Java version of CGI scripts, which are written in Perl, C, C++, UNIX shell scripts,
etc. There are however, a few important differences.

-When a CGI program (or script) is invoked, what typically happens is that a new process is spawned to handle
the request. This process is external to that of the webserver and as such, you have the overhead of creating a
new process and context switching, etc.

-Java Servlets on the other hand actually run inside the webserver (or Servlet engine). The developer writes the
Servlet classes, compiles them and places them somewhere that the server can locate them. The first time a
Servlet is requested, it is loaded into memory and cached. From then on, the same Servlet instance is used, with
different requests being handled by different threads.

-Of course, being Java, the compiled Servlet classes can be moved from one Servlet compatible webserver to
another very easily. CGI programs or scripts on the other hand may be platform dependent, need to be
recompiled or even webserver dependent.

The advantages of using servlets are their fast performance and ease of use combined with more power over
traditional CGI (Common Gateway Interface). Traditional CGI scripts written in Java have a number of
disadvantages when it comes to performance:

 When an HTTP request is made, a new process is created for each call of the CGI script. This overhead
of process creation can be very system-intensive, especially when the script does relatively fast
operations. Thus, process creation will take more time than CGI script execution. Java servlets solve
this, as a servlet is not a separate process. Each request to be handled by a servlet is handled by a
separate Java thread within the Web server process, omitting separate process forking by the HTTP
daemon.
 Simultaneous CGI request causes the CGI script to be copied and loaded into memory as many times as
there are requests. However, with servlets, there are the same amount of threads as requests, but there
will only be one copy of the servlet class created in memory that stays there also between requests.
 Only a single instance answers all requests concurrently. This reduces memory usage and makes the
management of persistent data easy.
 A servlet can be run by a servlet engine in a restrictive environment, called a sandbox. This is similar to
an applet that runs in the sandbox of the Web browser. This makes a restrictive use of potentially
harmful servlets possible.

 Life cycle of a servlet


-During initialization stage of the Servlet life cycle, the web container initializes the servlet instance by
calling the init() method. The container passes an object implementing the ServletConfig interface via the
init() method. This configuration object allows the servlet to access name-value initialization parameters
from the web application.
 After initialization, the servlet can service client requests. Each request is serviced in its own separate
thread. The Web container calls the service() method of the servlet for every request. The service()
method determines the kind of request being made and dispatches it to an appropriate method to handle
the request. The developer of the servlet must provide an implementation for these methods. If a request
for a method that is not implemented by the servlet is made, the method of the parent class is called,
typically resulting in an error being returned to the requester.
 Finally, the Web container calls the destroy() method that takes the servlet out of service. The destroy()
method, like init(), is called only once in the lifecycle of a servlet.

-Three methods are central to the life cycle of a servlet. These are init( ), service( ), and destroy( ). They are
implemented by every servlet and are invoked at specific times by the server. Let us consider a typical user
scenario to understand when these methods are called.
1. Assume that a user enters a Uniform Resource Locator (URL) to a web browser.
o The browser then generates an HTTP request for this URL.
o This request is then sent to the appropriate server.
2. The HTTP request is received by the web server.
o The server maps this request to a particular servlet.
o The servlet is dynamically retrieved and loaded into the address space of the server.
3. The server invokes the init() method of the servlet.
o This method is invoked only when the servlet is first loaded into memory.
o It is possible to pass initialization parameters to the servlet so it may configure itself.
4. The server invokes the service() method of the servlet.
o This method is called to process the HTTP request.
o You will see that it is possible for the servlet to read data that has been provided in the HTTP
request.
o It may also formulate an HTTP response for the client.
5. The servlet remains in the server’s address space and is available to process any other HTTP requests
received from clients.
o The service() method is called for each HTTP request.
6. The server may, at some point, decide to unload the servlet from its memory.
o The algorithms by which this determination is made are specific to each server.
7. The server calls the destroy() method to relinquish any resources such as file handles that are allocated
for the servlet; important data may be saved to a persistent store.
8. The memory allocated for the servlet and its objects can then be garbage collected.
 Example1
-In our example form, only the value of the action attribute has to be changed in order to use a servlet instead of
a CGI script. It depends on the configuration of the web server where servlets reside. Usually, this is the
/servlet/ path.

<html>
<head><title>Cluster Analysis</title></head>
<body>
<form action="/servlet/ClusterAnalysis" method="GET">
How many clusters?
<input type=text name="clusters" size=3>
<input type=submit value=" OK ">
</form>
</body>
</html>

-Below is a simple HTTP servlet that processes the form above:

input.
import [Link].*;
import [Link].*;
import [Link].*;
public class ClusterAnalysis extends HttpServlet {
public String getServletInfo()
{ return "Cluster Analysis V 1.0"; }
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
String clusters[]
= [Link]("clusters");
// ... compute results
[Link]("text/html");
PrintWriter out = [Link]();
[Link]("<html><head>"
+ "<title>Cluster Analysis Result</title></head>"
+ "<body><h1>Cluster Analysis Result</h1>"
Java Servlets versus CGI 7
+ "Number of clusters: " + clusters[0]
// ... print results
+ "</body></html>");
}
}
-The following example servlet prints a "Hello world" HTML page.
Note that HttpServlet is a subclass of GenericServlet, an implementation of the Servlet interface.
The service() method dispatches requests to the methods doGet(), doPost(), doPut(), doDelete(), and so on;
according to the HTTP request.

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class ServletLifeCycleExample extends HttpServlet {

private int count;

@Override
public void init(ServletConfig config) throws ServletException {
[Link](config);
getServletContext().log("init() called");
count=0;
}

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
getServletContext().log("service() called");
count++;
[Link]().write("Incrementig the count: Count = "+count);

@Override
public void destroy() {
getServletContext().log("destroy() called");
}

 Usage
-Servlets are most often used to
 process or store data that was submitted from an HTML form
 provide dynamic content such as the results of a database query
 Manage state information that does not exist in the stateless HTTP protocol, such as filling the articles
into the shopping cart of the appropriate customer.

You might also like