You are on page 1of 53

Introduction to Web Applications

Java Application Types:-

Java can be used to develop different types of applications:


• Standalone Applications
• Applets
• Web Applications
• Distributed Applications

Standalone Applications
A standalone application is a program that runs on your computer. It is more or less
like a C or C++ program. It always contains a main method().
Applets
An applet is an application designed to travel over the Internet and to be executed on
the client machine by a Java- Compatible Web browser like Internet Explorer or
Netscape. Applets are also java programs but they reside on the servers. An applet
can not be executed like standalone application. Applet can be executed only by
embedding it into an HTML page like an image or sound file. To run an applet you
need to access an HTML page which has applet embedded into it. When the web
browser downloads such an HTML page, it subsequently loads the executable file,
which contains Applet and then executes it on the local machine. Applet has its own
lifecycle. It does not have main method like standalone application.

Web Applications
Web applications run on the Web server. Web applications are accessed through web
clients i.e. web browser like Internet Explorer or Netscape. Whenever you access
some web site by specifying the URL(Universal Resource Locator), you are accessing
some web application. The main components of a web application written in Java are:
• Java Servlets
• Java Server Pages(JSP) , and HTML

Java Servlets are also java programs, which run on the Server and then send the
result/ response to the client. JSP pages can be thought of as a combination of HTML
and Java Code. The Web Server converts JSP pages into Java Servlets before
execution.

You access the web application by specifying the URL. If the URL corresponds to an
HTML page the web server simply returns the HTML page to the client, which then
displays it. If the URL corresponds to the servlet or JSP then it is executed on the
Server and the result/response is returned to the client, which is then displayed by the
client.

Distributed Application
Java application can be divide into a number of modules/components (Java
programs),which can run on different machines. The java programs/applications
running on different machines can communicate with each other. To be more precise
the Java objects on one machine can invoke methods on the Java objects running on
another machine. Thus has the support for the distributed processing in the language
itself.

Introduction to Web-Applications
A web application is noting but a web-site. A web application can be thought of as a
collection of two types of resources:
• Static Resources
• Dynamic Resource

Web applications are deployed on the web servers (web- containers) and are
normally accessed through the web Clients, which is normally a web browser.
The communication between web client and web server takes place through
HTTP protocol.

Uses the
Mapping
Information
Servlet/JSP
J2EE Web
Container WebInstances
Application
Http
Web Request
Web Static
Browser Resources
Http Browser
Response

Static
Resources

Diagram to show interaction between client and web application

Static Resources :-
These are normally non-executable resources. In some cases static resources may
also be the executable resources but they do not execute on the server.
A typical application might have following types of static resources:
• HTML
• Images, Audio and Video files
• Applets
• Documents
• Spreadsheets
• Text Files
A web client can take ask for any static resource by just specifying the URL. Web
server simply returns the specified resource to the client without any processing.
The client decides what to do with the static resource. The most common static
resource is the HTML page. The web browser parses the HTML page and
displays in the browser window. For other type of static resources the action taken
may differ from browser to browser. The browser either displays the contents of
the resource on its own or with the help of software corresponding to the static
resource. For example, Internet Explorer may open a .doc file using MS-word
software. The browser prompts for saving the contents in case it is not able to
display/process the contents.

Dynamic Resources:-
These are executable resources. A web application can have following types of
dynamic resources:
• Servlets
• Java server page
The dynamic resources are also accessed by directly or indirectly specifying the
URL. But the action taken by web server is different in case of dynamic
resources. The dynamic sources are Java programs. The server executes the
appropriate component and then returns the result to the client normally as HTML
using HTTP protocol.

Servlet:-
Java servlets are small, platform independent server side programs that
programmatically extend the functionality of the web server. The java servlet API
provides a simple framework for building application on such web servers.

Java Server Pages:-


Java Server Pages is an extension of the java servlets technology. However, in
contrast to servlets, which are pure Java programs, JSP pages are text-based
documents. A JSP page contains two parts:
• HTML for the static content
• JSP tags and scriptlets written in java to encapsulation the logic that
generate the dynamic content.
Since a JSP page provides a general representation of content that can produce
multiple views depending on the result of JSP tags and scriptlets, a JSP page acts
like a template for producing content.

Web client(Thin client):-


In web client based architectures , the user interaction layer is separated from the
traditional client layer.Web browser manages the user interaction but leaves the
rest to applications on the server side, including the logic for driving the user
interface, iteracting with components in the middle-tier, and accessing databases.

Features of web clients:-


• A browser or a similar application to manage user interaction. For an end-user this
is the client layer.
• HTML is normally used as the means of user interface definition.
• HTTP(s) is used as the information exchange protocol between the web-clients
and web applications. The Web Application programs on the web server side the
application logic on behalf of browser clients.

Web Server and the Web Container


• The web applications are deployed on the web servers. The Web server handles
all the communication between web client and the web application. As discussed
earlier a web application is simply collection of static and dynamic

3.0 The HTTP Protocol

The HTTP is an application – level protocol (generally implemented over TCP/IP


Connection). The HTTP is a stateless protocol based on requests & responses. In this
paradigm, client application (such as your web browser) sends request to the server (such
as the web server of an online store) to receive info (such as downloading a catalog) or to
initiate specific processing on the server (such as placing an order).

3.3 HTTP Request Methods

As an application – level protocol, HTTP defines the types of request that the clients can
send to serves and the type of response that the servers can send to clients.

• The Get Request Method


• The Post Request Method

3.1.1 The Get Request Method

The Get Request is the simplest & the most frequently used request method for accessing
static resources such as HTML documents, image etc. The GET method is used when the
resource is accessed by specifying the URL in the web browser or by clicking on a
hyperlink.

Get request can also be used to retrieve dynamic information by using additional query
parameters in the request URL of a dynamic resource.
http://www.domain.com?name=matrix

The data is transmitted as the part of URL if GET method is used.


Sometimes we employ GET method even when accepting the data from the client using
the form. In this case any data provided in the form is appended to the URL as query
parameters before sending to the server.

3.1.2 The Post Request Method


Post requests are used when we need to send large amount of complex information to the
server. The Post request allows the encapsulation of multi-part message into the request
body. For example, you can use post request to upload text & binary files.

Normally we send data using Post method through form by specifying “POST” as the
method.

The data is transmitted as part of the body. So it is possible to send the large amount of
data when using the Post request.

3.1.3 The Difference between Get & Post Requests

With get request, the request parameters are transmitted as a query string appended to the
request URL. In the case of post request parameters are transmitted within the body of the
request.

This has two ramifications:

• Firstly since a Get request contains the complete request info appended to the
URL itself, it allows browser to bookmark the page & revisit later. Depending on
the type & how sensitive the request parameters are this may or may not be
desirable.

• Secondly some servers might pose restrictions on the length of request URL. This
limits the amount of info that can be appended to the request URL.

Note: The HTTP/1.1 does not impose any upper limit on the length.However server /
clients complying only with HTTP/1.0 may not support unreasonably long length.

3.2 Key Feature of HTTP

• HTTP is a very simple and lightweight protocol.


• In this protocol, the clients always initiate requests. The Server can never make a
Callback Connection to the Client.
• The HTTP requires the clients to establish connections prior to each request and
the servers to close the connection after sending the response. This guarantees that
the client cannot hold on to a connection after recieving the response. Either the
client or the server can prematurely terminate the connection.

4. The Requirements for Devloping & Hosting Web Applications


The following are the most essential requirements for devloping and hosting web
applictions:

(i) A Prgramming Model and a API- for development of applications.


(ii) Server-side Runtime Support- This includes support for network services
and a runtime for executing the application.
(iii) Deployment Support- Deployment is the process of installing the application
on the server. Deployment could also include customizing the application.

For building and running web applications, the J2EE provides the following to meet
each of the above requirements:

(i) Java Servlets & Java Server Pages


These are the building blocks for developing web Applications in J2EE. Java
servlets & JSP pages are called the Web Components.

(ii) Web container for Hosting Web Applictions


The web container is essentially a java runtime providing an implementation
of the java servlets API and other facilities for JSP pages. The Web container
is responsible for initializing, invoking and managing the life cycle of java
servlets and Java Server pages.

(iii) Packing Structure & Deployment Descriptor


The J2EE specification defines a packing structure for web applications. The
specification also defines a deployment descriptor for each web application.
The deployment descriptor is an XML file that lets you customize the web
application at deployment time.
Chapter -5
Deployment and Packaging
1. Introduction

The process of installing a web application is known as deployment. While deploying a


web application we need to create a folder/directory structure as per J2EE specification
foe web applications, which is independent of web-server/ web- container. Putting
resources of a web application in the appropriate folders/directories in teh standard
hierarchy is called packing.

The design and development processes in web applications are clearly separated from
those of deployment and packing.

As dicussed earlier a web application is a collection of many different types of files


(resources). A typical web application might include among others:
• Servlets and Helper Classes
• HTML Pages
• Images, Audio, Video files
• Java Server Pages (JSP)
• Applet Classes
• Jar files
• A deployment Descriptor and other configuration file.

The concept of web application was introduced in version 2.2 of the Java Servlet
specification. A web application is organized with a hierarchy of directories, with
particular types of files stored in particular directories.

These directories can then be packaged into a Web Application Archive (WAR) file.

2. Directory Structure

The directory structure of a web application has two parts:

1. A directory WEB-INF that contains the resources, which are not to be directly
downloaded to a client. The Directory is private- the client does not have direct
access to the files in this directory.

The WEB-INF directory typically contains dynamic resources such s servlets, as


well as configuration files.

2. A directory that contains those resources that are intended to be publicly


available. This includes all the subdirectories of this diretory, except the private
WEB-INF directory. This Directory typically contains static resources such as
HTML and image files. The JSP files, which have static as well as dynamic
contents, are also stored in this directory.
For Example, a web-application could have the directory structure
MyWebApp\
Index.html
Login.jsp
Images\
Logo.gif
Banner.gif Static resource (publicly
available)
Documents\
Summary.jsp
Intro.html
Help.doc
WEB-INF\
Web.xml
Classes\
ShoppingCart.class
Catalog.class Dynamic Resources
(Private)
Lib\
Classes12.jar
<<app-specific jar files>>
MyWebApp is the root directory of the web application.
Public resources Files in MyWebApp (or subdirectories excluding WEB-INF)
Files in images folder (or subdirectories)
Files in documents folder (or subdirectories)
Private resources  Files contained within the WEB-INF directory.
These are resources that are only accessible to the container.
2.1 Public Resources
A public resource is any file that is accessible to the client of the web application. Typical
public resources include:
• HTML, XML and JSP documents.

• Images, Audio and Video files.

• Java Applets – classes as well as jar files containing applets.

• Microsoft office documents: world, Excel, etc.

Client browsers can download these resources unchanged and render them as required.
For example, when an HTML page include an <APPLET> tag that refers to an applet in a
jar file, the web container delivers that JAR file to the client browser unchanged.
Typically, the container reads the static resources from the file system, and writes the
contents directly to the network connection. The interpretation of the contents of these
resources is the responsibility of the client browser. In order to help the browser render
the file correctly, the container sends the MIME type of the file. These MIME types can
be set in the deployment descriptor of the web application.
Note:- Although JSP pages are included as public resources in a web application; the
container does not show them directly to clients. The Container automatically converts
JSP Pages into Servlets. The Sevlet is then complied and invoked to generate the
response for the client. However, since a JSP Page is often considered more near to an
HTML document than to a java class, JSP Pages are also included under public resources.
2.2 Private Resources
Of course, there are certain resources that clients should not load directly. There may be
files that the client should not view, such as configuration files or they may be files that
the container must perform some processing on before sending the response to the client,
like servlets. These private resources are stored in the WEB-INF directory, or its
subdirectories.
The types of resources that clients should not download directly include:
• Servelts- These components include application logic, and possibly
access to other resources such as databases.

• Any other files in the web application that servlets access directly.

• Resources that are meant for execution or use on the server side, such
as java class files and JAR files for classes used by your servlets.

• Temporary files created by your applications.

• Deployment descriptors and other configuration files.

These resources are private and as such are accessible only to their own web application
and the container. In order to accommodate private resources the web container requires
the WEB-INF directory to be present in your application. If your web application does
not contain this directory it will not work.
• The WEB-INF directory includes:

• A web.xml file. This is the deployment descriptor.

• A Subdirectory named classes. This directory is used to store server-


side Java class files such as servlets and other helper classes,
structured according to the usual java packaging rules.

• A lib subdirectory to contain JAR files used by the web application.

2.3 Advantage of the Structure


• Each application exists in a ‘sand-box’. The public and private
resources of an application are independent of any other application
that the container may be running.

• When a new application is added to the J2EE server, we can simply add
the appropriate context root in the deploy tool of the reference
implementation, without disturbing any other application.
• The Container knows where to look for classes. This means that you do
not need to explicitly add these classes and JAR files to the
CLASSPATH.

• The difference between a conventional web server and a web


container is that each web application has its own document root.

• Similar to the public resources, private resources of different web


applications are stored in different folder.

• According to the Servlet specification a container should load class/JAR


files of each web application using a different class loader. It is for this
reason that servlets, JSP Pages, and other classes that are part of one
web application cannot see classes in other applications and therefore
cannot share static variables or singleton classes, for example. This is
easily achieved by the structure discussed above.

Thus, even if you deployed the same web application twice (each mapping to a different
URL), as for as container is concerned they are two entirely different applications. Such
applications cannot share information. As a result, web containers create a virtual
partitioning of web applications within the container.
3.0 Deploying Web Application
A web application can be deployed simply by creating the directory structure and putting
the files/resources in the appropriate folders as discussed in the previous section. We can
also deploy the application using a WAR file, which is described in the next section.
The folder structure is independent of the web-server (and web-container). But the folder
under which the structure is to be created may differ from server to server. For example,
the structure must be created in the webapps folder if you are using Tomcat as the server.
4.0 Web archive Files
The various directories and files that make up a web application can be packaged into a
web application archive (WAR) file. The process is similar to the packaging of java class
files into JAR files. The purpose of the packaging is the same; it is to provide a simplified
way to distribute Java Class files and their related resources. WAR files can be created
using the same jar tool that is used to create JAR files. The Web application can be
deployed as a War files, rather than the unpackaged collection of directories and files.
Example: jar –cf greet.war*
This command packs all the contents under the current directory, including subdirectories
into an archive file called greet.war.
-c option is used for creating a new archive.
-f option is used to specify the target archive file name.
If the verbose option is specified using –v, the names of the files and directories included
in the archive will be output to the screen.
You can use the following command to view the contents of a WAR file:
Jar -tvf greet.war
Note:- Instead of including all the contents, you may select individual files and
subdirectories while creating WAR files. You can also use a standard ZIP file
manipulation tool such as WinZip to create and manipulate WAR files. Note that jar-tool
automatically create the META-INF sub-directory and its contents.
4.1 Deploying a WAR file
Any Servlet 2.2 or higher compliant server will automatically deploy and application
packaged as WAR file, as long as the location of a WAR file is explicitly stated or war
file is copied into appropriate folder..
When should WAR files be used
• Should be used when deploying the final application.

• During development try to use auto reload feature for java classes.

Mapping Request to Applications


In a Web Container each web application is associated with a context and all resources in
a web application exist relative to that context
5. Tomcat Web Server
Tomcat is one of the most popular open source web server (including web-container) for
deploying and running web applications.
5.1 Tomcat Installation
The installation process is described for tomcat 5.5:
1. Download the setup files (say Jakarta-tomcat-5.5.11.exe) from the
apache web site.

2. Make sure that you have J2SE 5.0 (JDK1.5) installed on your machine. If
the JDK is installed in folder C:\jdk1.5 then the environment variable
JAVA_HOME should be set to C:\JDK1.5 although it is not must.

3. Double-click on the setup file to install the tomcat. The installer will
guide you through the entire installation process.

4. When prompted for destination folder you can specify C:\Tomcat5.5 to


install the Tomcat in C:\Tomcat5.5 folder, which is known as tomcat’s
home folder. The CATALINA_HOME environment variable points to this
folder.

5. The installer then prompts for port number, user and password. The
default port number on which the tomcat server runs is 8080; you can
leave it as it is. The default user name is admin; you can leave this also
as it is. Specifying password is must. You should remember the
password as only the authorized user can access tomcat
administration site.

6. The installer then asks for the path of J2SE 5.0 JRE installed on the
machine. By default path C:\Program Files\Java\jre1.5.0_04 is selected,
which is the default path where the JRE is installed. Leave the selection
as it is if you have not changed the default path while installing JRE
otherwise give the path where you have installed the JRE.
7. Finally click on the install button. After this installation process will
take few seconds to complete.

Note: If the tomcat fails to start after successful installation then make sure that
JAVA_HOME is set properly and the CATALINA_HOME is set to the folder where
you have installed Tomcat i.e. C:\Tomcat5.5 as described above.
5.2 Tomcat Folders w.r.t CATALINA_HOME
1. bin – executable (tomcat5.exe to start the Tomcat)
2. common – har files visible to web applications as well as internal tomcat code.
3. conf – server level configuration.
Server.xml – for configuration tomcat server
Web.xml – contains default configuration for all the web applications.
Application specific resources should not be configured here.
Example: <welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file-list>
4. logs – log files
5. server- server web applications, admin (Server administration),
Manager(deployment)
6. shared- classes visible to all the web applications, but not to internal tomcat code.
7. temp – temporary files
8. webapps – user web applications, tomcat example applications.
9. work – session information, jsp compilation.
6. Web Application : Development to Deployment with Example
Example1 : Greeting Application (index.html, web.xml, GreetingServlet.java)
************************
********index.html************************************
1 <html>
2 <head>
3 <title> ProJava Registration.. </title>
4 </head>
5 <body>
6 <h1>Welcome</h1>\
7 <form action =”GreetingServlet” method =”POST”>
8 <p> Your Name <input type =”text” size =”40” name=”name” /></p>
9 <p> Your Email <input type =”text” size =”40” name=”email” /></p>
10 <input type = “submit” VALUE =”submit”/> </p>
11 </form>
12 </body>
13 </html>
chapter 6
The notion of a session provides this abstraction. In simple term, a session lets you group requests into a collected
group. In addition, session management also involves associating data with each session. The servlet API specifies the
javax.servlet.HttpSession interface to provide this abstraction.

Servlet context

The notion of servlet context is closely associated with the notion of a web application. The interface
javax.servlet.ServletContext allows servlets in an application to share data. It also provides the methods with which
servlets can access the host web container. Using the ServletContext object, a servlet can log events, obtain URL
refrences to resources and set and store attributes that other servlets in the context can access.

Servlet collaboration

The servlet API also provides an interface javax.servlet.Request Dispatcher with which a servlet can invoke another
servlet, a JSP, or even a static resource such as an HTML page. This mechanism helps you to control flow of logic
across multiple servlets and JSP pages programmatically.

Filtering

The servlet API has a mechanism with which we can introduce code (called a filter) to participate in the containers
request / response process. Filters are a new feature of the Java Servlet API version 2.3. They do not generally create
requests/responses; rather, they modify or adapt requests and responses to and from a web resource, which could have
static or dynamic content.

Cookie

The javax.servlet.http.Cookie is used to create cookies.

3. Servlet Implementation API

3.1 The Servlet Interface


• Public interface javax.servlet.Servlet
The interface specifies the contract between the web container and a servlet. In the OOPS paradigm, an object can
communicate with another object as long as the first object reference the second object with a known interface. It need
not know the name of the actual implementing class. In the case of the Servlet API, the javax.servlet.Servlet is the
interface that containers use to reference servlets.

When you write a servlet, you must implement this interface directly or indirectly. You will most likely always
implement the interface indirectly by extending either the javax.servlet.GenericServlet or javax.servlet.httpServlet
classes. When implementing the javax.servlet.Servlet interface, the following five methods must be implemented:

• Public void init(ServletConfig config)


• Public void service(ServletRequest request, ServletResponse response)
• Public void destroy( )
• Public ServletConfig getServletCondfig( )
• Public string getServletInfo( )
The init ( ) method
• Public void init(ServletConfig config) throws ServletException
Once the servlet has been instantiated, the web container calls the init ( ) method. The purpose of this method is to
allow a servlet to perform any initialization required before being invoked against HTTP requests. The container passes
an abject of type ServletConfig to the init ( ) method. A servlet can access its configuration data using the
ServletConfig object.

The init ( ) method throws a ServletExpection in the event that it does not complete normally.

The Servlet specification guarantees that the init( ) method will be called exactly once on any given instance of the
servlet, and the init( ) method will be allowed to complete (provide that it does not throw a ServletException) before
any requests are passed to the Servlet. Some of the typical tasks that can be implemented in the init ( ) methods are:
• Read configuration data from persistent resources such as configuration files.
• Read initialization parameters using the ServletConfig object.
• Initialization one-time activities such as registering a database driver, a Connection Pool, or a Logging
service.

The service ( ) Method


• Public void service(ServletRequest request, ServletResponse response)
Throws servletException, IOException
This is the entry point for executing the application logic in a servlet. The container calls this method in
response to incoming requests. Only after the servlet has been successfully initialized will the service ( ) method
be called. The service method takes two arguments, implementing the javax.servlet.ServletRequest and
javax.servlet.ServletResponse interfaces respectively. The request object provides methods to access the
original request data, and the response object provides methods with which the servlet can build a response.

The destroy ( ) method

• Public void destroy( )


The container calls this method before removing a servlet instance out of service. This might accrue if it needs to free
some memory or if the web server is being shutdown. Before the container calls this method, it will give the remaining
service threads time to finish executing (subject to some timeout period), so that the destroy ( ) method is not called
while a service ( ) call is still underway. After the destroy method is called, the container does not route requests to the
servlet.

Activities that can be implemented in the destroy ( ) methods include:


• Performing cleanup tasks, such as closing any open resources, closing a connection pool, or even informing
another applications/ system that the servlet will no longer be in service.

ThegetServletConfig ( ) Method

• Public ServletConfigConfig getServletConfig( )


This method should be implemented to return the ServletConfig that is passed to the servlet, during the init( )
method.

The getServletInfo ( ) Method

• Public String getServletInfo( )


This method should return a String object containing information about the Servlet (for example, author,
creation date, description and so on) This is available to the web container, should it wish to display, for
example, a list of servlets installed together with their descriptions.

3.2 The GenericServlet Class


• Public abstract class GenericServlet implements Servlet, ServletConfig, Serializable
The GenericServlet class provides a basic implementation of the Servlet interface. This is an abstract class,
and all subclasses should implement the service( ) method. The abstract class has following methods in
addition to those declared in javax.servlet.Servlet, and javax.servlet.ServletConfig.
• Public init( )
• Public void log (String message)
• Public void log(String message, Throwable t)

The init (ServletConfig config) method stores the ServletConfig object in a private transient instance variable (called
config). You can use the getServletConfig ( ) method to access this object. However, if you choose to override this
method, you should include a call to super. Init (config).

Alternatively, you can override the overloaded no-argument init ( ) method in the GenericServlet class.

The GenericServlet class also implements the ServletConfig interface. This allows the servlet developer to call the
ServletConfig methods directly without having to first obtain a ServletConfig object. These method are:-

• getInitParameter( )
• getInitParameterNames( )
• getServletContext(), and
• getServletName( )
Each of these methods delegates the calls to the respective methods in the stored ServletConfig object.

The GenericServlet class also includes two methods for writing to a servlet log, which call the corresponding methods
on the ServletContext.

The first method, log (String msg), writes the name of the servlet and the msg argument to the web container’s log. The
other method log (String msg, Throwable cause), includes a stack trace for the given Throwable exception in addition
to the servlet name and message. The actual implementation of the logging mechanism is container-specific, although
most of the containers use text files for logging purposes.

3.3 The HttpServlet Class


• public abstract class HttpServlet Extends GenericServlet
The HttpServlet class extendes GenericServlet, and provides an HTTP specific implementation of the servlet interface.
This will most likely be the class that all of your servlets will extend. The commonly used methods in this class are:
• public void service(ServletRequest request, ServletResponse response)
• protected void service (HttpServletRequest request, HttpServletResponse response)
• protected void doGet (HttpServletRequest request, HttpServletResponse response)
• Protected void doPost (HttpServletRequest request, HttpServletResponse response)

The service ( ) Methods

The HttpServlet has two variants of this method:


• Public void service(ServletRequest request, ServletResponse response)
Throws ServletException, IOException
This is an implementation of the service ( ) method in the GenericServlet. This method casts the request and
response objects to httpServletRequest and HttpServletResponse and calls the following overloaded service
( ) method. Therefore, you should not override the above method.

• Protected void service (HttpServletRequest request, HttpServletResponse response)


Throws ServletException, IOException
This overloaded method takes HTTP specific request and response object, and is invoked by the first method
above. HttpServlet implements this method to be a dispatcher of HTTP requests.

The javax.servlet.ServletRequest interface provides a getMethod ( ) method that returns the type of the HTTP
method associated with the request. For instance, for GET request, this method returns”GET” as a string. The
service ( ) method uses this string to delegate the request to one of the methods do XXX ( ). The
javax.servlet.http. HttpServlet provides default implementation of all these methods.

In general, you should avoid overriding this method as it affects the default behavior of the service ( ) method.
The only situation that requires you to override it is when you want to change the default behavior, or when you
want to include additional processing common to doXXX ( ) methods.

The sequence of method calls when the container receives a request for a servlet is :
1. The container calls the public service ( ) method.
2. The public service ( ) method calls the protected service ( ) method after casting the
arguments to HTTPServletRequest and HttpServletResponse respectively.
3. Protected service ( ) method calls one of the doXXX ( ) methods, depending on the type
of the HTTP request method.

3.4 The SingleThreadModel Interface


• Public interface javax.servlet.singleThreadModel
The Servlet API specifies a special maker interface called javax.servlet.SingleThreadModel. During the lifetime of a
servlet that does not implement this interface, the container may send multiple service requests in different threads to a
single instance. This means that implementation of the service ( ) method should be thread safe.

However, what is the alternative if the service ( ) method of a servlet is not thread safe?

The java Servlet API specifies the SingleThreadModel interface for this purpose. Servlets can implement the
SingleThreadModel interface ( in addition to implementating he javax.servlet.Servlet interface or extending one of its
implementation classes) in order to inform the container that it should make sure that only one thread is executing the
servlet’s service( ) method at any given moment.

For SingleThreadModel servlets, Containers may follow one of the following approaches to ensure that each servlet
instance is invoked in a separate thread:

o One Instance per Request


In this approach, the container allocates separate instance for each request. Normally the container maintains
a pool of servlet instances to avoid frequent creation and garbage collection, which may drastically affect the
performance. For each incoming request, the container allocates a Servlet instance from the pool, and upon
completion of the service, the container returns the instance to the pool.
o Request Serialization
In this approach, the container maintains a single instance of the servlet. However, since the container cannot
send multiple requests to the instance at the same time, the container serializes the requests. This means that
new requests will be kept waiting while the current request is being served.

o Fixed size Configurable Instance pool


In reality, a combination of these two approaches is more pragmatic, so that the container could maintain a
reasonable number as instances in the pool, while still serializing requests if the number of requests exceeds
the number of instances in the pool.

Note that the Single ThreadModel is resource intensive, particularly if a large no. of concurrent requests is
expected for the servlet. The effect of the SingleThreadModel is that the container invokes the service ( )
method in a synchronized block. This is equivalent to using the synchronized keyword for the servlet’s
service ( ) method. Accordingly, when there are hundreds or even thousands of concurrent requests to the
web container, the container may either serilize requests to the same instance of the servlet, or create that
many hampered due to serialization. In the later case, the container encounters more object allocation (which
includes more object creation overhead and memory usage).

However, in cases where only a few statements of the service ( ) method are not thread safe, you should
consider reducing the scope of synchronization of the service ( ) method are not thread safe, you should
consider reducing the scope of synchronization, and explicitly synchronize such blocks using the
synchronized keyword. Depending on how short such synchronization blocks are, this approach could
improve performance.

Note: - We should always consider redesigning our applications in order to avoid the SingleThreadModel or
thread synchronization. If we cannot avoid them, it is important to be aware of the performance implications.
With any thread synchronization code, you are potentially blocking a web container thread

4. Servlet Configuration API


The configuration information contains initialization parameters (set of name/value pairs), the name
Of the servlet, and a javax.servlet.Servletcontext object, this gives the servlet information about the
container. The initialization parameters and the name of a servlet can be specified in the
deployment descriptor (web.xml). For example:

<web-app>
<servlet>
<servlet-name>Admin</servlet-name>
<servlet-class>com.wrox.admin.AdminServlet</servlet-class>
<init-param>
<param-name>driverClass</param-name>
< param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>jdbcURL</param-name>
<param-value>jdbc:oracle:thin:@everesr:1521:orcl</param-value>
</init-param>
</servlet>
</web-app>

4.1 The ServletConfig Interface


• Public interface javax.servlet.ServletConfig
• Public Enumeration getInitParameterNames( )
• Public ServletContext getServletContext ( )
• Public String getServletName( )

4.2 Obtaining a Reference to ServletConfig


In the java API, a servlet can obtain a refrence to the javax.servlet.ServletConfig object in the following
ways:

During Servlet Initialization


The init( ) methods of the Servlet interface and the GenericServlet class have an argument of type
ServletConfig. During initialization of a servlet, the web container creates this argument and passes it to the
init( ) method. When you are overriding the init ( ) method, you can access the ServletConfig object.

However, when you are overriding the init( ) method in the GenericServlet class, you should explicity
invoke super.init( ) as follows:

Public init (ServletConfig config)


{
Super. Init(config);
----------------------
}

The call to super.init (config) ensures that the GreetongServlet class actually maintains a refrence to the
ServletConfig object. The implementation of the GenericServlet class actually maintains a refrence to the
ServletConfig object (as a private transient instance variable), and requires that super.init( ) be called in
subclass.

Using the getServletConfig( ) method


Servlets can also access the ServletConfig objects by calling the getServletConfig ( ) method. This method
is specified in the Servlet Interface.
Alternatively, servlets extending the GenericServlet, or its subclass HttpServlet can also call the method of
the ServletConfig interface directly. This is because the GenericServlet also implements the ServletConfig
Interface.

5. Servlet Exception API


This API defines two types of servlet exceptions:
• Javax.servlet.ServletException
• Javax.servlet.UnavailableException

The servlet can throw any of these exceptions to the container to indicate that due to some exceptions, servlet can not
continue its execution. The container will according mark that the servlet is either permanently or temporarily
unavailable.

5.1 javax.servlet.ServletException

Defines a general exception a servlet can throw when it encounters difficulty. The container sends the HTPP-500 error
to the client.

Constructors
• Public ServletException ( )
Construct a new Servlet Exception
• Public ServletException (String msg)
Constructs a new servlet exception when the servlet needs to throw an exception and includes a parameter
corresponding to the “root cause” exception that interfered with its normal operation, and a desription
message.
• ServletException (Throwable rootcause)
Constructs a new servlet exception when the servlet needs to throw an exception and includes a parameter
corresponding to the “root cause” exception that interfered with its normal operation.

5.2 javax,servlet.UnavailableException
Defines an exception that a servlet or filter throws to indicate that it is permanently or temporarily unavailable.

A servlet or filter is temporatily unavailable if it cannot handle request momentarily due to some system wide problem.
For example, a third-tier server might not be accessible or there may be insufficient memory or disk storage to handle
requests . A system administrator may need to take corrective action.

A servlet or filter is permanently unavailable if during its execution an exception occurs which can not be recovered.

Servlet containers can safely treat both types of unavailablr\e exceptions in the same way. However, treating temporary
unavailable effectively makes the servlet container more robust. Specifically, the servlet container might block requests
to the servlet or filter for a period of time suggested by the exception rather than rejecting them until the servlet
container restats.

Constructors
• UnavailableException (String msg)
Constructs a new exception with a description message indicating that the servlet is permanently unavailable.
The container sends the HTTP-404 error to the client.

• UnavailableException (String msg, int second)


Constructs a new exception with a descriptive message indicating that the servlet is temporarily unavailable
and giving an estimate of how long it will be unavailable. In some cases, the servlet cnnot make an estimate .
For example, the servlet might know that a server it needs is not running but not be able to report how long it
will take to restore the functionality? This can be indicated with a-ve or zero value for the second argument.
The container sends the HTTP-503 error to the client.

6. The Servlet Lifecycle


The container is a run-time that manages the Servlets. In the case of servlets, the lifecycle events are specified
in the javax.servlet.Servlet interface of the Servlet API. Although the lifecycle management is a container’s
responsibility, as servlet developers, we should make sure that our servlet follow the lifecycle model and that they
are not implemented in a way that ci\ontradicts this.

The Servlet interface methods relevant to the servlet lifecycle are init( ) , service ( ), and destroy ( ). The lifecycle
starts with the container calling the init( ) method, and ends with the container calling the destroy method.

The Lifecycle of a servlet consists of the following fundamental stages:


1. Instantiation
The Web Container creates an instance of the servlet.

2. Initialization
The Container calls the instance’s init( ) method.

3. Service
If the Container has a request for the servlet it calls the servlet instance’s service( ) method.

4. Destroy
Before destroying the instance, the container calls the servlet instance’s destroy ( ) method. After this
servlet instance is garbage collected.

5. Unavailable
The instance is marked as unavailable. The unavailable may be temporary or permanent.

Example: FreakServlet Application


The Example consists of a single servlet called FreakServlet, which demonstrates the various states in the lifecycle
of a typical servlet, including unavailablility.
FreakServlet.java
1 import javax.servlet.*;
2 import javax.servlet.http.*;
3 import java.io.*;
4 import java.util.*;
5 public class freakservlet extends Httpservlet
6 { Vector States;
7 Random random;
8 int waitINTERVAL;
9 public static final int DEFAULT_WAIT_INTERVAL=10;
10 public FreakServlet ( )
11 { states=new vector ( );
12 random=new random ( );
13 waitInterval=DEFAULT_WAIT_INTERVAL;
14 states. Add (create State (“Instantiation”));

Chapter-7
Request and Response API
1. Introduction
The javax.servlet.HttpServletRequest and javax.servlet.HttpServletResponse interfaces are the classes that servlets
depend on for accessing HTTP requests and responses. The important classes/interfaces in this category are:
o Javax.servlet.ServletRequest
o Javax.servlet.ServletResponse
o Javax.servlet.http.HttpServletRequest
o Javax.servlet.http.HttpServletResponse

2. The javax.servlet.ServletRequest Interface


The following specifies an abstraction of client request for a servlet. The web container creates an instance of
this object while calling the service ( ) method of the GenericServlet or HttpServlet.

2.1 Methods for Request Parameters

The following methods can be used to access the request parameters. In the case of HTTP request, these methods
can be used for both GET and POST requests.

o Public String getParameter(String name)


This will attempt to locate a parameter with the given name (Case-Sensitive) in the request and return its
value. If there are multiple values for a given parameters, then this method returns the first value in the
list. The method returns null if the key is not found in the request.

o Public string [ ] getParameterNames( )


If a parameter can return multiple values, such as a set of check boxes, a multi selection-list, or even
multiple controls with the same name, this method returns an array containing the parameter values.

o Public Enumeration getParameterNames( )


This method returns an enumeration of all the parameter names for the request. If the request has no
parameters, it returns an empty enumeration.

o Public Map getParameterMap( )


This method returns a java.util.Map containing all request parameters. In this map, the name of the
parameter is the key while its value is the map value. Both keys and values are strings. Note that this
map is immutable and you cannot change the contents of this map.

2.2 Methods for Request Attribute


Apart from request parameters, web containers or Servlet/JSP’s can attach attributes to requests, The Servlet
API specification specifies three different approaches for storing and retrieving attributes:

o Attaching attributes to request objects


o Storing attributes in Http Session object
o Servlet context.

The JSP specification provides an additional mechanism using page context to store and retrieve attributes. Each of
these approaches provides the notion of a scope for the attributes to exit: In the case of attributes attached to the request
objects, the lifetime of these attributes is that of the request itself.

In the servlet parlance, an attribute is a named Java language object. While setting an attribute, you assign a name to the
attribute, and while retrieving the attribute, specify the same name. Names are String objects. The purpose of attributes
in the request scope is to allow the container or another servlet to send additional data to a servlet or JSP. For the
application developers, this is useful when using the Request Dispatcher object to forward request from one servlet to
another. The following methods can be used to manage attributes in the request context.

o Public Object get Attribute(String name)


This method returns the value of the named attributes (or null if the named attribute does not exist)

o Public Enumeration getAttributeNames ( )


This method returns an enumeration of all the attributes contained in the request. It returns an
empty enumeration if there are no attributes in the request.

o Public void setAttribute(String name,Object attribute)


This method sets a named attribute.

o Public void remove Attribute(String name)


This method removes the named attribute from the request.

2.3 Methods for Input


The ServletRequest holds a reference to the underlying Client connection. Using the following methods, you
can access the stream and writer objects associated with the request.

o Public servletInputStream getInputStream ( )


This method can be used to access the body of the request using a ServletInputStream object.

o Public java.io.BufferedReader getReader( )


This method can be used to access the body of the request using a buffered reader object.

o Public String getCharacterEncoding( )


This method returns the name of the character encoding used in the body of this request.

3. The javax.servlet.http.HttpServletRequest Interface

o Public interface HttpServletRequest extends ServletRequest


The most commonly used methods in this interface are the methods for accessing request
parameters. HTTP allows you to submit parameters along with a request. In a GET request, these
parameters are appended to the request URL in the form of query String, Whereas in a POST
request the parameters are sent within the body of the request in x-www-form-urlencoded
format. In any case these parameters are represented as key –value pairs. HTTP does not require
that the keys are unique, so for some keys, there can be list of values. Examples include multiple
selection list-boxes or checkbox groups. When you build an HTML fom for GET or POST
requests, you specify certain controls using <input> tags. Each control has a type, such as
checkbox, text or submit and can also have a name and/or a value. The name attribute defines the
key by which the value returned to the server will be known. The value attribute has different
effects on different controls. Obviously, if we give more than one <input> tag the same name, we
could have several key/value pairs with the same key as part of our request.

Multiple controls can have the same name. The most common reason for having multiple
controls with the same name is to be able to build sets of radio buttons and check boxes, and
multiple-selection select controls. The radio button set will return the single selected value, and
checkboxes or multiple selection select controls will return all of selected values.

3.1 Methods for Request Path and URL


o Public String getPathInfo ( )
This method returns any extra path information associated with the request URL. In general, you
invoke a servlet using its alias or the class name. For instance, you can access a servlet
MyServlet using URL http://host:port/myApp/MyServlet where myAPP is the application
context. However, you can send additional path information to the servlet say as
http://host:port/myAPP/MyServlet/devesh. In this case /devesh is the additional path information
returns null if there is no additional path in the request.
o Public String getPathTranslated ( )
The method translates the extra path information into a real path. For instance, if the directory
corresponding to myApp application is c:\tomcat5.5\eabapps\myApp\devesh as the translated
path. This method returns null if there is no additional path in the request.
o Public String getRequest URI( )
This method returns URI path associated with the request. In the above example, this method
would return/myApp/MyServlet/devesh i.e. the path starting with the server root. The query
string is excluded.

o Public String getRequestURL ( )


This method reconstructs the URL that the client used to make this request. The returned string
included the protocol, Server name, Port and the Server path for this request. The query string is
excluded. For instance, in the above example, this method would return
http://host:port/myAPP/MyServlet/devesh
o Public String getServletPath( )
This method returns the URI path associated with this Servlet. This excludes any extra Path
information and query string. For Instance, in the above example, this method would return
/myApp/MyServlet as the servlet path.

3.2 Methods for HTTP Headers


o Public StringHeader (String name)
The method returns the value of the named header from the HTTP request. This method returns
null if the request does not include the specified header. The header”host” returms the name of
the machine sending the request. The header “user-agent” returns the browse r information.
o Public Enumeration getHeaderNames( )
This method returns an enumeration of names of request headers.
o Public String getMethos ( )
This method returns the type of the HTTP request such as GET, POST and so on.

4. The javax.servlet.ServletResponse Interface


o Public interface ServeltResponse
This method sets the content type of the response. If you are using PrintWriter object to generate the
response, before writing the response you should call setContentType( ) to set the MIME type of the
HTTP response.

o Public void setContentLength (int size)


This method sets the content-length header. The client can make use of this header to know the
length of data being sent by the servlet before it starts reading data.

4.2 Methods for output


o Public ServletOutputStream getOutputStream ( )
This method returns a ServletOutputStream object that can be used for writing binary data in the
response. The ServletOutputStream class is a subclass of java.io.OutputStream. ON a given
HttpServletResponse object, you should call this method only once. If you try to call this method
more then once, you will encounter an IllegalStateException.
o Public PrintWriter getWriter ( )
This returns a PrintWriter object that can be used to send character data in the response.
PrintWriter automatically translates java’s internal Unicode characters into the correct encoding
so that they can be read on the client m/c.

4.3 Methods for Buffered Output


If you are sending a large amount of data in the response, you should consider setting the buffer
size to smaller values, so that the user can start receiving the data quickly. Buffering also allows you to abort the
content generated so far, and restart the generation.
o Public void setBufferSize (int size)
o Public int getBufferSize ( )
o Public void reset Buffer ( )

This method clears content of the underlying buffer without clearing the response headers or the
status code. If the response has already been committed, then method throws an Illegal State
Exception.
o Public void FlushBuffer ( )
o Public Boolean is Committed ( )
o Public void reset ( )
This method clears content of the underlying buffer as well as the response headers.

5. The javax.servlet.http.HttpServletResponse Interface


o Public interface HttpServletResponse extends ServletResponse
Some of the important methods are described below:
o Public String encodeURL (String url)
This method encodes the URL if cookies are off on the client side. It adds the session to the URL.
o Public void sendError (int status)
Servlets can use this method to indicate standard HTTP status codes. As seen in the case of
Freakservlet, you can specify error pages for different HTTP errors and servlet exceptions. If there
is a matching page for the specified status code, the container sends the specified page to the client.
If there is no page specified, the container sends its default error page indicating the status and a
corresponding message.
o Public void sendError (int status, String msg)
o Public void sendRedirect (String location)
This method sends a redirect response to the client. The client receives the HTTP response code
302 indicating that temporarily the client is being redirected to the specified location. If the
specified location is relative, this method converts it into an absolute URL before redirecting.

Chapter-8
Session Handling

1. Introduction
A servlet receives a request object, extracts parameters (if any) from it, processes any application logic (which may
depend on the request parameters), and finally generates the perponse. Extending this model, you could build larger
web applications by having several servlets, with each servlet performing a well-defined independent task.

The model is adequate so long as the application logic in each of these servlets is atomic-that is, so long as the
application logic depends only on the parameters in the request (and, if applicable, any persistent data such as data
stores in a relational database). For instance, in the TechSupport application the servlet gets all the support request data
from the request, and as part of the application logic, writes the request data to a database, and sends a confirmation
back.

Now consider a familiar web application –an on-line store.


In a typical online store, the main application that drives the store is a shopping cart. An on-line store provides you with
a browsable interface to a catalog. You san select items in the catalog, and add them to a shopping cart. Once you have
added all the required items to the cart, you proceed to checkout, and place an order for the items in the cart. However
such an application is not as simple as it appears. Where is the shopping cart maintained? Since the client is ‘thin’, it is
the responsibility of the server to maintain the cart not only for you, but for all the other users that may simultaneously
be browsing the catalog and adding items to their respective shopping carts. In order for this mechanism to work, the
server should be able to individually distinguish each user and accordingly, maintain each shopping cart.

This is a typical requirement for web application where a ‘user activity’ happens across multiple requests and
responses, and the server is required to associate some form of uniqueness to each of the users.

This can be achieved using


o Session Tracking or
o Servlet context: Servlet in an application can use servlet context to exchange information or
collaborate with other servlets, access resources, log events etc.

2. Statelessness and Sessions


HTTP is a stateless protocol. A client opens a connection and requests some resource or information. The
server responds with the requested resource (if available)’ or sends an HTTP error status. After closing the
connection, the server does not remember any information about the client. So, the server considers the next
request from the same client as a fresh request, with no relation to the previous request. This is what makes
HTTP a stateless protocol.

A protocol is stateful is response to a given request may depend not only on the current request, but also on
the outcome of previous requests.
But why is it important to be stateful? A stateful protocol helps you develop complex application logic across multiple
requests and responses. Let’s consider an online bank. When you request a page containing balances of all your
accounts, the server should be able to verify that you are a genuine account holder, and that you have established your
credentials with every request-In fact, each business transaction will be required to occur in a single request. This is not
suitable for long business transaction that ought to happen across multiple requests, such as the online bank, or
shopping cart.

For implementing flexible business transaction across multiple requests and responses, we need two facilities.
• Session:
The server should be able to identify that a series of requests are from a single client and responses, we need
single working session.
• State:
The server should be able able to remember information related to previous requests and other business
decisions that are made for requests. That is, the shopping cart application, possible state could include the
user’s favorite item categories, user profile, or even the shopping cart itself.

However, in the case of HTTP, connections are closed at the end request, and hence HTTP servers cannot use the
notion of connections to establish a session. HTTP is a stateless protocol, concerned with requests and responses, which
are simple isolated transactions. This is perfect for simple web browsing, where each request typically results in
downloading static pages. The server does not need to know whether a series of requests come from the same, or from
different clients, or whether those

SERVLET PROGRAMMING
Servlets:-
Java servlet are small, plateform-independent Java programs that runs in a web
server or application server and provides server-side processing such as accessing a
database and e-commerce transactions.The java servlet API provides a simple framework
for building web applications .
Servlets are widely used for web processing. Servlets are designed to handle
HTTP requests (get, post, etc) and are the standard Java replacement for a variety of other
methods, including CGI scripts, Active Server Pages(ASPs).

Java Servlets are server side Java programs that require either a Web Server or an
Application Server for execution. Examples for Web Servers include Apache’s Tomcat
Server and Macromedia’s JRun.

Servlet Container

Servlets always run inside a Servlet Container. A server container is nothins but a
web server, which handles user requests and generates response. Servlet Container is
diffent from Web Server because it is only meant for Servlet and not other files(like .html
etc).server container is responsible for maintaining lifecycle of the Servlet

A web container is an application framework with a runtime environment. In the


framework, application objects are created and invoked by the runtime. While invoking
methods on the application objects, the container has to construct the objects for the
arguments. For instance, in GreetingServlet, the Container creates and passes the
HttpServletRequest and HttpServletResponse objects as arguments to the doPost()
method

It also provides the following features and functanalities:


• The network services over which request and response are sent
• Registers servlet against one or more URLs
• Manages the servlet lifecycle
• Decodes MIME based requests
• Construct MIME based responses
• Supports the HTTP (also supports other protocols)
A servlet servlet container can also enforce security restrictions on the environment, such
as requesting the user to login to access a web page
Advantages of Java Servlets
1. Portability
2. Powerful
3. Efficiency
4. Safety
5. Integration
6. Extensibilty
7. Inexpensive

Each of the points are defined below:


Portability
As we know that the servlets are written in java and follow well known standardized
APIs so they are highly portable across operating systems and server implementations.
We can develop a servlet on Windows machine running the tomcat server or any
other server and later we can deploy that servlet effortlessly on any other operating
system like Unix server running on the iPlanet/Netscape Application server. So
servlets are write once, run anywhere (WORA) program.
Powerful
We can do several things with the servlets which were difficult or even impossible to
do with CGI, for example the servlets can talk directly to the web server while the CGI
programs can't do. Servlets can share data among each other, they even make
the database connection pools easy to implement. They can maintain the session by
using the session tracking mechanism which helps them to maintain information from
request to request. It can do many other things which are difficult to implement in the
CGI programs.
Efficiency
As compared to CGI the servlets invocation is highly efficient. When the servlet get
loaded in the server, it remains in the server's memory as a single object instance.
However with servlets there are N threads but only a single copy of the servlet class.
Multiple concurrent requests are handled by separate threads so we can say that the
servlets are highly scalable.
Safety
As servlets are written in java, servlets inherit the strong type safety of java language.
Java's automatic garbage collection and a lack of pointers means that servlets are
generally safe from memory management problems. In servlets we can easily handle
the errors due to Java's exception handling mechanism. If any exception occurs then it
will throw an exception.
Integration
Servlets are tightly integrated with the server. Servlet can use the server to translate the
file paths, perform logging, check authorization, and MIME type mapping etc.
Extensibility
The servlet API is designed in such a way that it can be easily extensible. As it stands
today, the servlet API support Http Servlets, but in later date it can be extended for
another type of servlets.

Inexpensive
There are number of free web servers available for personal use or for commercial
purpose. Web servers are relatively expensive. So by using the free available web servers
you can add servlet support to it.

Advantages of Servlets over CGI


Servlets are server side components that provides a powerful mechanism for
developing server web applications for server side. Earlier CGI was developed to
provide server side capabilities to the web applications. Although CGI played a major
role in the explosion of the Internet, its performance, scalability and reusability issues
make it less than optimal solutions. Java Servlets changes all that. Built from ground
up using Sun's write once run anywheretechnology java servlets provide excellent
framework for server side processing.
Using servlets web developers can create fast and efficient server side applications and
can run it on any servlet enabled web server. Servlet runs entirely inside the Java
Virtual Machine. Since the servlet runs on server side so it does not depend on browser
compatibility.
Servlets have a number of advantages over CGI and other API's. They are:

1. Platform Independence
Servlets are written entirely in java so these are platform independent. Servlets
can run on any Servlet enabled web server. For example if you develop an web
application in windows machine running Java web server, you can easily run the
same on apache web server (if Apache Serve is installed) without modification or
compilation of code. Platform independency of servlets provide a great
advantages over alternatives of servlets.
2. Performance
Due to interpreted nature of java, programs written in java are slow. But the java
servlets runs very fast. These are due to the way servlets run on web server. For
any program initialization takes significant amount of time. But in case of servlets
initialization takes place first time it receives a request and remains in memory till
times out or server shut downs. After servlet is loaded, to handle a new request it
simply creates a new thread and runs service method of servlet. In comparison to
traditional CGI scripts which creates a new process to serve the request.
3. Extensibility
Java Servlets are developed in java which is robust, well-designed and object
oriented language which can be extended or polymorphed into new objects. So
the java servlets take all these advantages and can be extended from existing class
to provide the ideal solutions.
4. Safety
Java provides very good safety features like memory management, exception
handling etc. Servlets inherits all these features and emerged as a very powerful
web server extension.
5. Secure
Servlets are server side components, so it inherits the security provided by the
web server. Servlets are also benefited with Java Security Manager.

Introduction to Server Side Programming


All of us (or most of us) would have started programming in Java with the ever famous
“Hello World!” program. If you can recollect, we saved this file with a .java extension
and later compiled the program using javac and then executed the class file with java.
Apart from introducing you to the language basics, the point to be noted about this
program is that – “It is a client side program”. This means that you write, compile and
also execute the program on a client machine (e.g. Your PC). No doubt, this is the
easiest and fastest way to write, compile and execute programs. But, it has little
practical significance when it comes to real world programming.

1. Why Server Side Programming?

Though it is technically feasible to implement almost any business logic using


client side programs, logically or functionally it carries no ground when it comes
to enterprise applications (e.g. banking, air ticketing, e-shopping etc.). To further
explain, going by the client side programming logic; a bank having 10,000
customers would mean that each customer should have a copy of the program(s)
in his or her PC which translates to 10,000 programs! In addition, there are issues
like security, resource pooling, concurrent access and manipulations to
the database which simply cannot be handled by client side programs. The answer
to most of the issues cited above is – “Server Side Programming”. Figure-1
illustrates Server side architecture in the simplest terms.

2. Advantages of Server Side Programs

The list below highlights some of the important advantages of Server Side
programs.
i. All programs reside in one machine called the Server. Any number of
remote machines (called clients) can access the server programs.
ii. New functionalities to existing programs can be added at the server side
which the clients’ can advantage without having to change anything from
their side.
iii. Migrating to newer versions, architectures, design patterns, adding
patches, switching to new databases can be done at the server side without
having to bother about clients’ hardware or software capabilities.
iv. Issues relating to enterprise applications like resource management,
concurrency, session management, security and performance are managed
by service side applications.
v. They are portable and possess the capability to generate dynamic and user-
based content (e.g. displaying transaction information of credit card or
debit card depending on user’s choice).

3. Types of Server Side Programs


i. Active Server Pages (ASP)
ii. Java Servlets
iii. Java Server Pages (JSPs)
iv. Enterprise Java Beans (EJBs)
v. PHP

To summarize, the objective of server side programs is to centrally manage all


programs relating to a particular application (e.g. Banking, Insurance, e-shopping,
etc). Clients with bare minimum requirement (e.g. Pentium II, Windows XP
Professional, MS Internet Explorer and an internet connection) can experience the
power and performance of a Server (e.g. IBM Mainframe, Unix Server, etc) from a
remote location without having to compromise on security or speed. More
importantly, server programs are not only portable but also possess the capability to
generate dynamic responses based on user’s request.

Servlet Application Architecture


A servlet is a Java class that can be loaded dynamically into and run by a special web
server. This
servlet-aware web server is called a servlet container, which also was called a servlet
engine in the
early days of the servlet technology.
Servlets interact with clients via a request-response model based on HTTP. Because
servlet
technology works on top of HTTP, a servlet container must support HTTP as the protocol
for
client requests and server responses. However, a servlet container also can support
similar
protocols, such as HTTPS (HTTP over SSL) for secure transactions.

Servlet Servlet
Container
Http Request
Browser HTTP
Server
Http Response

Static
Contents

Basic Servlet Structure


As seen earlier, Java servlets are server side programs or to be more specific; web
applications that run on servers that comply HTTP protocol. The javax.servlet and
javax.servlet.http packages provide the necessary interfaces and classes to work with
servlets. Servlets generally extend the HttpServlet class and override the doGet or the
doPost methods. In addition, other methods such as init, service and destroy also called as
life cycle methods might be used which will be discussed in the following section. The
skeleton of a servlet is given in Figure

A Servlet’s Life Cycle


The first time a servlet is invoked, it is the init method which is called. And remember
that this is called only once during the lifetime of a servlet. So, you can put all your
initialization code here. This method next calls the service method. The service method in
turn calls the doGet or doPost methods (whichever the user has overridden). Finally, the
servlet calls the destroy method. It is in a sense equivalent to the finally method. You can
reset or close references / connections done earlier in the servlet’s methods (e.g. init,
service or doGet /doPost). After this method is called, the servlet ceases to exist for all
practical purposes. However, please note that it is not mandatory to override all these
methods. More often than not, it is the doGet or doPost method used with one or more of
the other life cycle methods.

A Simple Java Servlet Example:-

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

public class HelloWorld extends HttpServlet


{
Public void doGet(HttpServletRequest req, HttpServletReaponse res) throws
ServletException,IOException
{
Res.setContentType(“text/html”);
PrintWriter out=res.getWriter();
out.println(“<HTML>”);
out.println(“<HEAD><TITLE>Hello, welcome to the world of servlet
programming</TITLE></HEAD>”);
out.println(“<BODY BGCOLOR=RED>”);
out.println(“<H1>Hello world!</H1>”);
out.pritpln(“</BODY></HTML>”);
out.close();
}
}

Tomcat Web Server


Tomcat is one of the most popular open source web server (including web- container) for
deploying and running web applications

Tomcat Installation
The installation process is described for tomacat 6.0:
1. Before installing tomcat 5.5 make sure that you have installed JDK1.6 on your
machine. The environment variable JAVA_HOME should be set to C:\Program
Files\Java\jdk1.6.0_01.
2. Double click on the setup file to install the tomcat. Click on next-> select I agree.
3. The installer then prompts for port number, user and password. The default port
number on which the tomcat server runs is 8080; you can leave it as it is. The
default user name is admin; you can leave this also as it is. Specify your
password. And password must be remembered as only the authorized user can
access tomcat administration site.
4. The installer then asks for the path of J2SE 6.0 JRE installed on the machine. By
default path C:\program Files\Java\jre1.6.0_01 is selected, which is the default
path where the JRE is installed. Leave the selection as it is if you have not
changed the default path while installing JRE otherwise give the path where you
have installed the JRE.
5. Finally click on the install button.After this installation process will take few
seconds to complete.

Six Steps to Running Your First Servlet


After you have installed and configured Tomcat, you can put it into service. Basically,
you need to
follow six steps to go from writing your servlet to running it. These steps are summarized
as
follows:
1. Create a directory structure under Tomcat for your application.
2. Write the servlet source code.
3. Compile your source code.
4. Create a deployment descriptor.
5. Run Tomcat.
6. Call your servlet from a web browser.
Step1:- Create the following directory structure for your Web Application “star”
In webapps

star (folder)

index.html(welcome file)

WEB-INF(folder)
classes(folder)
HelloWorld.class
lib(folder)
web.xml(file- deployment descriptor)

Step2:- Write your code in HelloWorld.java and save it.

Step3:- Compile the java file and put your class in folder classes. Remember before
compile the code %CATALINA%\lib\servlet-api.jar should be in class path

Step4:- Create a web.xml which is known as deployment descriptor and save it in WEB-
INF

A deployment descriptor is an optional component in a servlet application. The descriptor takes


the form of an XML document called web.xml and must be located in the WEB-INF directory of
the servlet application. When present, the deployment descriptor contains configuration settings
specific to that application
The web.xml for above example application must have the following content.

<?xml version="1.0" ?>


- <web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
-
- <servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
- <servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>

The tags for the 'web.xml' file above are pretty simple to understand. First we define a
<servlet> tag within <web-app></web-app> tags. In <servlet-name> we provide name of
our Servlet and in <servlet-class>, the complete package and class name of
HelloWorld class. The <servlet-mapping> tag allows us to specify a a URL pattern which
when requested by the client browser, will result in the delegation of the response
generation by the Servlet Container to our HelloWorld.

This is all for 'web.xml' file.

Step5:- Now run Tomcat by click on tomcat6.exe available in C:\Program Files\Apache


Software Foundation\Tomcat 6.0\bin.

Step6: Now open your browser and point to this


address: http://localhost:8080/star/HelloWorld. You should a get response like following
image in your browser window:
Example:- 2:- In given example we have shown how to display Current date .
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.*;
import javax.servlet.http.*;

public class TestServlet extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws IOException, ServletException {

res.setContentType("text/html");

PrintWriter out = res.getWriter();

/* Display some response to the user */

out.println("<html><head>");
out.println("<title>TestServlet</title>");

out.println("</head>");
out.println("<body>");

out.println("<p>Current Date/Time: " +


new Date().toString() + "</p>");
out.println("</body></html>");

out.close();
}
}
Explanation
Our TestServlet is extremely simple. It displays the current date and time on the server to
the user.

We overrode just one method of HttpServlet class. doGet() is called when a HTTP GET
request is received by the Servlet Container. In this method we set the content type of our
response to 'text/html' (informing the client browser that it is an HTML document). Then
we get hold of PrintWriter object and using its println() method, we send our own HTML
content to the client browser. Once we are finished, we call its close() method.
Output:-

Example:- In given example we will create an application name greeting application in


which we fill a form an on the basis of that we will display contents:
In this program we have created three files index.html which is stored in Greeting folder
parallel to WEB-INF , web.xml which is stored in WEB-INF, and GreetingServlet.class
stored in classes folder in WEB-INF

Index.html

<html>
<head> <title>Projava registration</title></head>
<body >
<h1>Welcome</h1>
<form action="GreetingServlet" method="POST">
<p> Your Name<input type="text"size="40" name="name"/></p>
<p> Your email<input type="text" siez="40" name="email"/></p>
<input type="submit" value="Submit"/></p>
</form>
</body>
</html>
web.xml
<?xml version="1.0"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<servlet>
<servlet-name>GreetingServlet</servlet-name>
<servlet-class>GreetingServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>GreetingServlet</servlet-name>
<url-pattern>/GreetingServlet</url-pattern>
</servlet-mapping>

</web-app>

GreetingServlet.java

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;
public class GreetingServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
String name=req.getParameter("name");
String email=req.getParameter("email");
String message=null;
GregorianCalendar cal=new GregorianCalendar();
if(cal.get(Calendar.AM_PM)==Calendar.AM)
message="Good Morning";
else
message="Good Evening";
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<p>"+message+","+name+"</p>");
out.println("<p> Thanks for registering your email("+email+")with us.</p>");
out.println("<p>-The project Java Team.</p>");
out.println("</body>");
out.println("</html>");
out.close();
}

Accessing Greeting Application:


Step1:- type http://localhost:8080/Greeting or http://localhost:8080/Greeting/index.html

Step2:- fill the name and email


Step3:-Click on the sublit button
Step4:- GreetingServlet will be invoked and will give the following response
Methods of Servlets

A Generic servlet contains the following five methods:


init()

public void init(ServletConfig config) throws ServletException


The init() method is called only once by the servlet container throughout the life of a
servlet. By this init() method the servlet get to know that it has been placed into
service.
The servlet cannot be put into the service if

• The init() method does not return within a fix time set by the web server.
• It throws a ServletException

Parameters - The init() method takes a ServletConfig object that contains the
initialization parameters and servlet's configuration and throws a ServletException if
an exception has occurred.

service()

public void service(ServletRequest req, ServletResponse res) throws


ServletException, IOException
Once the servlet starts getting the requests, the service() method is called by the servlet
container to respond. The servlet services the client's request with the help of two
objects. These two
objectsjavax.servlet.ServletRequest and javax.servlet.ServletResponse are passed
by the servlet container.

The status code of the response always should be set for a servlet that throws or sends
an error.

Parameters - The service() method takes the ServletRequest object that contains the
client's request and the object ServletResponse contains the servlet's response. The
service() method throws ServletException and IOExceptions exception.

getServletConfig()

public ServletConfig getServletConfig()


This method contains parameters for initialization and startup of the servlet and returns
a ServletConfig object.This object is then passed to the init method. When this
interface is implemented then it stores the ServletConfig object in order to return it. It
is done by the generic class which implements this inetrface.
Returns - the ServletConfig object
getServletInfo()

public String getServletInfo()


The information about the servlet is returned by this method like version, author etc.
This method returns a string which should be in the form of plain text and not any kind
of markup.
Returns - a string that contains the information about the servlet
destroy()

public void destroy()


This method is called when we need to close the servlet. That is before removing a
servlet instance from service, the servlet container calls the destroy() method. Once the
servlet container calls the destroy() method, no service methods will be then called .
That is after the exit of all the threads running in the servlet, the destroy() method is
called. Hence, the servlet gets a chance to clean up all the resources like memory,
threads etc which are being held.

Life cycle of Servlet:- The first time a servlet is invoked, it is the init method
which is called. And remember that this is called only once during the lifetime of a
servlet. So, you can put all your initialization code here. This method next calls the
service method. The service method in turn calls the doGet or doPost methods
(whichever the user has overridden). Finally, the servlet calls the destroy method. It is in
a sense equivalent to the finally method. You can reset or close references / connections
done earlier in the servlet’s methods (e.g. init, service or doGet /doPost). After this
method is called, the servlet ceases to exist for all practical purposes. However, please
note that it is not mandatory to override all these methods. More often than not, it is the
doGet or doPost method used with one or more of the other life cycle methods.

The life cycle of a servlet can be categorized into four parts:

1. Loading and Inatantiation: The servlet container loads the servlet during startup
or when the first request is made. The loading of the servlet depends on the
attribute <load-on-startup> of web.xml file. If the attribute <load-on-startup> has
a positive value then the servlet is load with loading of the container otherwise it
load when the first request comes for service. After loading of the servlet, the
container creates the instances of the servlet.
2. Initialization: After creating the instances, the servlet container calls the init()
method and passes the servlet initialization parameters to the init() method. The
init() must be called by the servlet container before the servlet can service any
request. The initialization parameters persist untill the servlet is destroyed. The
init() method is called only once throughout the life cycle of the servlet.

The servlet will be available for service if it is loaded successfully otherwise the
servlet container unloads the servlet.
3. Servicing the Request: After successfully completing the initialization process,
the servlet will be available for service. Servlet creates seperate threads for each
request. The sevlet 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.
4. Destroying the Servlet: If the servlet is no longer needed for servicing any
request, the servlet container calls the destroy() method . Like the init() method
this method is also called only once throughout the life cycle of the servlet.
Calling the destroy() method indicates to the servlet container not to sent the any
request for service and the servlet releases all the resources associated with it.
Java Virtual Machine claims for the memory associated with the resources for
garbage collection.
Life Cycle of a Servlet

Example:- example given below shows the life cycle of a servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Servlet_LifeCycle extends HttpServlet{
int i;

public void init() throws ServletException


{
i=0;//initializing i value
}
public void doGet(HttpServletRequest req,HttpServletResponse res) throws
IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
if(i==0)
{
out.println("<HTML><HEAD><TITLE>Servlet's life
cycle</TITLE>");
out.println("</HEAD><BODY><h1>i value initializzed in init
method");
out.println("</h1>"+"<h1>"+i+"</h1>");
out.println("</body>");
out.println("</html>");
}
i=i+1;
if(i==10)
{
out.println("<HTML><HEAD><TITLE>Servlet's life cycle</TITLE>");

out.println("</HEAD><BODY><h1>i value initializzed 10,");


out.println("hencecalling destroy method to reset it in init
method");
out.println("</h1>"+"<h1>"+i+"</h1>");
out.println("</body>");
out.println("</html>");
destroy();
}
else if(i<10)
{out.println("<HTML><HEAD><TITLE>Servlet's life
cycle</TITLE>");
out.println("</HEAD><BODY><h1>i value initializzed in doGet
method");
out.println("</h1>"+"<h1>"+i+"</h1>");
out.println("</body>");
out.println("</html>");
}

}
public void destroy()
{
i=0;

Output:-

First time output will be given as above . To appreciate the execution of the servlet life
cycle methods, keep refreshing the browser (F5 in Windows). In the background, what
actually happens is – with each refresh, the doGet method is called which increments
i’s value and displays the current value. After press F5 56 times output will be as given
after press F5 10 times output is:
Example:- In this example we are going to know how we can make a program on
counter which will keep track how many times the servlet has been accessed.

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

public class SimpleCounter extends HttpServlet{


static int counter = 0;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
counter++;
pw.println("At present the value of the counter is " + counter);
}
}
Output:-

Java Servlet API:-

Servlets are basically developed for server side applications and designed to
handle http requests. The servlet- programming interface (Java Servlet API) is a standard
part of the J2EE plateform and has the following advantage over other comman server
extension mechanisms:
• They are faster than other server extensions, like,CGI scripts because they
use a different process model.
• They use a standards API that is supported by many Web servers.
• Since servlets are written in java, servlets are portable between servers and
operating systems. They have all of the advantage of the java language,
including ease of development.
They can access the large set of APIs available for the java plateform.

The Servlet API is specified in two Java extension packages.


1. javax.servlet
2. javax.servlet.http

The classes and interface in the javax.servlet package are protocol – independent. While
the second package javax.servlet.http contains classes and interfaces that are specified
to HTTP. Some of the classes/ interfaces in the javax.servlet.http extend those in the
javax.servlet package.

Overview of the java servlet API


The most commonly used classes/ interfaces of the Servlet are described below:
Purpose Class/Interface

Servlet Implementation javax.servlet.Servlet(Interface)


javax.servlet.SingleThreadModel(Interface)
javax.servlet.Genericservlet (Abstract class)
javax.servlet.http.HttpServlet(Abstract class)

Servlet Exception Javax.servlet.ServletException(Generic


Exception)
Javax.servlet.UnavailableException(Temp or
Parmanent)

Servlet Configurations Javax.servlet.ServletConfig(Interface)

Request and Responses Javax.servlet.Servletrequest(Interface)


Javax.servlet.ServletResponse(Interface)
Javax.servlet.ServletInputStream(class)
Javax.servlet.ServletOutputStream(class)
Javax.servlet.http.HttpServletRequest(Interface)
Javax.servlet.http.HttpServletResponse(Interface)

Session Tracking Javax.servlet.http.HttpSession(Interface)

Servlet Context Javax.servlet.ServletContext(Interface)

Servlet Collaboration Javax.servlet.RequestDispatcher

Filtering Javax.servlet.Filter(Interface)
Javax.servlet.FilterChain(Interface)
Javax.servlet..FilterConfig(Interface)

Cookies Javax.servlet..http.Cookie(Interface)

Web servers with java servlet implementation. Such as tomcat, Weblogic, Orion, iPlanet,
JRUN etc use most of the interfaces and classes in the above table. In fact apart from the
various listener interfaces, there is only one class (javax.servlet.http.HttpServlet) and one
interface( javax.servlet.Filter) that are left for you to implement when building web
applications.

1.1 Servlets
Servlets are Java technology’s answer to Common Gateway Interface (CGI)
programming. They are programs that run on a Web server, acting as a
middle
layer between a request coming from a Web browser or other HTTP client
and databases or applications on the HTTP server. Their job is to:
1. Read any data sent by the user.
This data is usually entered in a form on a Web page, but could
also come from a Java applet or a custom HTTP client program.
2. Look up any other information about the request that is
embedded in the HTTP request.
This information includes details about browser capabilities,
cookies, the host name of the requesting client, and so forth.

T
6 Chapter 1 Overview of Servlets and JavaServer Pages
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book’s author: courses.coreservlets.com.
© Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
3. Generate the results.
This process may require talking to a database, executing an
RMI or CORBA call, invoking a legacy application, or computing
the response directly.
4. Format the results inside a document.
In most cases, this involves embedding the information inside
an HTML page.
5. Set the appropriate HTTP response parameters.
This means telling the browser what type of document is being
returned (e.g., HTML), setting cookies and caching parameters,
and other such tasks.
6. Send the document back to the client.
This document may be sent in text format (HTML), binary format
(GIF images), or even in a compressed format like gzip that
is layered on top of some other underlying format.
Many client requests can be satisfied by returning pre-built documents,
and these requests would be handled by the server without invoking servlets.
In many cases, however, a static result is not sufficient, and a page needs to
be generated for each request. There are a number of reasons why Web
pages need to be built on-the-fly like this:
• The Web page is based on data submitted by the user.
For instance, the results page from search engines and
order-confirmation pages at on-line stores are specific to
particular user requests.
• The Web page is derived from data that changes
frequently.
For example, a weather report or news headlines page might
build the page dynamically, perhaps returning a previously built
page if it is still up to date.
• The Web page uses information from corporate
databases or other server-side sources.
For example, an e-commerce site could use a servlet to build a
Web page that lists the current price and availability of each
item that is for sale.
In principle, servlets are not restricted to Web or application servers that
handle HTTP requests, but can be used for other types of servers as well. For
1.2 The Advantages of Servlets Over “Traditional” CGI 7
© Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book’s author: courses.coreservlets.com.
example, servlets could be embedded in mail or FTP servers to extend their
functionality. In practice, however, this use of servlets has not caught on, and
I’ll only be discussing HTTP servlets.
1.2 The Advantages of Servlets
Over “Traditional” CGI
Java servlets are more efficient, easier to use, more powerful, more portable,
safer, and cheaper than traditional CGI and many alternative CGI-like
technologies.
Efficient
With traditional CGI, a new process is started for each HTTP request. If the
CGI program itself is relatively short, the overhead of starting the process can
dominate the execution time. With servlets, the Java Virtual Machine stays
running and handles each request using a lightweight Java thread, not a
heavyweight operating system process. Similarly, in traditional CGI, if there
are N simultaneous requests to the same CGI program, the code for the CGI
program is loaded into memory N times. With servlets, however, there would
be N threads but only a single copy of the servlet class. Finally, when a CGI
program finishes handling a request, the program terminates. This makes it
difficult to cache computations, keep database connections open, and
perform
other optimizations that rely on persistent data. Servlets, however,
remain in memory even after they complete a response, so it is
straightforward
to store arbitrarily complex data between requests.
Convenient
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 high-level utilities. Besides, you
already
know the Java programming language. Why learn Perl too? You’re already
convinced
that Java technology makes for more reliable and reusable code than
does C++. Why go back to C++ for server-side programming?
8 Chapter 1 Overview of Servlets and JavaServer Pages
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book’s author: courses.coreservlets.com.
© Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
Powerful
Servlets support several capabilities that are difficult or impossible to
accomplish
with regular CGI. Servlets can talk directly to the Web server, whereas
regular CGI programs cannot, at least not without using a server-specific
API. Communicating with the Web server makes it easier to translate relative
URLs into concrete path names, for instance. Multiple servlets can also share
data, making it easy to implement database connection pooling and similar
resource-sharing optimizations. Servlets can also maintain information from
request to request, simplifying techniques like session tracking and caching
of previous computations.
Portable
Servlets are written in the Java programming language and follow a standard
API. Consequently, servlets written for, say, I-Planet Enterprise Server can
run virtually unchanged on Apache, Microsoft Internet Information Server
(IIS), IBM WebSphere, or StarNine WebStar. For example, virtually all of
the servlets and JSP pages in this book were executed on Sun’s Java Web
Server, Apache Tomcat and Sun’s JavaServer Web Development Kit
(JSWDK) with no changes whatsoever in the code. Many were tested on
BEA WebLogic and IBM WebSphere as well. In fact, servlets are supported
directly or by a plug-in on virtually every major Web server. They are now
part of the Java 2 Platform, Enterprise Edition (J2EE; see
http://java.sun.com/j2ee/), so industry support for servlets is becoming
even more pervasive.
Secure
One of the main sources of vulnerabilities in traditional CGI programs
stems from the fact that they are often executed by general-purpose
operating
system shells. So the CGI programmer has to be very careful to filter
out characters such as backquotes and semicolons that are treated specially
by the shell. This is harder than one might think, and weaknesses stemming
from this problem are constantly being uncovered in widely used CGI
libraries. A second source of problems is the fact that some CGI programs
are processed by languages that do not automatically check array or string
bounds. For example, in C and C++ it is perfectly legal to allocate a
1.3 JavaServer Pages 9
© Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book’s author: courses.coreservlets.com.
100-element array then write into the 999th “element,” which is really some
random part of program memory. So programmers who forget to do this
check themselves open their system up to deliberate or accidental buffer
overflow attacks. Servlets suffer from neither of these problems. Even if a
servlet executes a remote system call to invoke a program on the local
operating
system, it does not use a shell to do so. And of course array bounds
checking and other memory protection features are a central part of the
Java programming language.
Inexpensive
There are a number of free or very inexpensive Web servers available that
are
good for “personal” use or low-volume Web sites. However, with the major
exception of Apache, which is free, most commercial-quality Web servers are
relatively expensive. Nevertheless, once you have a Web server, no matter
its
cost, adding servlet support to it (if it doesn’t come preconfigured to support
servlets) costs very little extra. This is in contrast to many of the other CGI
alternatives, which require a significant initial investment to purchase a
proprietary
package.

The Benefits of Servlets


When it first emerged, this great thing we call the Internet consisted of only static contents written
using Hypertext Markup Language (HTML). At that time, anyone who could author HTML pages
was considered an Internet expert.
This did not last long, however.
Soon dynamic web contents were made possible through the Common Gateway Interface (CGI)
technology. CGI enables the web server to call an external program and pass HTTP request
information to that external program to process the request. The response from the external
program is then passed back to the web server, which forwards it to the client browser. CGI
programs can be written in any language that can be called by the web server. Over the course of
time, Perl became the most popular language to write CGI programs.
As the Internet became more and more popular, however, the number of users visiting a popular
web site increased exponentially, and it became apparent that CGI had failed to deliver scalable
Internet applications. The flaw in CGI is that each client request makes the web server spawn a
new process of the requested CGI program. As we all know, process creation is an expensive
operation that consumes a lot of CPU cycles and computer memory.
3
Gradually, new and better technologies will replace CGI as the main technology for web
application development. The world has witnessed the following technologies trying to dominate
web development:
• ColdFusion. Allaire's ColdFusion provides HTML-like custom tags that can be used to
perform a number of operations, especially querying a database. This technology had its
glamorous time in the history of the World Wide Web as the main technology for web
application programming. Its glorious time has since gone with the invention of other
technologies.
• Server-side JavaScript (SSJS). SSJS is an extension of the JavaScript language, the
scripting language that still rules client-side web programming. SSJS can access Java
classes deployed at the server side using the LiveWire technology from Netscape.
• PHP. PHP is an exciting open-source technology that has matured in recent years. The
technology provides easy web application development with its session management and
includes some built-in functionality, such as file upload. The number of programmers
embracing PHP as their technology of choice has risen sharply in recent years.
• Servlet. The servlet technology was introduced by Sun Microsystems in 1996. This
technology is the main focus of this book and will be explained in more detail in this and
coming chapters.
• JavaServer Pages (JSP). JSP is an extension of the servlet technology. This, too, is the
center of attention in this book.
• Active Server Pages (ASP). Microsoft's ASP employs scripting technologies that work
in Windows platforms, even though there have been efforts to port this technology to
other operating systems. Windows ASP works with the Internet Information Server web
server. This technology will soon be replaced by Active Server Pages.NET.
• Active Server Pages.NET (ASP.NET). This technology is part of Microsoft's .NET
initiative. Interestingly, the .NET Framework employs a runtime called the Common
Language Runtime that is very similar to Java Virtual Machine and provides a vast class
library available to all .NET languages and from ASP.NET pages. ASP.NET is an
exciting technology. It introduced several new technologies including state management
that does not depend on cookies or URL rewriting.
In the past, ASP and servlet/JSP have been the main technologies used in web application
development. With the release of ASP.NET, it is not hard to predict that this technology will
become the servlet/JSP's main competitor. ASP (and ASP.NET) and servlet/JSP each have their
own fans, and it is not easy to predict which one will come out the winner. The most likely
outcome is that neither will be an absolute winner that corners the market; instead the technologies
will probably run head-to-head in the coming years.
Servlet (and JSP) offers the following benefits that are not necessarily available in other
technologies:
• Performance. The performance of servlets is superior to CGI because there is no process
creation for each client request. Instead, each request is handled by the servlet container
process. After a servlet is finished processing a request, it stays resident in memory,
waiting for another request.
• Portability. Similar to other Java technologies, servlet applications are portable. You can
move them to other operating systems without serious hassles.
• Rapid development cycle. As a Java technology, servlets have access to the rich Java
library, which helps speed up the development process.
• Robustness. Servlets are managed by the Java Virtual Machine. As such, you don't need
to worry about memory leak or garbage collection, which helps you write robust
applications.
• Widespread acceptance. Java is a widely accepted technology. This means that
numerous vendors work on Java-based technologies. One of the advantages of this
4
widespread acceptance is that you can easily find and purchase components that suit your
needs, which saves precious development time.
Servlet Application Architecture
A servlet is a Java class that can be loaded dynamically into and run by a special web server. This
servlet-aware web server is called a servlet container, which also was called a servlet engine in the
early days of the servlet technology.
Servlets interact with clients via a request-response model based on HTTP. Because servlet
technology works on top of HTTP, a servlet container must support HTTP as the protocol for
client requests and server responses. However, a servlet container also can support similar
protocols, such as HTTPS (HTTP over SSL) for secure transactions.
Figure 1.1 provides the architecture of a servlet application.
Figure 1.1. The servlet application architecture.
In a JSP application, the servlet container is replaced by a JSP container. Both the servlet
container and the JSP container often are referred to as the web container or servlet/JSP container,
especially if a web application consists of both servlets and JSP pages.
Note
You will learn more about servlet and JSP containers in Chapter 8, "JSP Basics."
As you can see in the Figure 1.1, a servlet application also can include static content, such as
HTML pages and image files. Allowing the servlet container to serve static content is not
preferable because the content is faster if served by a more robust HTTP server, such as the
Apache web server or Microsoft Internet Information Server. As such, it is common practice to
put a web server at the front to handle all client requests. The web server serves static content and
passes to the servlet containers all client requests for servlets. Figure 1.2 shows a more common
architecture for a servlet application.
Figure 1.2. The servlet application architecture employing an HTTP server.
Caution
A Java web application architecture employing a J2EE server is different from the
diagrams in Figures 1.1
How a Servlet Works
A servlet is loaded by the servlet container the first time the servlet is requested. The servlet then
is forwarded the user request, processes it, and returns the response to the servlet container, which
in turn sends the response back to the user. After that, the servlet stays in memory waiting for
other requests—it will not be unloaded from the memory unless the servlet container sees a
shortage of memory. Each time the servlet is requested, however, the servlet container compares
the timestamp of the loaded servlet with the servlet class file. If the class file timestamp is more
recent, the servlet is reloaded into memory. This way, you don't need to restart the servlet
container every time you update your servlet.
The way in which a servlet works inside the servlet container is depicted in the diagram in Figure
1.3.
Figure 1.3. How a servlet works.

The Tomcat Servlet Container


A number of servlet containers are available today. The most popular one—and the one
recognized as the official servlet/JSP container—is Tomcat. Originally designed by Sun
Microsystems, Tomcat source code was handed over to the Apache Software Foundation in
October 1999. In this new home, Tomcat was included as part of the Jakarta Project, one of the
6
projects of the Apache Software Foundation. Working through the Apache process, Apache, Sun,
and other companies—with the help of volunteer programmers worldwide—turned Tomcat into a
world-class servlet reference implementation. Two months after the handover, Tomcat version 3.0
was released. Tomcat went through several 3.x releases until version 3.3 was introduced.
The successor of version 3.3 is the current version, version 4.0. The 4.0 servlet container (Catalina)
is based on a completely new architecture and has been developed from the ground up for
flexibility and performance. Version 4.0 implements the Servlet 2.3 and JSP 1.2 specifications,
and it is this version you will be using in this book.
Another popular servlet container is JRun from Allaire Corporation. JRun is available in three
editions: Developer, Professional, and Enterprise. The Developer edition is free but not licensed
for deployment. The Professional and Enterprise editions grant you the license for deployment
with a fee. You can download JRun from http://commerce.allaire.com/download.
Tomcat by itself is a web server. This means that you can use Tomcat to service HTTP requests
for servlets, as well as static files (HTML, image files, and so on). In practice, however, since it is
faster for non-servlet, non-JSP requests, Tomcat normally is used as a module with another more
robust web server, such as Apache web server or Microsoft Internet Information Server. Only
requests for servlets or JSP pages are passed to Tomcat.
To write a servlet, you need at least version 1.2 of the Java Development Kit. If you have not
already downloaded one, you can download JDK 1.2 from http://java.sun.com/j2se. The reference
implementation for both servlets and JSP are not included in J2SE, but they are included in
Tomcat. Tomcat is written purely in Java.
If you haven't yet installed and configured Tomcat, now's the time to do it. If you need help with
these tasks, refer to Appendix A for specific steps.
Six Steps to Running Your First Servlet
After you have installed and configured Tomcat, you can put it into service. Basically, you need to
follow six steps to go from writing your servlet to running it. These steps are summarized as
follows:
1. Create a directory structure under Tomcat for your application.
2. Write the servlet source code. You need to import the javax.servlet package and the
javax.servlet.http package in your source file.
3. Compile your source code.
4. Create a deployment descriptor.
5. Run Tomcat.
6. Call your servlet from a web browser.
The sect

You might also like