You are on page 1of 47

Enterprise Application:-

An enterprise application is a business application. In today’s corporate environment, enterprise


applications are complex, Scalable, distributed component based and mission critical.

An enterprise application (EA) is a large software system platform designed to operate in a


corporate environment such as business or government. EAs are complex, scalable,
component-based, distributed and mission critical. EA software consists of a group of programs
with shared business applications and organizational modeling utilities designed for
unparalleled functionalities. EAs are developed using enterprise architecture.

EA software is a critical component of any computer-based information system. EA software


ultimately enhances efficiency and productivity through business level support functionality.

EA software services include online shopping and payment processing, interactive product
catalogs, computerized billing systems, security, content management, IT service management,
content switching modules, resource planning, business intelligence, human resource
management, manufacturing, application integration, forms automation, sales force
automation, enterprise resource planning and business process management.

Java Enterprise Edition:-

Java platform consists of a Java Virtual Machines and implementations of standard libraries.

To develop the applications for different types of system , there are now three version of the java
Platform:

1. Java Platform, Micro Edition Java(Java ME)


2. Java Platform , Standard Edition(Java SE)
3. Java Platform, Enterprise Edition(Java EE)

1. Java Platform, Micro Edition Java(Java ME)

i) Collection of Java APIs


ii) Used for the development of software for resource constrained devices such as
PDAs, Cell Phones and consumer product such as AC, Fridges, Micro waves , Setup
boxes.
iii) Used for creating games for cell phones.

2. Java Platform , Standard Edition(Java SE)

i) Collection of Java Programming Language APIS


ii) Used for developing general purpose software application for desktop PCs, Server
and Small Devices.
iii) Provides a huge number of ready to use classes. A Java package organizes these
classes into groups, similar to the Sections of books in library.

3. Java Platform, Enterprise Edition(Java EE)

i) Used for developing and running distributed multi –tier architecture java applications .
ii) These applications are mostly modular software components running on an application
server.

Its Core component is Enterprise Java Beans(EJBs), followed by Java Server Pages (JSPs) and Java Servlet
Pages and Java Servlets and a variety of interfaces for linking to the information resources in the
enterprise. Java EE includes several API Specifications such as JDBC, RMI, Java Mail, Java Mesagging
System, Web services , XML and so on and defines how to Coordinate them.

Architecture of an Enterprise Application


Enterprise architecture is the extension of the concept of multi tier architecture and available
technologies resulting in a custom made platform that can run across hardware and software
frameworks found across an enterprise.

Enterprise architecture is divided into the following tiers:

1. Client Tier Services run on the client machine.


2. Web Tier services run on the server.
3. Business Tier Services run on the server.
4. Enterprise Information System Tier software runs on the EIS Server.

Java EE Technologies:
Web Application Technologies:

Java Servlet

A servlet is a program that extends the functionality of a web server . Servlet receives a Request
from a client, dynamically generate the response and then send the response containing an
HTML or XML document to the client.
Java Server Pages

Java server pages technology helps to generate dynamic content for a web client. A JSP is a text based
document that contains two types of text:

 Static Data
 JSP Elements

Java Server Pages Standard Tag Library

It encapsulates core functionality of JSP Applications. This technology allows creating a standard
set of tags, instead of mixing tags from numerous vendors in a JSP Application.

JavaServer Faces

It is a user interface framework for building web applications.

Facelets

It refers to java server Faces view definition Framework which is a page declaration language developed
for use with java server technology.

Enterprise Application Technologies


Enterprise Java Beans

An EJB component is an enterprise beans having methods to implement modules of business


logic. They are scalable , transactional, secure and are building blocks of the enterprise
application running on Java EE server. EJBs can be accessed easily locally and remotely through
RMI or HTTP for SOAP and RESTful web services.

Java Persistence API


Java persistence is a java standard based API for Object Relational Mapping, a solution for
persistence.

Java Transaction API

It provides a standard interface for demarcating transactions.

Java Message Services

JMS API is a messaging standard that allows javaEE application components to create, send ,
receive and read messages.

Java Mail

It includes Java Mail with a service provider interface that allows application components to
send mails.

Web Services Technologies


Java EE provides supports for SOAP and RESTful web services.

Java API for RESTful web services defines APIs for the development of web services built
according to the REST architectural style.

Java API for XML Based web services provides support for web services using the SOAP/HTTP
Protocol.

Security Technologies

JACC
Java Authorization Contract for Containers specification defines a contract between a Java EE
application server and an authorization policy provider. It enable services to authenticate and
enforce access controls upon users.
JASPIC
Java Authentication service provider Interface for Containers specification defines a Service
Provider Interface by which authentication providers that implement message message
authentication mechanisms may be integrated in client or server message processing
containers or runtimes.

Java Enterprise Edition


Java EE is a set of coordinated technologies and practices that enable , developing, deploying
and managing multi tier server enterprise applications. It is a collection of standardized
components , containers and services for creating and deploying distributed applications within
a well defined distributed computing architecture.

Glassfish Server
GlassFish is an Application Server which can also be used as a Web Server (Http Server).

A web Server means: Handling HTTP requests (usually from browsers).

A Servlet Container (e.g. Tomcat) means: It can handle servlets & JSP.

An Application Server (e.g. GlassFish) means: It can manage Java EE applications (usually
both servlet/JSP and EJBs).

You should use GlassFish for Java EE enterprise applications.

Java EE Architecture, Server and Containers:

Applications are developed to support companies in their business operations. They take data as
input, process the data based on business rules and provide data or information as output. Based
on this fact, all applications have three elements:

1. The User Interface or the presentation element through which data is taken as input 
2. The Application Logic or the business rule element, which helps in implementing the
operations to be performed on the data input 
3. The Data Storage or the data management element, which manages the storage and
retrieval of data

These three elements form the core of all application architecture used in Commercial
Application Development.

Applications may vary from single-tier desktop applications to multi-tier applications.


Developers have several choices while deciding on the type of architecture to use in their
application, depending on its usage and deployment.

As a developer, before deciding on the number of tiers in application architecture, the following
factors must be considered:

1. Scalability: The capability of an application to adapt to any new hardware environment 

2. Availability: The ability of an application to cater to the increased demands


from clients

3. Extensibility: The ability of an application to incrementally add features from


time to time to improve performance and provide better functionality to the
client 

4. Security: The ability of an application to maintain the integrity of data

5. Maintainability: The ability of an application to respond to bug-fixes with the minimum


utilization of resources in terms of people, time and technology

6. Performance: The ability of an application to respond to a client request in the minimum


time

Types of System Architecture

The following are the different types of system architectures:

1. Single Tier Architecture


Some applications are written to run on a single computer. All the services provided by the
application i.e. the user interface, persistent data access and the logic that processes the data
input by the user and read and displayed to the user from a data store, all exist on the same
physical machine and are thus lumped together in the application.

Hence in a Single-tier architecture:

 The user interface of a Web application i.e. the presentation layer


 The middle ware i.e. the business rules
 The data access layer 
Are all contained in one single computer.

Advantages:
 The simplest and least expensive alternative
  Less equipment to purchase and maintain

Disadvantages:
1. This type of implementation is lower security and the lack of scalability. An architecture
is scalable when it can be easily expanded or augmented to meet increasing performance
needs
2. Having all of the site's major components and data on a single computer behind the
domain firewall leaves the site more vulnerable to malicious attacks
3. Running all of the site's components on a single computer also limits expansion and
optimization possibilities

If the developer knows that the application will not grow over time, then the developer may
decide to use single tier architecture.

2. Two Tier Architecture


In this architecture, an application is divided into two components:
1.  Client
a. Implements the user interface
b. Contains business logic 

2. Server- Used to store and access business data, captured by the user interface run on the
Client in  a data store at the Server 

Hence in a two-tier architecture:


 The User Interface is always physically located in the user's desktop [i.e. the Client) 
 The database management services are always physically located on a Server

The Server is always a more powerful machine as it has to service multiple client requests to
store or retrieve data.

In other words, the client machine gets the data from the user and passes it to the server for
processing whereas the server validates the input data based on business rules and accordingly
the data is updated in the database.

Advantages:

 Adds additional security by removing sensitive customer data from the single computer 
 Having the database on a separate computer improves the overall performance of the site 
 Allows optimizing each machine for more specific performance requirements

Disadvantages:

 The increased cost and complexity of the architecture


While this is the recommended architecture for an initial electronic commerce site, provide a cost
benefit analysis to the customer to help them make the decision.

3. Three Tier Architecture

This architecture is the evolution of two tier applications. Logically the application is divided
into three constituent layers:

 User Services - Presentation Layer: Provides service such as the Graphical User Interface
and other automation tasks that the application has to perform

 Business Services - Business Layer: Implements business rules. This layer encapsulates
the business logic from users such that they need not know how business logic is applied.
When business is upgraded, only the business layer is affected and must be upgraded, the
rest of the application services can remain untouched

 Data Services - Data Layer: Provides data availability and integrity. It is responsible for
adding, modifying and deleting data from the data store

This architecture, while it is the most expensive, is the most secure and scalable of the three
options.

Since, the Business Layer has been moved from the Presentation Layer, it reduces the security
risk.

As usage on the site grows, additional Business Layer can be added and the application can be
cloned across multiple computers.
Each of the three layers can now be optimized for peak operating efficiencies. 
The main functions of:

 The Presentation Layer is network I/O

 The Business Layer is CPU-intensive

 The Data Layer is disk I/O intensive

4. Multi-Tier Architecture

Today the industry appears to be rapidly moving towards multi-tier architecture. Multi-tier
architecture does not prevent the use of the two or three-tiered architecture. 
Depending on the scale of the application and the requirements for access to data, two or three-
tiered architecture is often used for department specific applications.
Java EE architecture is based on the notion of Multi-tier applications. Java EE makes it very easy
to build industrial-strength applications based on two, three or more application layers and
provides all that is required to make this possible.

User Interface Tier: Handles the user's interaction with the application. It could be a web
browser run through a firewall, a heavier desktop application or even a wireless device .

Presentation Tier: Defines what the user interface displays and how a user's requests are
handled depends on what user interfaces are supported, a need may arise to have slightly
different versions of the presentation logic to handle each client appropriately. This is the layer
that provides an interface for the end user to the application data manipulation code spec

Business Tier: This is where the brains of the application reside. It contains stuffs such the
business rules, business data manipulation and so on. For example: If a Payroll system is created
and a need arises to ensure that no employee is paid a wage below a pre-specified minimum
wage, then this logic is placed in the business layer. This layer does not know anything about
HTML nor does it output it. It does not even care about Databases/tables or SQL. It really should
not have any code to access databases/tables. These tasks are assigned to corresponding layers
either above or below the Business tier

Infrastructure Services: Provides additional functionality which are required by the application
components such as messaging transactional support and so on

Integration Tier / Data Access Tier: Is responsible for providing access to backend resources
including powerful relational databases and external systems. This layer is where generic
methods to interface with the data store are written. This layer contains no data business rules or
data manipulation or transformation logic. It is merely a reusable interface to a database engine
and through the engine business data stored in related tables

Data Tier: Since this has been deemed the Age of Information and since all information needs to
be stored, the Data tier is an essential part of any commercial application. Developing a system
without a data tier is possible but for most applications the data tier must exist. Basically, the
Data tier could be a DBMS such as SQL Server, M.S. Access, Oracle, MySQL, Plain text files
(binary files) and so on. This layer is only intended to deal with the storage and retrieval of
business data. It does not care about how plans are made on manipulating or delivering this data
to the requester

Enterprise Architecture

Java EE platform is designed to help developers create large-scale multi-tiered salable reliable
and securer network applications. A distributed multi-tier application model can be described as
an enterprise application as these applications are designed to solve the problems encountered by
large enterprises

Enterprise applications are not only useful for:

 Large corporations
 Agencies of an enterprise
 Governments

However, in an increasingly networked world, the benefits application are helpful, even
essential, for:
 Individual developers
 Small organizations

Enterprise architecture is the extension of the concept of multi-tier available technologies


resulting in a custom made platform that can run across hardware and software frameworks
found across an enterprise, often spanning geographical boundaries,

Application logic is divided into components according to functions and the various application
components put together make up the enterprise application. These components are physically
installed on different computers, at different physical locations, depending on the tier in the
multi-tiered environment to which the application component belongs. All components work
together in harmony across the enterprise.

Enterprise architecture shown in diagram is divided into the following tiers:

1. Client Tier Services run on the Client Machine

2. Web Tier Services run on the Java EE Server

3. Business Tier Services run on the Java EE Server

4. Enterprise Information System (EIS) Tier Software run on the Database Server
Machine
The Client Tier

The Client Tier consists of a client program that makes requests to the Web Tier.

The client can be:


1. A Web client (Dynamic HTML Pages)
2. An Application Client

Web Client
A web client consists of:
 Dynamic web pages containing various types of markup language such as HTML, XML
and so on, which are generated by web components running in the web tier
 A web browser, which renders the pages received from the server

Web clients usually do not:


 Query databases
 Execute complex business rules
 Connect to legacy applications

In fact, such heavyweight operations are off-loaded to enterprise beans executing on the Java EE
server, where they can leverage the security, speed, services and reliability of Java EE server-
side technologies.

1. Application Client

An application client runs on a client machine and provides a way for users to handle tasks that
require a richer user interface than cannot be provided by a markup language.

It typically has a Graphical User Interface (GUI) created from Swing or Abstract Window
Toolkit (AWT) API, but a command-line interface is certainly possible.

Application clients directly access enterprise beans running in the business tier. An application
client can open an HTTP connection to establish communication with a Servlet running in the
web tier. Application clients written in languages other than Java can interact with Java EE
servers, enabling the Java EE platform to interoperate with legacy systems, clients and non-Java
languages.

2. The Web Tier

The Web Tier consists of components that handle the interaction between clients and the
business tier.
The Web Tier usually performs the following tasks:
 Dynamically generate content in various formats for the client
 Collect input from the client and return appropriate results from the components in the
Business Tier
 Control the flow of screens or pages on the client
 Maintain the state of data for a user's session
 Perform some basic logic and hold some data temporarily in JavaBeans components 

The following Java EE technologies are used in the Web Tier:

Servlets: Are Java programming language classes that dynamically process requests and
constructs responses

JavaServer Pages [SP]: Are text-based documents that execute as Servlets but allow a more
natural approach to creating static content
JavaServer Faces [JSF]: A user-interface component framework for Web applications that
allows including:
 UI components such as fields and buttons on a page
 Convert and validate UI component data 
 Save UI component data to server-side data stores
 Maintain component state 

JavaServer Faces Facelets: Are a type of JavaServer Faces applications that use XHTML pages
rather than JSP pages

Expression Language: A set of standard tags used in JSP and Facelets pages to refer to Java EE
components

JavaServer Pages Standard Tag Library [JSTL]: A tag library that encapsulates core
functionality common to JSP pages

JavaBeans Components: Are objects that act as temporary data stores for the pages of an
application
The Business Tier

In a well-designed enterprise application, the core functionality often exists in the Business Tier.
The Business Tier consists of components that provide the business logic for an application

Business logic is code that provides functionality to a particular business domain such as
banking, retail , finance or an e-commerce site. In Java EE, the business logic is handled by
Enterprise Beans.

An enterprise bean:
 Receives data from the client program
 Processes it, if necessary
 Sends it to the Enterprise Information System Tier for storage 
 Retrieves data from storage
 Processes it, if necessary
 Sends it back to the client program

The following Java EE technologies are used in the business tier:


 Enterprise JavaBeans [EJB]
 Java Persistence API (JPA]: Standard API for Object-Relational Mapping [ORM]. With
its Java Persistence Query Language [JPQL), objects stored in the underlying database
can be queried

The Enterprise Information System (EIS) Tier

The Enterprise Information Systems (EIS) tier consists of:


 Database servers
 Enterprise resource planning systems
 Mainframe transaction processing
 Other legacy information systems

These resources typically are located on a separate machine than the Java EE server and are
accessed by components on the Business Tier.

For example, Java EE application components might need access to enterprise information
systems for database connectivity.

The following Java EE technologies are used in the EIS tier:


 Java DataBase Connectivity [JDBC)
 Java Persistence API (JPA): Standard API for Object-Relational Mapping (ORM).
With its Java Persistence Query Language [JPQL), objects stored in the underlying
database can be queried
 Java EE Connector Architecture
 Java Transaction API [JTA]: Provides an interface between the transaction manager
and a resource manager at the Service Provider Interface (SPI) level

Java EE Server
Java EE Server is a server application that implements the Java EE platform APIs and provides
the standard Java EE services.

Java EE servers are sometimes called Application Servers because they allow serving application
data to clients, much as Web Servers serve web pages to Web Browsers.

Java EE servers host several application component types that correspond to the tiers in a multi-
tiered application. The Java EE server provides services to these components in the form of a
Container
During the deployment process, installation of Java EE application components takes place in the
Java EE Containers on the Java EE Server. Java EE Server is used as the runtime portion for the
execution of an application, which contains the EJB and Web containers.
Java EE Containers

Database

Writing multi-tiered applications that run on thin clients is quite time consuming, because a host
of issues, taken for granted on thick clients have to be coded for. These issues would be
transaction and state management, multithreading, resource pooling and so on. Java architecture
changes this, making Java EE applications easy to write, because business logic is organized into
reusable components.

For every component type, Java EE server provides a container that takes care of these
application services. Since application developers need not develop these services themselves
they are free to concentrate on solving application to business process mapping issues.

Containers are like interfaces connecting them with the low-level platform specific component
that is first assembled into Java EE Module and deployed into its container. Then only the
component can be executed.

A Java EE runtime container is built to automatically provide services such as security and
transaction management to appropriate code spec that is run within them.

Assembling an application requires the crafting of a business logic component that is run within
a container and then specifying container settings for each such component and for the overall
Java EE application itself. These settings customize the underlying support provided by the Java
EE server bound to security, transaction management, Java Naming and Directory lookups,
remote connectivity and so on.
Java EE application components use the protocols and methods of the container to access other
application components and services provided by the Java EE server. The Java EE application
server provides an application client container, an applet container, a web container and an EJB
container.

The following are the services provided by container to a component:

 Allows configuring a web component or enterprise bean so that only authorized users can
access the system resources
 Allows specifying relationships among methods that make up a single transaction so that
all methods in one transaction are treated as a single unit
 Provides a unified interface to multiple naming and directory services in the enterprise so
that application components can access these services
 Manage low-level communications between clients and enterprise beans. After an
enterprise bean is created, a client invokes methods on it as if it were in the same virtual
machine

The container also manages non-configurable services such as enterprise bean and Servlet
lifecycles, database connection resource pooling, data persistence and access to the Java EE
platform APIs.

Container Types

The deployment process installs Java EE application components in the Java EE containers 

Enterprise JavaBeans [EJB] Container


Java EE server components that are coded to hold business logiç are called Enterprise JavaBeans
(EJB) . The Java EE server's EJB container provides local and remote access to EJB's.

EJB container is responsible for spawning the EJB on demand, binding the EJB to an appropriate
naming service so that other applications can find and use the EJB. This approach ensures that
only authorized clients have access to the EJB's methods. Additionally, the EJB container takes
care of such things as persistent storage, EJB state caching as well as activating and passivating
the bean on demand.

EJB container is responsible for managing the execution of the enterprise beans containing the
business logic tier of the Java EE application.

Enterprise JavaBean Container:

 Creates new instances of EJBs


 Manages their life cycle
 Provides services such as:
 Transaction
 Security
 Concurrency
 Distribution 
 Naming service 
 The possibility to be invoked asynchronously

Web Container

A Java EE container that hosts web applications is a Web Container.Web container provides the
underlying services for managing and executing web components. A web container extends a
Java enabled Web server's functionality by providing developers the environment to run Servlets,
JSPs, JSFs, JSTLs, Listeners, Filters and so on.

It is responsible for instantiating, initializing and invoking Servlets and supporting the HTTP and
HTTPS protocols. It is the container used to feed web pages to client browsers.

Application Client Container

Application Client Container provides client components. Application clients services required
for the execution of application and their container run on the client,

Application client container includes:


 A set of:
 Java classes
 Libraries
 Other files required to bring injection
 Security management
 Naming service to Java SE applications

Applet Container

Applet Container is provided by the majority of the Web browsers for the execution of applets.

When applets are developed, the visual aspect of the application is given more priority while the
applet container gives a secure environment.

The applet container uses a sandbox security model where code executed in the sandbox is not
allowed to play outside the sandbox i.e. the container prevents any code downloaded to the local
computer from accessing local system resources such as processes or files.

Servlet
The Need For Dynamic Content

In the earlier days, web pages were static i.e a user requests a resource (such as a web page, an
image, a video and so on) and the server returns it. However, with the growth of in the earlier
days, web pages were static i.e. a user requests a resource (such as a web page, commercial
activities on the Web and the rapid spread and adoption of the World Wide Web as a network
without geographical boundaries, companies wanted to deliver dynamic to their customers such
as:
 Displaying bank account details
 Performing bank transactions
 Booking tickets
 Weather reports
 News headlines

Common Gateway Interface [CGI]

And during those days, the only way dynamic data could be rendered to the Web was using
Common Gateway Interface (CGI). CGI programs provide a relatively simple way to create Web
applications that accepts user input, queries a database and returns relevant results back to the
Web browser.

Being the most common of the web technologies, almost every leading Web server in existence
today provides support for CGI programs. A CGI program can be written in many languages
such as C, C++, VB Script, TCL, REXX, Python, Icon, AppleScript, although the most popular
language for CGI programming is PERL.

Disadvantages In CGI
 The biggest disadvantage of CGI programming is lack of scalability and reduced speed.
Each time a request is received by the Web server, an entirely new process thread is
created
 It was platform dependent
 A process thread consumes a lot of server side resources especially in multi-user situation
 Difficult for beginners to program modules in this environment
 Sharing resources such as database connections between scripts or multiple calls to the
same script was not available, leading to repeated execution of expensive operations

Alternatives To CGI
Several alternatives (proprietary APIs) of CGI came into picture.
 FastCGI a mod_perl
 Common Gateway Interface (CGI]
 NSAPI
 ISAPI
 Java Servlets
Most of these had relatively better performance and scalability support. However, it was the Java
Servlets Technology which actually replaced CGI almost entirely.

Sun introduced Servlets la highly efficient CGI program written in Java) as a way to have thin,
dynamic web clients. Servlet was introduced as Java's solution to the issues of CGI and other
proprietary APIs.

Java Servlet Technology

A lava Servlet is a server-side program that services HTTP requests and returns the results as
HTTP responses. A good analogy for a Servlet is a non-visual applet that runs on a Web server.
It has a lifecycle similar to that of an applet and runs inside a JVM at the Web server.

A Servlet:
 Is a module written using Java that runs in a server application (hence the name Servlets,
similar to Applets on the client side) to answer client requests 
 Is most commonly used with HTTP and the word Servlet is often used in the meaning of
HTTP Servlet
 Is supported by virtually all Web servers and Application Servers 
 Solves the performance problem by executing all requests as threads in one process 
 Can be easily ported to other platforms that support Java, as it runs inside a JVM
 Can easily share resources

When a user issues a request for a URL that corresponds to a Java Servlet, the server hands the
request off to the Servlet for processing. The Servlet dynamically produces a response to the
request, typically an HTML Web page and sends it back to the requesting Web browser.

Java Servlets are efficient, due to an intuitive and automated threading model in which each
request is handled by a new lightweight thread.
Servlets are also platform (i.e. hardware) independent, they run using a set of standard interfaces
(that make up the Servlet engine) and a JVM. It is the JVM that is built to run on a specific
hardware platform.

Thus if a JVM exists for a specific hardware platform any Servlet crafted and validated on any
other hardware platform will run successfully.

Java Servlets provide an object-oriented and extensible middle tier for Web Server based
applications. Servlets can access all of the enterprise Java APIs such as INDI, JDBC, RMI and
Enterprise JavaBeans and so on.

Servlets And The Web Server


Servlets, written in Java, dynamically extend the functionality of any Java enabled Web server.

Web servers generally cannot talk to databases. Hence, a Web server alone cannot dynamically
create web page content using data held in a database table. Even if there is a a large amount of
legacy data in a database table, this information cannot be made accessible to public through the
Web server, Internet and Browser combination.

This is where Servlets, [i.e. basically Java .class files] help extend the functionality of a Web
server. Web servers use the Servlet's ability to access a database table, extract table data and
convert this data into a format acceptable to a Web server for delivery to a client's browser
through the Internet.

Servlet Clients
Even though Servlets are written in Java, their clients may not necessarily be written in Java.
Servlet clients [i.e. an application that consumes the output of a Servlet) can be written in any
desired language. This simply means that Servlets are used in the middle tiers of distributed
application systems. Servlets can in turn be clients to other services, which are written in some
other language.

Servlet Container
A Servlet Container (i.e. the Servlet Engine) provides the runtime environment in which a
Servlet executes. The Servlet engine manages the lifecycle of Servlets from the moment they are
spawned until they are destroyed. The Servlet engine exposes an API based on the version of the
Servlet specification that it implements.
Servlets are supported by several Web servers such as Apache, Netscape, Microsoft IIS and
others.

Since Servlets run within a Web server's namespace they do not display a graphical interface to a
user. A Servlet's work is done behind the scene i.e. working with a Web server. Only the results
of a Servlet's processing (table data converted to suitably formatted HTML) are returned to a
client's browser.

Why Servlets?
 Are loaded into memory once and run from memory thereafter 
 Are a powerful object-oriented abstraction of HTTP and platforms 
 Are tightly integrated with the Web server 
 Run within the secure and reliable scope of a Java Virtual Machine [JVM] 
 Provide direct Database Access using native and ODBC based DB drivers 
 Being on the Server-side provides code protection 
 Are supported by several Web servers
 Are spawned as a thread, not as a process
 Are portable across multiple Web servers
 Are simple to design and implement
 Service client requests efficiently
 Obey the rules of a standard Servlet API
 Return vanilla HTML to the requesting Browser
 Are robust, scalable, secure CGI Replacement

What Can Servlets Do?


A Servlet is a small, self-contained, portion of code that is executed at the Web Server in
response to an HTTP request from a client's browser. Servlets can do the following:
 A Servlet can process and/or store data submitted by an HTML form
 A Servlet can provide dynamic content, for example, return the results of a database
query to the client
 A Servlet can manage state information on top of the stateless HTTP, for example, for an
online shopping cart system which manages shopping carts for many concurrent
customers and maps every request to the right customer 0
 Servlets can be used as a plug-in, that features a search engine or semi-customized
applications such as web-based banking or inventory systems
 A Servlet can handle multiple requests concurrently and these requests can be
synchronized to support systems allowing collaboration between people
 Servlets can forward requests to other Servers and Servlets. This allows them to be used
to balance load among several servers that mirror the same content
 Servlets can maintain and track sessions (either by URL rewriting or cookies). Servlets
clean up the session precisely when a session is terminated, either by logging off or by a
time-out
 Servlets can pass data between themselves
 Servlets can be used to serve as the HTTP speaking middle tier between any kind of thin
client and large enterprise services being made available via EJB's

Steps to create a servlet example

There are given 6 steps to create a servlet example. These steps are required
for all the servers.

The servlet example can be created by three ways:

1. By implementing Servlet interface,


2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http


request specific method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are
as follows:

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet

DemoServlet.java

1. import javax.servlet.http.*;  
2. import javax.servlet.*;  
3. import java.io.*;  
4. public class DemoServlet extends HttpServlet{  
5. public void doGet(HttpServletRequest req,HttpServletResponse res)  
6. throws ServletException,IOException  
7. {  
8. res.setContentType("text/html");//setting the content type  
9. PrintWriter pw=res.getWriter();//get the stream to write the data  
10.   
11. //writing html in the stream  
12. pw.println("<html><body>");  
13. pw.println("Welcome to servlet");  
14. pw.println("</body></html>");  
15.   
16. pw.close();//closing the stream  
17. }}  

web.xml file
1. <web-app>  
2.   
3. <servlet>  
4. <servlet-name>sonoojaiswal</servlet-name>  
5. <servlet-class>DemoServlet</servlet-class>  
6. </servlet>  
7.   
8. <servlet-mapping>  
9. <servlet-name>sonoojaiswal</servlet-name>  
10. <url-pattern>/welcome</url-pattern>  
11. </servlet-mapping>  
12.   
13. </web-app>  

Servlet API and Lifecycle: Java Servlet API, The Servlet Skeleton, The Servlet Life Cycle, A
Simple Welcome Servlet
Servlet API And Lifecycle

Now that the concept of Servlet is in place, let's move one step further and understand the basic
classes and interfaces that Java provides to deal with Servlets,

Java provides a Servlet Application Programming Interface (API) which is a class library (basic
classes and interfaces] for implementing Servlets

Java API forms a standard interface for developing Web applications, regardless of the
underlying operating system. Without the implementation of Java API it is not possible to
develop dynamic applications. This Java API consists of a set of important interfaces that can be
implemented in different areas so that developers can conveniently build Java-powered
applications.

Servlets can access the entire family of Java APIs. The Java Servlet API is the class library using
which requests can be processed and responses can be constructed dynamically. The API thus
helps define the expected interactions of a Web container and a Servlet.
The following are the basic classes and interfaces used for implementing the Servlet.

javax.servlet Package
javax.servlet package is the core of the Servlet API.

javax.servlet package includes the basic Servlet interface, which all Servlets must implement in
one form or another and an abstract GenericServlet class for developing basic Servlets.

This package also includes classes for:

 Communicating with the host server and client:


 ServletRequest 
 ServletResponse
 Communicating with the client: 
 ServletInputStream 
 ServletOutputStream

Servlet Interface
Servlet interface is a collection of empty method signatures,
A Servlet must directly or indirectly [by subclassing the GenericServlet or HttpServlet class}
implement the Servlet interface.

This interface holds method signatures that bring the following basic Servlet functionalities: 
 Initializing a Servlet
 Handling a client request
 Destroying a Servlet

The following are the methods available in this interface: Methods Description

Methods Description

init() Is used for initializing the Servlet parameters provided by the ServletConfig
object. 
Is called only once when the Servlet is first loaded. 
It is commonly used to initialize resources to be used by a Servlet when
requests are received. 
For example, database or network connections, file initialization and other
environmental settings. 
None of the Servlets methods can be called unless the Servlet is initialized
using init().

destroy() destroy() is also called only once immediately before the Servlet is
unloaded.
Is used to clear all retained resources such as memory, database connection,
threads, file handles and so on and also makes sure that any persistent state
is synchronized with the Servlet's current state in memory.

service() Is the actual heart of the HTTP Request-Response model.


Is called to handle a single client request.
A Servlet receives request information through the ServletRequest object
and sends data back to the client through the ServletResponse object.

getServletConfig( Provides the ServletConfig object for initializing the Servlet's parameters.
)

getServletInfo() Provides the Servlet metadata such as author, Servlet version and other
copyright information.

ServletContext Interface
All Servlets belong to one Servlet context. ServletContext can only be called at context
initialization time.

The ServletContext interface provides a set of methods which allow communicating with the
server such as:
 Finding path information
 Accessing other Servlets running on the server
 Writing to the server log file

ServletContext allows applications to load Servlets and Filters at runtime that are needed.

The following are the methods available in this interface:

Methods Description

getAttribute() Returns the value of the named server attribute as an Object.

getAttributeNames() Returns an Enumeration containing the attribute names


available within the current ServletContext.

getContext() Returns a ServletContext object that corresponds to a specified


URL on the server. 

getContextPath()  Returns the context path of the web application.

getMajorVersion() Returns the major version of the Servlet API that this Servlet
container supports. This method returns 3 if the
implementations comply with Version 3.0.

getMinor Version()  Returns the minor version of the Servlet API that this Servlet
container supports. This method return 0 if the implementations
comply with Version 3.0. 

getEffectiveMajorVersion() Returns the major version of Servlet specification that the


application represented by this ServletContext is based on. 

getEffective MinorVersion() Returns the minor version of Servlet specification that the
application represented by this ServletContext is based on. 

getMimeType() Returns the MIME type of the given file. Common MIME |
types are text/html and image/gif.

getResourcePaths() Returns a directory-like listing of all the paths to resources


within the web application whose longest sub-path matches the
supplied path argument.

getRealPath() Returns the real file system path of any given virtual path. 

getServletInfo() Returns the real file system path of any given virtual path.
Returns the name and version of the servlet container on which
the servlet is running

getServletContextName() Returns the name of the current web application corresponding


to the current ServletContext as specified in the deployment
descriptor for this web application by the <display-name>
element.

getAttribute() Returns the servlet container attribute with the given name or
null if there is no attribute by that name.

getAttributeNames() Returns an Enumeration containing the attribute names


available within this ServletContext. 

log() Writes an exception's stack trace and a given message to a


Servlet log, usually an event log file. 

addServlet() Adds the Servlet with the given name and class type or class
name to the current ServletContext.

addFilter() Adds the filter with the given name and class type or class
name to the current ServletContext. 

createServlet() Instantiates the given Servlet class and performs any required
resource injection into the new Servlet instance before returning
it.

createFilter()  Instantiates the given Filter class and performs any required
resource injection into the new Filter instance before returning
it. 

getInitParameter() Returns a String containing the value of the named context-


wide initialization parameter.

getInitParameterNames() Returns the names of the context's initialization parameters as


an Enumeration of String objects. 

getNamed Dispatcher()  Returns a RequestDispatcher object that acts as a wrapper for


the named servlet.

getRequestDispatcher() Returns a RequestDispatcher object that acts as a wrapper for


the resource located at the given path. 

getResource()  Returns a URL to the resource that is mapped to the given


path. 

getResourceAsStream()  Returns the resource located at the named path as an


InputStream object. 
setAttribute() Binds an object to a given attribute name in the current
ServletContext. 

setinitParameter() Sets the context initialization parameter with the given name
and value on the current ServletContext.

setSession Tracking Modes() Sets the session tracking modes that are to become effective for
the current ServletContext 

removeAttribute() Removes the attribute with the given name from the current
ServletContext.

getSession Tracking Modes() Retrieves the session tracking modes that are in effect for the
current ServletContext

getDefaultSessionTracking Retrieves the session tracking modes that are supported by


Modes() default for the current ServletContext.

getEffectiveSessionTracking Retrieves the session tracking modes that are effective for this
Modes() ServletContext

getSessionCookieConfig0 Retrieves the SessionCookieConfig object through which


various properties of the session tracking cookies created on
behalf of the current ServletContext may be configured.

getFilter Registrations() Retrieves an immutable Map of the Filter Registration objects


[keyed by filter name) corresponding to all filters registered
with the current ServletContext.

getFilterRegistration()  Retrieves the Filter Registration corresponding to the filter with


the given filter name. 

getServletRegistrations() Retrieves an immutable Map of the ServletRegistration objects


[keyed by servlet name] corresponding to all servlets registered
with the current ServletContext.

getServletRegistration()  Retrieves the ServletRegistration corresponding to the servlet


with the given servlet name.

addListener()  Adds the listener with the given class name or class type to this
ServletContext.

createListener() Instantiates the given EventListener class.

getjspConfigDescriptor()  Retrieves <jsp-config> related configuration that was


aggregated from the deployment descriptor files of the web
application represented by this ServletContext.
getClassLoader() Retrieves the class loader of the web application represented by
this ServletContext. 

declareRoles()  Declares role names that are tested using isUserInRole. 

getVirtualServerName()  Returns the configuration name of the logical host on which the
ServletContext is deployed.

ServletConfig Interface

ServletConfig help Servers pass initialization and context information to Servlets such as:
 A series of initialization parameters 
 A ServletContext object, which provides information about the server environment

Methods Description

getServletName() Returns the name of this servlet instance.

getInitParameter()  Returns the value of the named Servlet initialization parameter

getInitParameterNames( Returns all the Servlet's initialization parameter names as an


) Enumeration of String objects. 

getServletContext() Returns a reference to the ServletContext in which the caller is


executing 

ServletRequest And ServletResponse Interfaces

When a Servlet accepts a call from a client, it receives two objects, one is a ServletRequest and
the other is a ServletResponse.

ServletRequest interface encapsulates the communication from the client to the server, while
ServletResponse interface encapsulates the communication from the Servlet back to the client.

ServletRequest interface allows the Servlet to access information such as:


1. Names of the parameters passed by the client
2. The protocol [scheme] such as the HTTP POST and PUT methods being used by the
client
3. The names of the remote host that made the request
4. The server that received it
5. An input stream for reading binary data from the request body

Subclasses of ServletRequest allow the Servlet to retrieve more protocol-specific data. For
example, HttpServletRequest contains methods for accessing HTTP-specific header information.

The following are the commonly used methods available in ServletRequest interface:

Method  Description

getAttribute() Returns the value of the named attribute as an Object

getAttributeNames()  Returns an Enumeration containing the names of the attributes to this


request 

getContentLengthLong( Returns the length, in bytes, of the request body and made available
) by the input stream. 

getParameter()  Returns the value of a request parameter as a String

getParameterNames() Returns an Enumeration of String objects containing the names of the


parameters to this request.

getParameterValues() Returns an array of String objects containing all of the values the
given request parameter has

getRequestDispatcher() Returns a RequestDispatcher object that acts as a wrapper for the


resource located at the given path.

getServerName() Returns the host name of the server to which the request was sent. 

getServerPort() Returns the port number to which the request was sent.

removeAttribute() Removes the attribute from this request.

setAttribute()  Stores an attribute in this request. 

getServletContext() Retrieves the servlet context to which this servlet was last dispatched.

startAsync() Puts this request into asynchronous mode and initializes its
AsyncContext with the original (unwrapped) ServletRequest and
ServletResponse objects. 

isAsyncStarted() Checks if this request has been put into asynchronous mode.

isAsyncSupported()  Checks if this request supports asynchronous mode. 


getAsyncContext() Gets the AsyncContext that was created or reinitialized by the most
recent invocation of startAsync() on this request.

getDispatcherType() Retrieves the dispatcher type of this request.

ServletResponse interface provides methods to the Servlet for replying to the client.

ServletResponse interface allows Servlet:


 To set the content length and mime type of the reply a Provides an output stream and a
Writer
 Through ServletResponse interface, the Servlet can send the reply data.

Subclasses of ServletResponse provide the Servlet with more protocol-specific capabilities. For
example, HttpServletResponse contains methods that allow the Servlet to manipulate HTTP-
specific header information.

The following are the commonly used methods available in the ServletResponse interface:
Methods Description

Method Description

getLocale()  Returns the locale assigned to the response.

gerOutputStream() Returns a ServletOutputStream suitable for writing, binary data in the


response

getWriter() Returns a Print Writer object that can send character text to the
client. 

SetContentLengthLong( Sets the length of the content body in the response


)

reset() Clears any data that exists in the buffer as well as the status code and
headers.

setLocale() Sets the locale of the response, setting the headers (including the
Content-Type's charset) as appropriate. 

Generic Servlet Class

javax.Servlet.GenericServlet class provides the basic implementation of the Servlet interface. It


also implements ServletConfig interface.
GenericServlet may be directly extended by a Servlet, although it's more common to extend a
protocol-specific subclass such as HttpServlet.

GenericServlet makes writing Servlets easier.

ServletInputStream And ServletOutputStream Classes

ServletInputStream and ServletOutputStream classes are abstract classes that a Servlet


container implements.

ServletInputStream class provides an input stream for reading binary data from a client request.

The ServletInputStream class is returned by getInputStream() of ServletRequest.

A Servlet that filters binary output from other sources generally receives its input through this
stream.

The following is the method available in the ServletInputStream

Methods Description

readLine() Reads the input stream one line at a time.

isFinished() Returns true when all the data from the stream has been read.

isReady()  Returns true if data can be read without blocking.

setReadListener( Instructs ServletInputStream to invoke the provided ReadListener when it is


) possible to read.

ServletOutputStream class provides an output stream for sending binary data back to a client.

A servlet obtains ServletOutputStream object from getOutputStream() of ServletResponse.

The following are the commonly used methods available in the ServletOutputStream class:

Methods Description
print() Writes a character to the client, with no carriage return line feed at the end.

println()  Writes a carriage return line feed to the client.

isReady() Used to determine if data can be written without blocking.

setWriteListener()  Instructs ServletOutputStream to invoke the provided WriteListener when it


is possible to write.

Deployment Descriptor
Servlet uses the deployment descriptor (web.xml file) for deploying your application into a web
server. Servlet API 3.0 has introduced a new package called javax.servlet.annotation. It
provides annotation types which can be used for annotating a servlet class. If you use
annotation, then the deployment descriptor (web.xml) is not required. But you should use
tomcat7 or any later version of tomcat.
Annotations can replace equivalent XML configuration in the web deployment descriptor file
(web.xml) such as servlet declaration and servlet mapping. Servlet containers will process the
annotated classes at deployment time.
The annotation types introduced in Servlet 3.0 are −

Sr.No Annotation & Description


.

1 @WebServlet
To declare a servlet.

@WebInitParam
2
To specify an initialization parameter.

@WebFilter
3
To declare a servlet filter.

@WebListener
4
To declare a WebListener
@HandlesTypes
5
To declare the class types that a ServletContainerInitializer can
handle.

@HttpConstraint

6 This annotation is used within the ServletSecurity annotation to


represent the security constraints to be applied to all HTTP protocol
methods for which a corresponding HttpMethodConstraint element
does NOT occur within the ServletSecurity annotation.

@HttpMethodConstraint
7
This annotation is used within the ServletSecurity annotation to
represent security constraints on specific HTTP protocol messages.

@MultipartConfig
8 Annotation that may be specified on a Servlet class, indicating that
instances of the Servlet expect requests that conform to the
multipart/form-data MIME type.

@ServletSecurity
9 This annotation is used on a Servlet implementation class to specify
security constraints to be enforced by a Servlet container on HTTP
protocol messages.

Here we have discussed some of the Annotations in detail.


@WebServlet

The @WebServlet is used to declare the configuration of a Servlet with a container. The
following table contains the list of attributes used for WebServlet annotation.

Sr.No. Attribute & Description

1 String name
Name of the Servlet
String[] value
2
Array of URL patterns

String[] urlPatterns
3
Array of URL patterns to which this Filter applies

Int loadOnStartup
4
The integer value gives you the startup ordering hint

WebInitParam[] initParams
5
Array of initialization parameters for this Servlet

Boolean asyncSupported
6
Asynchronous operation supported by this Servlet

String smallIcon
7
Small icon for this Servlet, if present

String largeIcon
8
Large icon for this Servlet, if present

String description
9
Description of this Servlet, if present

String displayName
10
Display name of this Servlet, if present

At least one URL pattern MUST be declared in either the value or urlPattern attribute of the


annotation, but not both.
The value attribute is recommended for use when the URL pattern is the only attribute being set,
otherwise the urlPattern attribute should be used.
@WebInitParam
The @WebInitParam annotation is used for specifying an initialization parameter for a Servlet
or a Filter. It is used within a WebFilter or WebSevlet annotations. The following table contains
the list of attributes used for WebInitParam annotation.

Sr.No. Attribute & Description

1 String name
Name of the initialization parameter

String value
2
Value of the initialization parameter

String description
3
Description of the initialization parameter
@Webfilter
This is the annotation used to declare a servlet filter. It is processed by the container at
deployment time, and the corresponding filter applied to the specified URL patterns, servlets,
and dispatcher types.
The @WebFilter annotation defines a filter in a web application. This annotation is specified
on a class and contains metadata about the filter being declared. The annotated filter must
specify at least one URL pattern. The following table lists the attributes used for WebFilter
annotation.

Sr.No. Attribute & Description

1 String filterName
Name of the filter

String[] urlPatterns
2
Provides array of values or urlPatterns to which the filter applies

DispatcherType[] dispatcherTypes
3
Specifies the types of dispatcher (Request/Response) to which the filter applies

String[] servletNames
4
Provides an array of servlet names

String displayName
5
Name of the filter

String description
6
Description of the filter

WebInitParam[] initParams
7
Array of initialization parameters for this filter
Boolean asyncSupported
8
Asynchronous operation supported by this filter

String smallIcon
9
Small icon for this filter, if present

String largeIcon
10
Large icon for this filter, if present

JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. 

We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.

o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
o ResultSetMetaData interface
o DatabaseMetaData interface
o RowSet interface

Why Should We Use JDBC

Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the following
activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

JDBC Architecture

The JDBC API supports both two-tier and three-tier processing models for database access but
in general, JDBC Architecture consists of two layers −
 JDBC API − This provides the application-to-JDBC Manager connection.
 JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −

Accessing Database using JDBC

There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:

o Register the Driver class


o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.

Syntax of forName() method


1. public static void forName(String className)throws ClassNotFoundException  

Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

1. Class.forName("oracle.jdbc.driver.OracleDriver");  

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection
with the database.
Syntax of getConnection() method
1. 1) public static Connection getConnection(String url)throws SQLException  
2. 2) public static Connection getConnection(String url,String name,String password)  
3. throws SQLException  
Example to establish connection with the Oracle database
1. Connection con=DriverManager.getConnection(  
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");  

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement.
The object of statement is responsible to execute queries with the database.

Syntax of createStatement() method


1. public Statement createStatement()throws SQLException  
Example to create the statement object
1. Statement stmt=con.createStatement();  

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the
records of a table.

Syntax of executeQuery() method


1. public ResultSet executeQuery(String sql)throws SQLException  
Example to execute query
1. ResultSet rs=stmt.executeQuery("select * from emp");  
2.   
3. while(rs.next()){  
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));  
5. }  

5) Close the connection object


By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close the
connection.

Syntax of close() method


1. public void close()throws SQLException  
Example to close connection
1. con.close();  

You might also like