USIT506-Enterprise-Java-munotes

Page 1

1 UNIT I
1
UNDERSTANDING JAVA EE
Unit Structure
1.1 Objectives
1.2 Introduction to Java EE
1.3 Basic Concepts related Java EE
1.3.1 Specification of Java EE
1.3.2 Wha t is an Enterprise Application
1.3.3 What is java enterprise edition
1.3.3.1 Business [ Model]
1.3.3.2 Présentation [View]
1.3.3.3 Persistence layers(Controllers)
1.3.4 Java EE Technologies
1.3.5 Java EE evolution
1.3.6 Glassfish Server
1.4 Questions
1.5 Summary
1.6 Reference for further reading
1.1 OBJECTIVES 1) Java EE Provides More Flex ible Technology.
2) Java EE is a collection of API where students/professionals are able to
design server side applications.
3) Students/professionals are able to originally design and develop
applications in a thin -client -tiered environment.
4) Java EE application s are hosted on application servers ( WebSphere,
GlassFish, WildFly, Apache Tomcat etc….)
5) When we design & develop Java EE applications to use popular
design patterns [ MVC].
6) Java EE support for Enhanced Extensibility.
7) Java EE provides a powerful API for Strong and Dynamic Web
Programming.

munotes.in

Page 2


Enterprise Java
2 1.2 INTRODUCTION TO JAVA EE The Java EE stands for Java Enterprise Edition, which was earlier known
as J2EE and is currently known as Jakarta EE in JDK latest version. The
Java EE provides a platform for Student/profe ssionals with enterprise
features including - distributed computing and web services. Java EE types
of applications are usually run on microservers or application servers.
Areas where Java EE is used are e -commerce, accounting, banking
information systems.
1.3 BASIC CONCEPTS RELATED TO JAVA EE 1.3.1 Specification of Java EE:
Java EE has various specifications which are useful in Designing &
Developing applications and web pages, reading and writing from the
database in various transactional ways and also managing distributed
queues in network communication. Java EE API such as Enterprise
JavaBeans, connectors, Servlets, Java Server Pages and various web
services.
1.3.2 What is an Enterprise Application? :
In Java EE we can design the Enterprise /Business/C ommercial level
Applications. Java EA is a large software system platform designed to
operate in a corporate / business or government level environment. Java
EE Applications are complex,scalable, component -based, distributed and
mission critical.
Java EA consists of a large number of programs with shared business
applications and organizational modeling utilities designed for
unparalleled functionalities.
Enterprise Application’s software is a critical component of any computer -
based information system. E nterprise level Application software
ultimately enhances their efficiency and productivity through various
levels of functionality in business.
1.3.3 What is java enterprise edition? :
Java EE frameworks provide common design patterns rarely used in
develop ment of Java EE Application, and add into reusable class libraries.
These class libraries are implemented to access the database for various
processing ways - security, transaction processing, screen layout, data
validation,object construction, caching, a nd other
development/Programming related tasks so that Java EE developers can
focus on the purely business logic . munotes.in

Page 3


Understanding Java EE
3

1.3.3 A Figure shows Java EE Architecture.
Above Figure indicate flow of java EE applications first layer as an client
where they can be s end & receive responses from server side(Java
Enterprise Edition Programs) ,second layer is an middle Tier
[Combination of java’s web enabled API’s] where it can be acting as a
Controller of client & Database .
Java Enterprise Edition (Java EE) technology provides services to
enterprise applications using a multi -layer architecture. Java EE
applications/projects are web -enabled and Java based, which means they
may be written once and deployed on any container supporting the
powerful execution in Java EE en vironment.
Following are The three most common Java EE design patterns also
known as MVC model focus on:
1) business(Model)
2) presentation(View)
3) persistence layers(Controllers).
1.3.3.1 Business [Model]:
Model/Business Logic represents an object or JAVA POJO[purely old
java object] carrying data. It can also have logic to update controllers if its
data changes vary to Action.Model represents the state of the application
i.e. data. Model containing business logic.
1.3.3.2 Presentation [View]:
View represents the visualization of the data and represents on the user
screen that model contains processed data/result oriented. View is an
represents the presentation i.e. UI(User Interface)/front end..
1.3.3.3 Persistence layers [Controllers]:
Controllers are handled on both model and view. It controls the data flow
into the model object and updates the view whenever data
changes/requirements change . It keeps view and model separate. munotes.in

Page 4


Enterprise Java
4 In MVC Controller acts as an interface/Intermediate between View and
Model. Controller Handling all the incoming requests from Model &
View as per request redirect to automatically as per request & response
preference .

1.3.3 A Figure shows Java EE design patterns Communication.

1.3.3 B Figure shows Java EE design patter ns Communication[MVC].
1.3.4 JAVA EE TECHNOLOGIES.
Java EE is actually a collection of various technologies and
API[Application Programming Interface] for the Java EE platform
designed & Developed to support "Enterprise" levels Applications which
can ge nerally be classed as large -scale, Multi -tier , distributed,
transactional and highly -available applications designed to support
mission -critical/handling critical processes in business requirements.
● Following are list of java EE Technologies:
1. JDBC:
JDBC stands for Java Database Connectivity.JDBC is a Java API used to
connect and execute the sql query with their relevant database. JDBC can munotes.in

Page 5


Understanding Java EE
5 handle backend & frontend transactions the JDBC API uses JDBC drivers
to connect with the database/backend to fron t end or java application .

Fig: shows JDBC for Database connectivity with java application.
There are four types of JDBC drivers:
A) JDBC -ODBC Bridge Driver.
B) Native Driver.
C) Network Protocol Driver.
D) Thin Driver.
2. JNDI:
Java Naming and Directory Interface is the name of the interface in the
Java programming language. It is an API( Application Program Interface)
that works with servers for fetching files from a database using naming
conventions. The naming convention(Name of class,interface etc….) can
be a single phrase or a word. It can also be incorporated in a socket to
implement socket programming, using servers transferring data files or flat
files in a project.
JNDI is used in web pages in browsers/clients where there are instances
of many directories/files. JNDI provides users in Java related various
facilities to search objects in Java using the Java coding language.

Fig: shows Architecture of JNDI. munotes.in

Page 6


Enterprise Java
6 3. EJB:
EJB stands for Enterprise Java Bean. It is a specification provided by Sun
Micros ystems/Oracle corporation or IBM to develop robust,secure and
scalable distributed applications using Java EE.
To run the Java EJB applications, you should install an application
server (EJB Container) such as Weblogic,Jboss,Websphere, Glassfish etc.
It performs Following Transaction of EJB application:
1. life cycle management.
2. security.
3. transaction management.
4. object pooling.
● Use of EJB:
1) EJB Application needs Remote Access. In other words, it is distributed.
2) EJB Application needs to be scalable. Java EJB a pplications support
load balancing, clustering and fail -over.
3) EJB Application needs encapsulated business logic. Java EJB
application is separated from presentation and persistent layer.
● Types of Enterprise Java Bean :
There are 3 types of enterprise beans in java.
1) Session Bean :
Session bean contains business logic that can be invoked by local, remote
or web service clients/browsers.
2) Message Driven Bean :
Message Driven Bean also Like Session Bean, it contains the business
logic but it is invoked by pas sing messages/message communication.
3) Entity Bean :
IN Entity Bean It encapsulates the state that can be persisted in the
database. Currently it is known as or it is replaced with JPA (Java
Persistence API).
4) RMI:
The RMI (Remote Method Invocation) is an API that provides a
mechanism to create distributed applications in java. The RMI allows an
object to invoke methods on an object running in another JVM. munotes.in

Page 7


Understanding Java EE
7 The RMI provides remote communication between the applications using
two objects stub and skeleton.
● Understanding stub and skeleton :
In client server communication RMI uses stub and skeleton objects for
communication with the remote object for both objects are accessing
purpose .
Note: A remote object is an object whose method can be invoked from
anothe r JVM.
Let's understand the stub and skeleton objects:
1) stub:
The stub is an object, acts as a gateway for the client side. All the outgoing
requests are routed through it. It resides at the client side and represents
the remote object. When the caller invokes method on the stub object, it
does the following tasks:
1. It implement a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshalls) the parameters to the remote Virtual
Machine (JVM),
3. It waits for the result from the remote JVM .
4. Stub reads (unmarshalls) the return value or exception.
5. Stub finally returns the value to the caller .
2) skeleton:
The skeleton is an instance/object, and acts as an interface for the server
side object. All the incoming requests are routed through sk eleton. When
the skeleton receives the incoming request, it does the following
operations:
1. Skeleton reads the parameter for the remote method.
2. Skeleton invokes the method on the actual remote object as per
communication.
3. Skeleton writes and transmits (marshalls) the result to the caller. munotes.in

Page 8


Enterprise Java
8

Fig: Shows communication of stub & skeleton.
5) JSP:
In Java EE uses JSP technology to create web applications just like
Servlet technology. It can be treated as an enhancement to Servlet because
it provides more f unctionality than servlet such as expression language,
JSTL, etc.
In the JSP page containing HTML tags and JSP tags. The JSP pages are
easier to maintain than Servlet because we can separate the code of
designing and development. It provides some addition al features such as
implicit objects,Expression Language, Custom Tags, etc.
6) Java servlets:
Servlet technology is used to create a web application (Executes/resides on
server side and generates a dynamic web page & response to browser).
Servlet is a tech nology that would be robust and scalable because of the
Java language. Before Servlet, to use one common interface CGI
(Common Gateway Interface) scripting language was common as a server -
side programming language.
● What is a Servlet?
Following are the Se rvlet can be described in many ways
● Servlet is a technology which is used to create and design a dynamic
web application.
● Servlet consists of an API that provides various interfaces and classes.
● Servlet is an interface that must be implemented for creating any
Servlet class.
● Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any requests.
● In java EE Servlet is a web component that is deployed on the server to
create a dynamic web page. munotes.in

Page 9


Understanding Java EE
9

Fig: Using servlet interface implementing client server
communication.
7) XML:
XML (Extensible Markup Language) is a very popular simple text -
based/marked up language that can be used as an interface of
communication between different applications. It is considered as a
standard technique to transport and store data. JAVA provides excellent
support and a rich set of libraries to modify, parse and inquire XML
documents.
8) JMS:
MS (Java Message Service) is an API that provides the facility to create,
send and read messages.JMS is also known as a messaging service. It
provides loosely coupled, reliable and asynchronous communication.
Use of Java Messaging Service :
● In JMS Service messaging is a technique to communicate applications
or software components.
● JMS service is mainly used to send and receive messages from one
application to another.
● Generally, the user sends a message to the application. But, if we want
to send messages from one application to another, we need to use the
JMS API.
● Consider a scenari o, one application A is running in INDIA and
another application B is running in the UK. To send a message from A
application to B, we need to use JMS.
9) Java IDL:
In Java EE IDL stands for (Interface Definition Language) is a
technology for distribute d objects -that is, objects can
communicate/interact on different platforms across a network. Java IDL is
similar to RMI (Remote Method Invocation), But in IDL which supports
distributed objects written entirely in the Java programming language. munotes.in

Page 10


Enterprise Java
10 10) JTS:
In Java The JTS stands for Java Topology Suite (JTS) is an open source
Java API/ library that provides an object model for planar geometry
together with a set of fundamental geometric functions.
JTS is specifically designed to be used as a core component of vector -
based geomatics software such as GIS -Geographical Information Systems.
Now JTS also be used as a general -purpose library providing algorithms in
computational geometry in java applications.
11 ) JTA:
The Java Transaction API (JTA) allows for app lications to perform
distributed transactions, that is, transactions that access and update data on
two or more networked computer resources. The JTA specifies standard
Java interfaces between a transaction manager and the other network
component.
12) Java Mail:
In Java EE Technology JavaMail is an API that is used to compose, write
and read electronic messages i.e (to send & receive emails).
These JavaMail API provides services related to protocol -independent
and platform -independent frameworks for sendi ng and receiving mail
through the network.
The javax.mail and javax.mail.activation packages contain the core classes
of JavaMail API.
13) JAF:
JFA (Java Framework Architecture) is an API included in the Software
Development Kit(SDK) for designing software applications in Indian
languages. It consists of a set of Java components ,Interfaces and
supporting classes which enable the creation of content in Indian
scripts(Language). The scripts supported are Devanagari,Oriya ,
Kannada,Assamese, Bengali, Tamil, Gujarati, Punjabi, Malayalam,Telugu
and English.
1.3.5 Java EE evolution:
Java EE Formerly called as a J2EE, the first version of Java EE platform
was officially released in December 1999 with 10 specifications. Among
these specifications, there were Serv lets and JavaServer Pages (JSP) for
data presentation, Enterprise JavaBeans (EJB) for the management of
persistent data and secure transactions, remote access to business services
through RMI -IIOP protocol (Remote Method Invocation over Internet
Inter -ORB Protocol), and the JMS (Java Message Service) specification,
which was used to send messages.
More effort and many contributions, early versions of Java EE were too
much complex and difficult to implement because JEE provides more munotes.in

Page 11


Understanding Java EE
11 specification than J2EE. This leading to much criticism/complexity of
code and caused the rise of competing frameworks such as Spring
Framework.
1.3.6 Glassfish Server:
GlassFish is an application server/web server started by Sun Microsystems
for Java Enterprise Edition which is now owned & managed by Oracle
corporation. It is a free software that is released under two free software
licenses. The one is a common development and distribution license and
the other is GNU general public license. Sun Microsystems launched the
project on June 6, 2005.
Requirement:
1. JDK must be installed on the system.
2. Windows OS
3. Login as an admin.
Steps to Install Glassfish web server in Eclipse:
1. Open Eclipse.
2. Go to Help > Eclipse Marketplace.
3. Search for GlassFish.
4. Click on Install.
5. Glassfish Tools and oracle. eclipse. tools. glassfish is selected. Click
Confirm.
Steps to configure Glassfish server with eclipse :
Step-1 launch Eclipse IDE. Click Window menu > select Show View sub menu > select Servers.
munotes.in

Page 12


Enterprise Java
12 Or, right click mouse anywhere in the Serve rs page > select New menu >
select Server sub menu.

Step-2: in the New Server page, notice in the middle box which list the
available servers. We are going to download the Glassfish server which is
not in the list. Type the Server’s host name (if neede d). In this case we are
using 'localhost'. Then, click the Download additional server adapters link.
munotes.in

Page 13


Understanding Java EE
13
The Install New Extension wizard will begin, searching available server
adapters which are available from the update servers.

Step-3 from the list of available server adapter, select Glassfish server
and click Next.
munotes.in

Page 14


Enterprise Java
14 The download requirements and dependencies process will begin.

After the download requirement and dependencies process is completed,
click Next.

munotes.in

Page 15


Understanding Java EE
15 Step-4 Accept the license agre ement and click Finish.

Step -5 Click OK for the server adapter download confirmation prompt
window.

The Glassfish download and installation will begin. Click Details for the
details process.
munotes.in

Page 16


Enterprise Java
16 The task can be set to be done at the background by cl icking the Run in
Background button.

Step-6 restart Eclipse in order the new downloaded and installed
Glassfish server take effect.

Step-7 Now, in the New Server page, Glassfish server will be visible in
the list of the available servers that are associated with Eclipse and ready
to be used.
munotes.in

Page 17


Understanding Java EE
17

1.4 SUMMARY We can use the Java EE tools for implementing new features in
applications that are structured around modules with different purposes,
such as web sites, web applications and Enterprise applica tions. When
you use Java Enterprise Edition components, you can create distributed,
secure applications with transactional support.
1.5 QUESTIONS Q.1 Define java EE?
Q.2 Applications of Java EE.
Q.3 Explain Design Pattern [MVC] in Java EE.
Q.4 Explain wh at technologies are used in Java EE.
Q.5 Define Java Enterprise Application. munotes.in

Page 18


Enterprise Java
18 Q.6 Explain Servlet & JSP.
Q.7 Define Web Server?
Q.8 Explain steps to configure glassfish web server in eclipse.
Q.9 Define JavaMail API.
Q.10 Explain Architecture of JEE.
1.6 RE FERENCE FOR FURTHER READING 1. Java EE 6 Enterprise Architect Exam Guide ,Author: PaulAllen ,
Publisher: McGraw -Hill
2. The Complete Reference -Java Enterprise Edition (Black Book)
,Author:Herbert schildt.
3. Java EE 7 The Big Picture by - Dr.Danny Co ward Publisher - Oracle
press.
4. Advanced Java by -Balaguruswamy .
5. The Java Ee 7 Tutorial by -Ricardo Cervera -Navarro

*****







munotes.in

Page 19

19 2
JAVA EE ARCHITECTURE, SERVER AND
CONTAINERS
Unit Structure
2.1 Objectives
2.2 Introduction to Java EE Architecture
2.3 Types of System Architecture
A) Java Enterprise System deployments based Architecture
2.3.1 Logical Tiers Level
2.3.2 Infrastruc ture Service Levels
2.3.3 Quality of Service Level
B) Java EE Development Architecture
2.4 Java EE Server
2.5 Java EE Containers
2.6 Questions
2.7 Summary
2.8 Reference for further reading
2.1 OBJECTIVES 1) Java EE Provides Simplified coding Techniq ue.
2) Java EE Provides Flexible Architecture where we can design in
various perspective levels..
3) students/professionals are able to originally design and develop &
Deploy their application on server.
4) Java EE Server for implementation of Enterprise Application.
5) Java EE Provides various Containers to transform Business logic etc...
6) Java EE provides a powerful API for Strong and Dynamic Web
Programming.
2.2 JAVA ENTERPRISE SYSTEM ARCHITECTURE

Fig: 2.2 Java Enterprise System Architecture. munotes.in

Page 20


Enterprise Java
20 A) Java Enterprise System deployments based Architecture:
To discuss java EE architectural concepts upon which Java Enterprise
System deployments are based.
Java Enterprise Edition is a framework in which Java Enterprise System
deployment architectures are a nalyzing along with the following three
ways/Dimensions:
 Logical tiers.
 Infrastructure service levels,
 Quality of service.
These three dimensions, following figure, help to clarify the architectural
functions of Java Enterprise System components while de signing and
developing projects. In Java EE The three -dimensional framework is the
key to designing successful Design & deployment architectures for
business software solutions.

Figure 2.3 -A Three Dimensions of Java Enterprise System
Architectural Frame work
1) Logical Tiers:
In Java EE standard architecture for distributed applications separates
application logic into a number of tiers. These tiers signify a logical and
physical organization of components into an ordered chain/processing
sequence of serv ice providers and consumers in network.

Figure 2.3.1 Logical Tiers for Distributed Enterprise Applications
munotes.in

Page 21


Java EE Architecture, Server and Containers
21 I) Client Tier:
The client tier consists of application logic/Business logic accessed
directly by an end user/client side through a user interfac e. The logic in
the client tier could include browser -based clients.
II) Presentation Tier:
The presentation tier consists of application logic/Business logic that
prepares data as per request/response for sending to the client tier and
processes request s from the client tier to get the back -end business logic as
per concern of request & response. The logic in the presentation tier
typically consists of J2EE components such as Java Servlet components or
JSP components that prepare data for HTML or XML sen ding/receiving or
that receive requests for processing from client to server or vice versa.
This tier includes various services - secure, personalized, and customized
access to business services in the business service tier.
III) Business Service Tier:
The business service tier consists of actual required Business logic that
performs the main functionality of the applications such as processing
data, implementing business rules, coordinating multiple users, and
managing external resources such as databases or legacy systems as per
request & response from the network. In J2EE components can be
assembled to deliver complex business services/business processes such as
an inventory service or tax calculation service etc.
The various implementations of business services encapsulate specific
application functionality that can reside and run on a particular computing
node/client.
IV) Data Tier:
The data tier consists of data used by business logic. The data can be
persistent application data stored in a database management system. The
data can also include data feeds from external sources or data accessible
from legacy systems.
2) Infrastructure Service Levels:
The interacting software components of distributed enterprise applications
require an underlying set of infrastructure services that allows the
distributed components to communicate with each other on network
communication i.e client to server & server to client, coordinate their
work, implement secure access, and so forth. This set of distributed
services c onstitutes an infrastructure upon which distributed components
can be design & built.

munotes.in

Page 22


Enterprise Java
22 Distributed Infrastructure Services:
Distributed infrastructure services distributed at many different levels.

Figure 2.3.2 Distributed Infrastructure Service Levels
The Infrastructure Service Levels in the above Figure reflect a general
dependence of the various distributed services on one another, from the
lowest -level operating system services to the highest -level application and
integration services in Java Enterpr ise.
Following are the list of Levels from bottom to top:
I) Operating system platform:
It Provides the basic support for any process running on a computing
node. The operating system manages physical devices as well as memory,
threads, and other resource s necessary to support the Java Virtual Machine
.
II) Network transport:
Network transport Provides basic networking support for communication
between distributed application components running on different
computing nodes/Network connected different nod es or clients. All These
services include support for protocols such as TCP and HTTP/ HTTPS.
III) Persistence:
It Provides support for accessing/fetching and storing both static data
(such as user, directory, or configuration information) and dynamic
application data (information that is frequently being updated).
VI) Messaging:
Messaging Layer Provides support for both synchronous and
asynchronous communication between application components in client
and server. Synchronous messaging is real -time sendi ng and receipt of munotes.in

Page 23


Java EE Architecture, Server and Containers
23 messages; it includes remote method invocation (RMI) between J2EE
components and SOAP interactions with web services. Asynchronous
messaging is communication in which the sending of a message does not
depend on the readiness of the consum er to immediately receive it.
Asynchronous messaging specifications, for example, Java Message
Service (JMS) and ebXML, It will support guaranteed reliability and other
messaging semantics.
VII) Runtime:
It Provides support required by any distributed com ponent model, such as
the J2EE or CORBA models. In addition to the remote method invocation
needed for tightly coupled distributed components, runtime services
include component state (life -cycle) management, thread pool
management, synchronization (mutex locking), persistence services,
distributed transaction monitoring, and distributed exception handling. In a
J2EE environment, these runtime services are provided by EJB, web, and
message -driven bean (MDB) containers in an application server or web
server.
VIII) Security and policy:
Provides support for secure access to application resources. These services
include support for policies that govern group or role -based access to
distributed resources, as well as single sign -on capabilities. The
enhancement o f authentication in Single sign -on allows a user’s
authentication to one service in a distributed system to be automatically
applied to other services (J2EE components, business services, and web
services) in the system.
IX) User collaboration:
It Provid es services that play a key role in supporting direct
communication between users and collaboration among users in enterprise
and Internet environments. And also, al l these services are application -
level business services, normally provided by standalone s ervers (such as
an e-mail server).
X) Integration:
It Provides the services that aggregate existing business services, either by
providing a common interface for accessing them through a network, as in
a portal, or by integrating them through a process engine that coordinates
them within a production workflow. Integration can also take place as
business -to-business interactions between different enterprises/ various
enterprise applications.
3) Quality of Service Layer:
The previous two architectural Le vels (logical tiers and infrastructure
service levels) largely define the logical/business logical aspects of
architecture, namely which components are needed to interact in what are
the ways where to deliver services to end users/clients. munotes.in

Page 24


Enterprise Java
24 As internet and E-commerce services now become more critical to handle
business operations/services, scalability, performance, security,
availability and serviceability of these services has become a key
requirement of large -scale, high -performance deployment architect ures in
java enterprise applications.
Following are the List of Quality Services required in Java EE
Architecture.
1) Performance:
To check out measurement of response time and latency with respect to
user load conditions.
2) Availability:
A measuredly sys tem’s resources and services are accessible to end
users/clients, often expressed as the uptime of a desired system.
3) Security:
Regarding security, a complex combination of factors that describe the
integrity of a system and its users. Security includes authentication and
authorization of users as well as the secure transport of information
through the network.
4) Scalability:
In Enterprise applications the ability to add capacity (and users) to a
deployed system over time. Scalability typically involves adding resources
to the system but should not require changes to the deployment
architecture while designing java applications.
B) Java EE Development Architecture:
Following are Java EE provides an environment for development and
deployment of web -based e nterprise applications using multi -tier
architecture.

The above diagram demonstrates J2EE multi -tier architecture that
encompasses several J2EE containers each including its own J2EE
components. munotes.in

Page 25


Java EE Architecture, Server and Containers
25 Following a list of overview about the different tiers of J2EE
architecture:
1) Client Tier :
In JEE Architecture Components of Client Tier will run in the client
devices / containers. Client Tier components are standalone or web based
java applications, static and dynamic HTML pages, and applets.
2) Middle Tie r:
I) Web Tier: In JEE the web tier components namely JSP and Servlets
execute with the help of J2EE web server in a web container.
II) Business Tier: In this tire integrate purely Business logic with
Enterprise Java Beans (EJB) are the business tier comp onents that are
executed within the EJB container using J2EE Application
Server/web server.
3) EIS Tier :
EIS (Enterprise Information Systems) tier follows operations related to
application data that are stored in a database. EIS tier may also include
ERP’s varois big operations or legacy systems.
2.4 JAVA EE SERVER A Java EE server is a server application that implements the Java EE
platform APIs and provides the standard Java EE services for Design &
developing Applications. Java EE servers are sometimes called application
servers or web servers, because they allow you to serve application data to
clients, same processing on 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.

Fig: 2.4 Java EE Communication Server: munotes.in

Page 26


Enterprise Java
26 2.4.1 Java EE Containers:
Java EE containers are the interface between the component and the
lowe r-level functionality of the application server provided by the
platform to support that component and API . The functionality of the
container is defined by the platform to provide more productivity, and is
different for each component type. The server al lows the different
component types to work together to provide the enhancement of
functionality in an enterprise application.

Fig: 2.4.1 Java EE Containers
2.4.2 The Web Container:
The web container is the interface between web components or API and
the web server. A web component can be a JSP page, or a JavaServer
Faces Facelets page, and servlet. The web container manages the
processes of Request & Response in the component’s lifecycle ,
dispatches requests to application components, and provides i nterfaces to
context data, such as information about the current request.

Fig: 2.4.2 TheWeb Container: munotes.in

Page 27


Java EE Architecture, Server and Containers
27 2.4.3 The Application Client Container:
The application client container is the interface between Java EE
applications and clients/browsers , which ar e special Java SE applications
that use Java EE server components with more API’s , and the Java EE
server. The application client container runs on the client machine, and is
the gateway between the client application and the Java EE server
components tha t the client/browsers uses.

Fig: 2.4.3 The Application Client Container.
2.4.4 The EJB Container:
The EJB container is the interface between enterprise java beans, which
provide the business logic in a Java EE application to manage data
transportation in critical condition with the Java EE server. The EJB
container runs on the Java EE server or web server and manages the
execution of an application’s enterprise beans in Business Logic to
Database and viceversa.

Fig: 2.4.4 The EJB Container.
2.5 JAVA EE CONTAINERS Containers easily manage their transaction and state management,
multithreading, resource pooling, and other complex low -level details. The
component -based and platform -independent. munotes.in

Page 28


Enterprise Java
28 Java EE architecture provides better service to write business logic that is
organized into reusable components.
Container Services:
Containers are the interface between a component and the low -level
platform -specific functionality that supports the component. Before a web,
enterprise bean, or application client com ponent can be executed, it must
be assembled into a Java EE module and deployed into its container.
Key points of Container:
 In Java EE security models configure a web component or EJB so
that system resources are accessed at client side/browsers only by
authorized users.
 The Java EE transaction model provides relati onships among
methods/functions that communicate a single transaction so that all
methods/functions in single transaction are treated as a single unit.
 The Java EE can be remotely connecti vity model manages low -level
communications between clients and EJB
Following diagrams shows The deployment process installs Java EE
application components in the Java EE containers as illustrated in
Following Figure.

Figure 2.5 Java EE Server and Conta iner.
Following are the list of Types of Container:
1) Enterprise JavaBeans (EJB) container:
EJB containers can manage the execution of enterprise beans for Java EE
applications/ web applications & services. EJB and their container run on
the Java EE se rver/web server. munotes.in

Page 29


Java EE Architecture, Server and Containers
29 2) Web container:
Here Web containers can manage the execution of JSP page and servlet
components for Java EE applications. Web components and their
containers run on the Java EE server/web server.
3) Application client container:
Java E E Application client container can manage the execution of
application client components. Java EE Application clients and their
container run on the client/browser.
4) Applet container:
Manages the execution of applets/java programs executed on client.
Applet container consists of a web browser and Java Plug -in running on
the client.
2.6 QUESTION 1 Explain in detail the container with types.
2 Explain Java EE Development Architecture.
3 Difference between Apache tomcat & Glassfish server.
4 Explain Java EE Deployment Architecture.
5 Explain Quality of Service layer in Java EE Deployment Architecture.
6 Define the web container.
7 Define the EJB container.
2.7 SUMMARY Web server is a computer where the web content is stored. Basically a web
serve r is used to host the web sites . In java EE Containers are the interface
between a component and the low -level, platform -specific functionality
that supports the component. Java Enterprise Edition is a set of various
specifications, for enterprise features such as dis tributed computing,
Security, Powerful API’s and web services.
2.8 REFERENCE FOR FURTHER READING: 1. Java EE 6 Enterprise Architect Exam Guide ,Author: PaulAllen,
Publisher: McGraw -Hill
2. The Complete Reference -Java Enterprise Edition (Black Book),
Author:Herbert schildt.
3. Java EE 7 The Big Picture by - Dr.Danny Coward Publisher - Oracle
press.
4. Advanced Java by -Balaguruswamy .
5. The Java Ee 7 Tutorial by -Ricardo Cervera -Navarro
***** munotes.in

Page 30

30 3
INTRODUCTION TO JAVA SERVLETS
Unit Structure
3.1 Objectives
3.2 The Need for DynamicContent
3.2.1 Introduction
3.2.2 Dy namic content vs static content
3.2.3 Area s to implement Dynamic Content
3.3 Java Servlet Techno logy
3.3.1 Use of Servlet
3.3.2 CGI (Common Gateway Interface)
3.3.3 Servlet Technology
3.4 Why Servlets
3.5 What can Servlets do
3.6 Questions
3.7 Summary
3.8 Reference for further reading
3.1 OBJECTIVES 1) Java servlet provides server side coding technique.
2) Java servlet is used to de velop & design web applications in a web
server.
3) Using servlet for students/professionals are able to originally design
and develop & Deploy their application on server.
4) Servlet is a technology which is used to create a web application
executed at server s ide.
5) Java servlet provides a powerful API for best Dynamic Web
Programming.
3.2 THE NEED FOR DYNAMIC CONTENT 3.2.1 Introduction:
Dynamic content refers to web content that changes based on
the behaviour , preferences, and interests of the user. It refers to websites as
well as e -mail content and is generated at the moment a user requests a
page. Dynamic content is personalized and adapts based on the data you
have about the user and on the access time, its goal being to deliver an
engaging and satisfying onl ine experience for the visitor.
munotes.in

Page 31


Introduction to Java Servlets
31 Dynamic content ( adaptive content) refers to web content that changes
based on the behaviour , preferences, and interests of the user. It refers to
websites as well as Email content and is generated at the moment a user
requests a page. Dynamic content is personalized and adapts based on the
data you have about the user and on the access time, its goal being to
deliver an engaging and satisfying on line experience for the visitor.
A server -side dynamic web page is a web page whose construction is
controlled by an application server to process server -side scripts
dynamically . In se rver-side scripting programming , an parameters
determine how the assemb ly of every new web page proceeds as per user
request, including the setting up of more client -side processing
This content can be displayed in a variet y of different forms on the Web .
The way it is usually presented is based on the type of website you are on.
However, things like pictures, text, videos, newsletters, and other web
forms are often great examples of this content being used.
3.2.2 Dynamic content vs static content :
Static content has not changed on the internet. This is because it’s much
easie r to implement than the dynam ic text alternatives on the Web .
However, the downside is that static content is not personalized and thus it
reduces the performance of the website. Dynamic content has various
benefits as follows:
Difference between Static and Dynamic Web Pages
Sr.No Static Web Page Dynamic Web Page 1. In static web pages, Pages will remain same until someone changes it manually. In dynamic web pages, Content of pages are different for different visitors. 2. Static Web Pages are simple in terms of complexity. Dynamic web pages are complicated. 3. In static web pages, Information are change rarely. In dynamic web page, Information are change frequently. 4. Static Web Page takes less time for loading than dynamic web page. Dynamic web page takes more time for loading. 5. In Static Web Pages, database is not used. In dynamic web pages, database is used. 6. Static web pages are written in languages such as: HTML, JavaScript, CSS, etc. Dynamic web pages are written in languages such as: CGI, AJAX, ASP, ASP.NET, etc. 7. Static web pages does not contain any application program Dynamic web pages contains application program for different services.
munotes.in

Page 32


Enterprise Java
32 8. Static web pages require less work and cost in designing them. Dynamic web pages require comparatively more work and cost in designing them.
● it makes for a more user -friendly experience on the web/Internet.
● it helps increase vital current data, latest information or instant info.
● Within page layout properly & accurate displays data.
● Once has been upload , live and active, you don’t need to tend to it
anymore
3.2.3 Areas to implement Dynamic Content:
1) Newsletters and Emails:
Newsletters and emails are probably the most basic and classic forms of
dynamic content being presented as per requireme nt. Customized emails
or customized form fields for specific users have been around on the web
for a long time. Presenting your dynamic content this way is always a
good choice because data is frequently changed. And some newsletter
plugins will display its content/data as per updated content you re -purpose.
2) Landing Pages :
A landing page is built specifically to target a cer tain thing or targeted
audience . Whether it is a product or a service that has to be reached , the
landing page acts as an informational doorway to what you are selling to
an accurate customer. Take it further by presenting a landing page that
uses dynamic content to display different information and items based on
who is viewing it as per search & updated data.
3) Articles :
Articles can be used to display dynamic content based on the
device/platforms that is being used to read the article. This type of content
can be displayed properly on any devic e and screen size or resolution . This
is why your website should be mobile frie ndly and responsive web
content . Giving the user viewable content no matter wher e they access it
would be displayed in proper layout to any device or screen.
4) Forms and Purchases :
As per every user requirement or organization operation perspective
Different form and purchase fields or other information can be displayed,
based on how the checkout is going to be on demand , who the user is, and
what their interests are different users makes the entire experience much
better for them.
5) Produ ct Pages :
In E -commerce online stores will use product pages to cross -sell and
match related items for the site user where the user chooses the products. munotes.in

Page 33


Introduction to Java Servlets
33 This is dynamic content at work using certain things to match up what we
think or what the users need as per the user wants to see. Online store
organization bounce offers like sales and coupons or other special
recommendations as well.
6) Website Ads :
Ads on websites, social media and on Google can use Digital marketing or
Digital advertisement using dyna mic content technique. These ads display
content on what users search and interests the website or Application. This
makes ad interaction and click -throughs much more likely where users
easily interact with.
3.3 Java Servlet Technology:

Servlet is a tech nology used to create a java web application ( placed at
server side and generates a dynamic web page as per client request ).
Servlet is a technology that is robust and scalable and secure because of
the Java language. Before Servlet, CGI (Common Gateway I nterface)
scripting language was common as a server -side programming language.
There were many disadvantages of CGI. Some of these disadvantages are
discussed below.
Servlet API is a collection of various interfaces and classes in the Servlet
API such as S ervlet, ServletResponse,ServletRequest GenericServlet,
HttpServlet... etc.
3.3.1 Use of Servlet:
Servlet technology can be described in many ways, As follows.
● Servlet is a technology which is used to create a java web application.
● Servlet is an API collect ion of various interfaces and classes.
● Servlet is an interface that must be implemented for creating any
Servlet page. munotes.in

Page 34


Enterprise Java
34 ● Servlet is a class that extends the capabilities of the servers and
responds to the incoming requests. It can respond to any requests.
● Servlet is a web component that is deployed on the server to create a
dynamic web page.

Fig: 3.3 Communication of Java Servlet Technology.
What is a web application?
A web application is a server side application which is accessible from the
web/web brows er. A web application is composed of web components like
Servlet, Filter & JSP, etc. and other elements such as HTML, CSS, and
JavaScript. The web components typically execute in Web Server and
respond to the HTTP request.
3.3.2 CGI (Common Gateway Interfa ce):
CGI technology enables the web server to call an external program and
pass HTTP request information to the external program to process the
request. For each & every request, it starts a new process or creates a new
Thread for every request. i.e. Numbe r request coming to CGI , a number of
newly processes or threads to create. CGI will get more load & responses
are slow or its processing task may be heavy.
The Common Gateway Interface (CGI) provides the middleware
between WWW servers and external database s and information sources.
The World Wide Web Consortium (W3C) defined the Common Gateway
Interface (CGI) and also defined how a program interacts with a Hyper
Text Transfer Protocol (HTTP) server. The Web server typically passes
the form information to a small application program that processes the
data and may send back a confirmation message. This process or
convention for passing data back and forth between the server and the
application is called the common gateway interface (CGI).
Features of CGI:
 It is a very well defined and supported standard. munotes.in

Page 35


Introduction to Java Servlets
35  CGI scripts are generally written in either Perl, C, or maybe just a
simple shell script.
 CGI is a technology that interfaces with HTML.
 CGI is the best method to create a counter because it is currently the
quickest
 CGI standard is generally the most compatible with today’s
browsers .
Advantages of CGI:
 The advanced tasks are currently a lot easier to perform in CGI than
in Java.
 It is always easier to use the code already written than to write your
own.
 CGI sp ecifies that the programs can be written in any language, and
on any platform, as long as they conform to the specification.
 CGI-based counters and CGI code to perform simple tasks are
available in plenty.

Fig: 3.3.2 CGI (Common Gateway Interface) Commun ication flow.
Disadvantages of CGI :
There are many problems in CGI technology:
1. If the number of clients increases, it takes more time to send the
response.
2. For each request, it starts a process, and the web server is limited to
start processes.
3. It uses pla tform dependent languages e.g. C, C++, perl.
4. CGI facing Net work Traffic, because of heavy load.
5. Number request , Number of newly processes so CGI contain heavy
load. munotes.in

Page 36


Enterprise Java
36 3.3.3 Servlet Technology & its Advantages:

Fig: 3.3.3 Servlet Technology Communication flow.
As per comparison of Servlet & CGI there are many advan tages of Servlet
over CGI. The web container/Servlet will create threads for handling the
multiple requests to the Servlet. Threads have many benefits over the
Processes happening in Network such as they share a common memory
area of the server, are lightw eight, and cost of communication between the
threads are low.
Shortly after the Web began to be used for delivering services, service
providers recognized the need for dynamic content. Applets, one of the
earliest attempts toward this goal, focused on usi ng the client platform to
deliver dynamic user experiences. At the same time, developers also
investigated using the server platform for the same purpose. Initially,
Common Gateway Interface (CGI) server -side scripts were the main
technology used to genera te dynamic content. Although widely used, CGI
scripting technology had many shortcomings, including platform
dependence and lack of scalability. To address these limitations, Java
Servlet technology was created as a portable way to provide dynamic,
user-oriented content.
The advantages of Servlet are as follows:
1. Better performance : No of process es is converted into threads so ,
because it creates a thread for each request, not process.
2. Portability: Servlet programs execute any platform because it uses
Java l anguage.
3. Robust: JVM manages Servlet programs, so we don't need to worry
about the memory leak, garbage collection, etc.
4. Secure: because it uses java language.

munotes.in

Page 37


Introduction to Java Servlets
37 Difference between Servlet and CGI Servlet CGI(Common Gateway Interface) Servlets are portable and efficient. CGI is not portable In Servlets, sharing data is possible. In CGI, sharing data is not possible. Servlets can directly communicate with the webserver. CGI cannot directly communicate with the webserver. Servlets are less expensive than CGI. CGI is more expensive than
Servlets. Servlets can handle the cookies. CGI cannot handle the cookies.
3.4 WHY SERVLETS? Today’s Web applications trends it to creating dynamic web pages i.e the
ones which have the capability to change the site conten ts according to the
time/response or are able to generate the contents according to the request
received by the client. If you like coding in Java, then you will be happy to
know about Java. There also exists a way to generate dynamic web pages
and that w ay is Java Servlet API. first understand the need for server -side
extensions i.e why use servlet to develop dynamic applications.
A servlet is a Java Programming language class that is used to extend the
capabilities of servers that host applications acce ssed by means of a
request -response programming model. Although servlets can respond to
any type of request, they are commonly used to extend the applications
hosted by web servers. It is also a web component that is deployed on the
server to create a dyna mic web page.

Fig: How servlet Work. munotes.in

Page 38


Enterprise Java
38 In this figure you can see, a client sends a request to the server and the
server generates the response, analyses it and sends the response to the
client.
Servlets are the Java programs that run on the Java -enabled w eb server or
application server[Apache server, Glassfish server, etc….]. They are used
to handle the request obta ined from the web server/Client , process the
request, produce the response, then send a response back to the web
server/web browser.
Propertie s of Servlets are as follows:
 Servlets work on the server -side.
 Servlets are capable of handling complex requests obtained from the
web server.

Fig: 3.4 Servlet Architecture

Execution of Servlets basically involves following basic steps:
1. The client s/browsers send the request to the web server.
2. The web server receives the request from clients.
3. The web server passes the request to the corresponding servlet
container.
4. The servlet processes the request and generates the response in the
form of output.
5. The servlet sends the response back to the web server. munotes.in

Page 39


Introduction to Java Servlets
39 6. The web server sends the response back to the client and the client
browser displays it on the screen.
3.5 WHAT CAN SERVLETS DO? Introduction:
Java Servlets are programs that run on a Web or Application server and act
as a middle layer between a request coming from a Web browser or other
HTTP client and databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms,
present records fro m a database or another source, and create web pages
dynamically.
Java Servlets often serve the same purpose as programs implemented
using the Common Gateway Interface (CGI).
But Servlets offer several advantages in comparison with the CGI:
 Performance is significantly better.
 Servlets execute within the address space of a Web server. It is not
necessary to create a separate process to handle each client request.
 Servlets are platform -independent because they are written in Java.
 Java security manager on t he server enforces a set of restrictions to
protect the resources on a server machine. So servlets are trusted.
 The full functionality of the Java class libraries is available to a
servlet. It can communicate with applets, databases, or other software
via the sockets and RMI mechanisms that you have seen already.
Servlets Architecture
The following diagram shows the position of Servlets in a Web
Application.

Fig: Servlet Architecture munotes.in

Page 40


Enterprise Java
40 Servlets Tasks :
Servlets per form the following major tasks
 Read the exp licit data sent by the clients (browsers). This includes an
HTML form on a Web page or it could also come from an applet or a
custom HTTP client program.
 Read the implicit HTTP request data sent by the clients (browsers).
This includes cookies, media types and compression schemes the
browser understands, and so forth.
 Process the data and generate the results. This process may require
talking to a database, executing an RMI or CORBA call, invoking a
Web service, or computing the response directly.
 Send the explicit data (i.e., the document) to the clients (browsers).
This document can be sent in a variety of formats, including text
(HTML or XML), binary (GIF images), Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This
includes telling the browsers or other clients what type of document is
being returned (e.g., HTML), setting cookies and caching parameters,
and other such tasks.
1) Dynamic website:
Dynamic website is a collection of dynamic web pages whose content
changes dynamically. I t accesses content from a database or Content
Management System (CMS). Therefore, when you alter or update the
content of the database, the content of the website is also altered or
updated.
Dynamic websites are those websites that changes the content or l ayout
with every request to the webserver. These websites have the capability
of producing different content for different visitors from the same source
code file. There are two kinds of dynamic web pages i.e. client side
scripting and server side scriptin g. The client -side web pages changes
according to your activity on the web page. On the server -side, web
pages are changed whenever a web page is loaded.
Dynamic websites use client -side scripting or server -side scripting, or both
to generate dynamic conte nt.
Dynamic websites use client -side scripting or server -side scripting, or both
to generate dynamic content.
Client side scripting generates content at the client computer on the basis
of user input. The web browser downloads the web page from the server
and processes the code within the page to render information to the user. munotes.in

Page 41


Introduction to Java Servlets
41 In server side scripting, the software runs on the server and processing is
completed in the server then plain pages are sent to the user.

2) The server -side extensions:
In Java se rver side extensions i.e . servlet or JEE are nothing but the
technologies that are used to create dynamic Web pages. In servlet
Technology to provide the facility of dynamic Web pages, Web pages
need a container or Web server. To complete this requirement,
independent Web server providers offer some essentials solutions in the
form of APIs(Application Programming Interface).
3) Handling Request & Response:
In Servlet Technology for the purpose of communication to use HTTP
protocol. The Hypertext Transfer P rotocol (HTTP) is an application -level
protocol for distributed, collaborative and hypermedia information
systems. HTTP Request & Response are the data communication protocol
used to establish communication between client and server.
HTTP is a stateless T CP/IP based communication protocol, which is used
to send & receive data like image files, query results, HTML files etc on
the World Wide Web (WWW) with the default port being TCP 80. It
provides a standardized way for computers to communicate with eac h
other in a network .

Fig:A- Handling Http Request & Response munotes.in

Page 42


Enterprise Java
42

Fig:B- Handling Http Request & Response .

The Basic Characteristics of HTTP (HyperText Transfer Protocol):
 HTTP protocol allows web servers and browsers to exchange data
over the web.
 HTTP a r equest response protocol.
 HTTPuses the reliable TCP connections by default on TCP port 80.
 HTTP is stateless means each request is considered as the new
request. In other words, the server doesn't recognize the user by
default.
HttpServlet class provides s pecialized methods that handle the various
types of HTTP requests. A servlet developer typically overrides one of
these methods. These methods are doDelete( ), doGet( ), doHead( ),
doOptions( ), doPost( ), doPut( ), and doTrace( ). However, the GET and
POST requests are commonly used when handling form input.
The doPost( ) method is overridden to process any HTTP POST requests
that are sent to this servlet. It uses the getParameter( ) method of
HttpServletRequest to obtain the selection that was made by the user.
4) Filtering Requests and Responses:
In Servlet Technology to provide a filter object that can transform the
header and content (or both) of a request or response. In the Servlet Filters
objects differ from web components in that filters usually do not
themselves create a response. Instead a filter object provides functionality
that can be “attached” to any kind of web resource with servlet objects.
In Servlet filter Object can perform following tasks:
● Filter object Query the request and act acco rdingly.
● Block the request -and-response pair from passing any further
transaction.
● Filter objects can modify the request headers and data. You do this by
providing a customized version of the request. munotes.in

Page 43


Introduction to Java Servlets
43 ● In Filter Modify the response headers and data. You do this by
providing a customized version of the response.
● Filter Objects are Interact with various external resources.
5) Sharing Information:
In servlet its mechanism is objects communicate in through a network.
There are several ways they can do this. In Java Servlet class can use
private helper objects (for example, JavaBeans components), Servlet class
(beans) can share objects that are attributes of a public scope or private,
they can use a database, and they can invoke other web resources.
In servlet its mechanism is objects communicate in through a network.
There are several ways they can do this. In Java Servlet class can use
private helper objects (for example, JavaBeans components), Servlet class
(beans) can share objects that are attributes of a public scope or private,
they can use a database, and they can invoke other web resources.
The Java Servlet technology mechanisms that can be allowed to access a
component to invoke other web resources are described in Invoking Other
Web Resources.
6) Accessing the Web Context:
In The Servlet context in which web components execute is an object that
implements the ServletContext interface. You retrieve the web context
using the getServletContext method. The web context provides methods
for accessing:
● Initialization parameters.
● Resources associated with the web context.
● Object -valued attributes.
● Logging capabilities.
3.6 QUESTIONS 1. Explain what is Dynamic Content?
2. Explain what is needed to be Design Dynamic Content.
3. Explain the features of Servl et.
4. Explain in detail Why Servlet is popular as compared to CGI.
5. Difference between Servlet Vs CGI.
6. Explain Use of Servlet in Web Application.
7. Define Servlet API. munotes.in

Page 44


Enterprise Java
44 8. Explain in brief What can servlet do?
9. Explain in detail Servlet Architectur e.
10. Define Request & Response Methodology.
3.7 SUMMARY A server -side dynamic web page is a web page whose construction is
controlled by an application server to process server -side scri pts
dynamically . In se rver-side scripting programming , parameters de termine
how the assembly of every new web page proceeds as per user request,
including the setting up of more client -side processing.
Dynamic content is personalized and adapts based on the data you have
about the user and on the access time, its goal bein g to deliver an engaging
and satisfying online experience for the visitor.
Servlet is a technology used to create a java web ap plication ( placed at
server side and generates a dynamic web page as per client request ).
Servlet is a technology that is robust and scalable and secure because of
the Java language. Before Servlet, CGI (Common Gateway Interface)
scripting language was common as a server -side programming language.
There were many disadvantages of CGI. Some of these disadvantages are
discussed below.
The client -side web pages changes according to your activity on the web
page. On the server -side, web pages are changed whenever a web page is
loaded.
Dynamic website is a collection of dynamic web pages whose content
changes dynamically so we can design such a dynamic application using
servlet. It accesses content from a database or Content Management
System (CMS).
3.8 REFERENCE FOR FURTHER READING 1. The Complete Reference -Java Enterprise Edition (Black Book) ,
Author:Herbert schildt.
2. Java EE 7 The Big Picture by - Dr.Danny Coward Publisher - Oracle
press.
3. Advanced Java by -Balaguruswamy .
4. The Java Ee 7 Tutorial by -Ricardo Cervera -Navarro.
***** munotes.in

Page 45

45 4
SERVLET API AND LIFECYCLE
Unit Structure
4.1 Objectives
4.2 Java Servlet API
4.3 The Servlet Skeleton
4.4 The Servlet Life Cycle
4.5 A Simple Welcome Servlet Program
4.6 Questions
4.7 Summary
4.8 Reference for further reading
4.1 OBJECTIVES 1) Java Ser vlet Provides Server side Programming techniques.
2) Java Servlet Provides Flexible Architecture where we can
communicate easily through a web server.
3) Java Servlet for implementation of communication between client &
server.
4) Java Servlet Provides a mechanism i.e handles the request & response
services.
5) Java Servlet provides a powerful API for Strong and Dynamic Web
Programming.
6) Students/professionals are able to originally design and develop &
deploy their application on server.
4.2 JAVA SERVLET API  In Java S ervlet Containing API i.e the javax.servlet and
javax.servlet.http packages represent interfaces and classes for servlet
API Where to design java web applications.
 The javax.servlet package contains so many interfaces and classes
that are used by the serv let or web container programming.
 The javax.servlet.http package contains interfaces and classes that are
responsible for handling HTTP related Requests & Responses from
client to server & viceversa.
In Java EE Servlet interface provides common behavi or to all the servlets.
Servlet interface defines methods that all servlets must implement for
handling processes. munotes.in

Page 46


Enterprise Java
46 Servlet interface needs to be implemented for creating any servlet (either
directly or indirectly) Without servlet interface servlet class wi ll not be
generate.
In the Javax.servlet package , the ServletRequest Interface is used to
handle client requests to access a servlet. It provides th e information of a
servlet like , parameter names, content type, content length and values.
In the Javax.serv let package, the ServletResponse interface defines an
object to help a Servlet in sending a response to the client/browser. It has
various methods that help communicate a servlet to respond to the client
requests.
In the Javax.servlet package , the RequestD ispatcher interface provides the
facility of dispatching the request to another resource , be it html, servlet
or jsp. This interface can also be used to include the content of another
resource.
Following are the inte rfaces of javax.servlet package:
There are many interfaces in the javax.servlet package. They are as
follows:
1. Servlet Interface.
2. ServletRequest.
3. ServletResponse.
4. RequestDispatcher.
5. ServletConfig:
6. ServletContext
7. ServletRequestListener
8. ServletRequestAttributeListener
9. ServletContextListener
10. ervlet ContextAttributeListener
Following are the List of Classes in javax.servlet package
1. GenericServlet.
2. ServletInputStream.
3. ServletOutputStream. munotes.in

Page 47


Servlet API and Lifecycle
47 4. ServletRequestWrapper.
5. ServletResponseWrapper.
6. ServletRequestEvent.
7. ServletContextEvent.
8. ServletRequestAttributeEve nt.
9. ServletContextAttributeEvent.
10. ServletException.
11. UnavailableException.
Following are the List of Interface s in javax.servlet.http package:
1) HttpServletRequest.
2) HttpServletResponse.
3) HttpSession.
4) HttpSessionListener.
5) HttpSessionAttributeListener.
6) HttpSess ionBindingListener.
7) HttpSessionActivationListener.
Following are the List of Classes in javax.servlet.http package :
1) HttpServlet.
2) Cookie.
3) HttpServletRequestWrapper
4) HttpServletResponseWrapper
5) HttpSessionEvent.
6) HttpSessionBindingEvent.
4.3 THE SERVLET SKELE TON Servlet development: a skeleton Servlet, Once you have set up your
Servlet environment , the first step is generally to write a test Servlet using
code such as the skeleton shown in this example.
munotes.in

Page 48


Enterprise Java
48 To write a basic Servlet, you generally:
 overwrite HttpServlet;
 overwrite the doGet() and doPut().
In servlet there are two methods: doGet() and doPut(). These methods will
be called in response to GET and POST requests from the user's web
browser/client side. Unless you specifically need your web application to
respond differently to the two types of request.
Servlet code looks as follows:
import java.io.*;
impor t javax.servlet.*;
import javax.servlet.http.*;
public class BasicServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWri ter pw = res.getWriter();
// ... output page to pw...
}
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
doGet(req, res);
}
}
The above example doesn't actually output any HTML, but i t shows the
basic anatomy of a servlet class. Class extends HttpServlet and must
provide implementations of the two methods. These methods correspond
to HTTP get() and post() methods respectively. Developers can generally
make doPost() simply pass the re quest to doGet(). Servlets containing
both types of requests essentially look the same. For example, parameters
will be extracted from either a URL or POSTed data. munotes.in

Page 49


Servlet API and Lifecycle
49 4.4 THE SERVLET LIFE CYCLE In Java Servlet , The web container maintains the life cycle of a servlet
instance/Object.
Following are the Stages of life cycle of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
Fi
g: 4.4 Stages of servlet life cycle .
As displayed in the above diagram, there are three states of a servlet
namely: new, ready and end.
 The servlet is in a new state if the servlet instance is created.
 After invoking the init() method, Servlet comes in the ready state. In
the ready state, se rvlet performs all the tasks.
 When the web container invokes the destroy() method, it shifts to the
end state.
1) Servlet class is loaded:
In servlet while executing the servlet class first stage is i.e classloader is
responsible for loading the servlet c lass into RAM. servlet class is loaded
when the first request comes from the web container.

munotes.in

Page 50


Enterprise Java
50 2) Servlet instance is created:
After loading the servlet class web container creates the instance of a
servlet t class. The servlet instance/object is created only once in the
servlet life cycle; the second time request is not created.
3) init method is invoked:
The web container/web server calls the init() method only once after
creating the servlet instance. Basically the init() method is used to
initialize t he servlet. init() method is the content of the life cycle of the
javax.servlet.Servlet interface.
Syntax :
public void init(ServletConfig config)
4) service method is invoked:
The web container/web server calls the service method each time when a
request for the servlet is received. If the servlet class or object is not
initialized, again it follows the first three steps as described above then
calls the service method. If the servlet is initialized, it calls the service
method.
Syntax:
public void servi ce(ServletRequest reque st, ServletResponse response)
5) destroy method is invoked:
The web container/web server calls the destroy method before removing
the servlet instance from the RAM. destroy() method gives the servlet an
opportunity to clean up any resource for example memory, thread etc.
4.5 SIMPLE WELCOME SERVLET PROGRAM There are 6 steps to create a servlet Program example.
Following are These steps are required for writing the Servlet Programs.
The servlet example can be created by three w ays:
 Implementing Servlet interface.
 Inheriting GenericServlet class.
 Inheriting HttpServlet class.
The most used approach is by extending HttpServlet in the desired servlet
file because it provides http request/response , specific methods such as
doGet(), doPost(), doHead().
❖ Steps to Create & Execute servlet Program: munotes.in

Page 51


Servlet API and Lifecycle
51 1) Create a directory structures:
The directory structure defines where to put the different types of files so
that the web container may get the information and respond to the client.
The Sun Microsystem defines a unique standard to be followed by all the
server vendors. Let's see the directory structure that must be followed to
create the servlet.

As you can see, the servlet class file must be in the classes folder. The
web.xml file must be under the WEB -INF folder.
2) Create a Servlet file:
There are three ways to create the servlet
1. By implementing the Servlet interface
2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class
The HttpServlet class is widely used to create t he servlet because it
provides methods to handle http requests such as doGet(), doPost
doHead() etc.
In this servlet example we are going to create a servlet class that will be
extended from HttpServlet class. In this example, we are inheriting the
HttpSe rvlet class and providing the implementation of the doGet()
method. Notice that get request is the default request
munotes.in

Page 52


Enterprise Java
52 Create File : SampleServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class SampleServlet ex tends HttpServlet//servlet class is extends
from Httpservlet class.
{
public void doGet(HttpServletRequest request,HttpServletResponse
response)
throws ServletException,IOException
{
response.setContentType("text/html");//setting the content type
PrintWriter pw=response.getWriter();//get the stream to write the data
//writing html in the stream
pw.println("");
pw.println("Welcome to servlet");
pw.println("");
pw.close();//closing the stream
}
}
3) Compile th e servlet :
For compiling the Servlet, a jar file is required to be loaded. Different
Servers provide different jar files: Jar files Desired Server 1) servlet-api.jar Apache Tomcat 2) weblogic.jar Weblogic 3) javaee.jar Glassfish 4) javaee.jar JBoss
Put the java file in any folder. After compiling the java file, paste the class
file of servlet in WEB -INF/classes directory. munotes.in

Page 53


Servlet API and Lifecycle
53 4) Create the deployment descriptor (web.xml file) :
The deployment descriptor is an xml file, from which Web Container gets
the inf ormation about the servet to be invoked.
The web container uses the Parser to get the information from the web.xml
file. There are many xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here are some necessary
elements to run the simple servlet program.
web.xml file


umesh
SampleServlet


umesh
/welcome


Description of the content of web.xml file :
There are too many elements in the web.xml file. Here is the illustration of
some elements that are used in the above web.xml file. The elements are
as follows:
1. represents the whole application.
2. is a sub element of and represents the servlet.
3. is a sub element of that represents the name
of the servlet.
4. is a sub element of that represe nts the class
of the servlet.
5. is a sub element of . It is used to map
the servlet.
6. is a sub element of . This pattern is
used at client side to invoke the servlet.
munotes.in

Page 54


Enterprise Java
54 5) Start the Server and dep loy the project :
To start Apache Tomcat server, double click on the startup.bat file under
apache -tomcat/bin directory.
❖ One Time Configuration for Apache Tomcat Server
You need to perform 2 tasks:
1. We have to set JAVA_HOME or JRE_HOME in the environment
variable (It is required to start the server).
2. To Change the port number of tomcat (optional). It is required if
another server is running on the same port (8080).
1) How to set JAVA_HOME in the environment variable :
To start Apache Tomcat server JAVA_HOME an d JRE_HOME must be
set in Environment variables.
Right click on my computer/ThisPC -> Click on advanced tab then
environment variables -> Click on the new tab of user variable -> Write
JAVA_HOME in variable name and paste the path of jdk folder in
variable value -> Then click on ok
Go Computer properties:



munotes.in

Page 55


Servlet API and Lifecycle
55 Click on advanced system settings:


Click on the new tab of user variable or system variable whenever
required:
munotes.in

Page 56


Enterprise Java
56 JAVA_HOME in variable name and paste the path of jdk folder in
variable value unti l bin directory:


munotes.in

Page 57


Servlet API and Lifecycle
57 Finally, the Apache server is started successfully.
2) How to change port number of apache tomcat :
TO change port number is required if there is another server running on
the same system with the same port number.
Suppose you have in stalled oracle, you need to change the port number of
apache tomcat because both have the default port number 8080.
By manually we can change the port no. Open server.xml file in notepad.
It is located inside the apache -tomcat/conf direct ory. TO Change the
Connector port = 8080 and replace 8080 by any four digit number instead
of 8080. E.g replace it by 9999 and save this file.
5) How to deploy the servlet project :
Copy the project and paste it in the webapps folder under apache tomcat.

You can also crea te a war file, and paste it inside the webapps directory.
To do so, you need to use a jar tool to create the war file. Go inside the
project directory (before the WEB -INF), then write:
projectfolder> jar cvf myproject.war
Creating a war file has the advan tage that moving the project from one
location to another takes less time.
6) How to access the servlet class:
Now Open browser and write in the address bar
http://hostname:portno/contextroot/urlpatternofservlet. For example:
http://localhost:9999/demo/wel come munotes.in

Page 58


Enterprise Java
58

2) Example of Student Registration form in servlet:
In this example, we have created the three pages.
 register.html
 Register.java
 web.xml
1) Student Register.html :
In this web page, we have input from the user using text fields and
Dropdown list. T he information entered by the user is forwarded to the
Register servlet.



Enter Student Name:


Enter Password:


Enter Email Id:


Select Country:





munotes.in

Page 59


Servlet API and Lifecycle
59

2) Register.java:
This Java Servlet class File is designed to receive all the data entered by
the user and store it into the database. Here, we are performing the
database logic.
impor t java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Register extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletExceptio n, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String uname=request.getParameter("userName");
String upass=request.getParameter("userPass");
String uemail=request.getParameter("userEmail");
String uc=request.getParameter("userCountry");
PrintWriter out = response.getWriter();
out.println("

User name=" +uname + "

");
out.println("

User pass=" +upass+ "

");
out.println("

User email=" +uemail+ "

");
out.println("

User co untry=" +uc+ "

");
out.close();
}
}
3) web.xml file :
Web.xml is the configuration file, to provide information about the
servlet.


Register munotes.in

Page 60


Enterprise Java
60 Register


Register
/register


Student Register .html


Outpu t:
1) Input Screen - Student Register.html :

2) Output Screen - Register,java// servlet file executed

4.6 QUESTIONS 1. Define Servlet?
2. Explain in detail the servlet life cycle.
3. Explain API of Servlet.
4. Differentiate between servlet & CGI. munotes.in

Page 61


Servlet API and Lifecycle
61 5. Why use ser vlets?
6. Explain servlet interface.
7. Explain Role of servlet in web application.
8. Explain stages of executing servlet programs.
9. Explain javax.servlet package.
10. Explain javax.servlet.http package.
4.7 SUMMARY In java servlet technology is use d to create a web application (basically
resides at server side and generates a dynamic web page as per request).
Java Servlet technology is secure, robust and scalable because of the Java
language features. Before Servlet, CGI (Common Gateway Interface) t his
scripting language was used for server -side programming language. In the
servlet API there are many interfaces and classes such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse.
4.8 REFERENCE FOR FURTHER READING 1. The Complete Reference -Java Enterprise Edition (Black Book) ,
Author:Herbert schildt.
2. Java EE 7 The Big Picture by - Dr.Danny Coward Publisher - Oracle
press.
3. Advanced Java by -Balaguruswamy .
4. The Java Ee 7 Tutorial by -Ricardo Cervera -Navarro.

***** munotes.in

Page 62

62 5
WORKING WITH SERVLETS
Unit structure
5.1 Objectives
5.2 Annotations in Java
5.3 Getting Started with servlet
5.4 Using Annotations I nstead of Deployment Descriptor
5.5 Servlet Program
5.6 Questions
5.7 Summary
5.8 Reference for furt her reading
5.1 OBJECTIVES 1) Java Servlet Provides Server side Programming techniques.
2) In Java Servlet for implementation of XML file or Deployment
Descriptor file.
3) We can use Annotation “ @webservlet” for there is no requirement
for a Deployment Descriptor file i.e web.xml .
4) Java Servlet provides a powerful API for Strong and Dynamic Web
Programming.
5) students/professionals are able to originally design and develop &
Deploy their application on server.
5.2 JAVA ANNOTATIONS In java Annotations is a tag that represen ts the metadata(Data about Data)
i.e. attached with class, interface, methods or fields to indicate some
additional information which can be used by java compiler and JVM.
Annotations in Java are used to provide additional information, so it is an
alternat ive option for XML i.e web.xml file (Deployment Descriptor) and
Java marker interfaces.
 Built -In Java Annotations :
There are several built -in annotations in Java. Some annotations are
applied to Java code and some to other annotations.
Built -In Java Annota tions used in Java code :
1. @Override
2. @SuppressWarnings
3. @Deprecated munotes.in

Page 63


Working with Servlets
63 ● Let's Discuss with Built -In Annotations:
1) @Override :
@Override annotation assures that the subclass method is overriding the
parent class method. If it is not so, a compile time error occur s.
Sometimes, we make silly mistakes such as spelling mistakes etc. So, it is
better to mark @Override annotation that provides assurity that method is
overridden.
class Student
{
void learnSomething()
{
System.out.println("Learning something");
}
}
class Result extends Student
{
@Override
void learnsomething()
{
System.out.println("Result ----”);
}//should be override learnSomething
}
class TestStudent
{
public static void main(String args[])
{
Student a=new Result();
a.learnSomethin g();
}
}
Output:
Compile Time Error
2) @SuppressWarnings:
@SuppressWarnings annotation: is used to suppress warnings issued by
the compiler.
import java.util.*; munotes.in

Page 64


Enterprise Java
64 class Employee
{
@SuppressWarnings("unchecked")
public static void main(String args[] )
{
ArrayList emplist=new ArrayList();
list.add("Umesh");
list.add("Datta");
list.add("Monu");
for(Object obj1:emplist)
System.out.println(obj1);
}
}
At Compile Time:
Now no warning at compile time.
If you remove the @SuppressWarnings("unch ecked") annotation, it will
show a warning at compile time because we are using a non -generic
collection.
3) @Deprecated :
@Deprecated annotation marks that this method is deprecated so the
compiler prints a warning. It informs users that it may be removed in the
future versions. So, it is better not to use such methods.
class A
{
void mfun(){System.out.println("hello m");
}
@Deprecated
void nfun()
{
System.out.println("hello n");
}
}
class TestAnnotation3
{
public static void main(String args[])
{
A a=new A(); munotes.in

Page 65


Working with Servlets
65 a.nfun();
}
}
At Compile Time:
Note: Test.java uses or overrides a deprecated API.
5.3 GETTING STARTED WITH SERVLET Servlet is the key component that forms a typical Java EE application,
beside JSP, EJB, XML and other related techno logies.
A Java EE application can be packaged/Archived in a WAR file (Web
ARchive) in order to be deployed on a web server/Application server. A
web server that can run Java servlets is called a servlet container. The
most popular and widely used servlet containers are - Apache Tomcat,
JBoss, Glassfish etc.
In Java EE servlet is a simple Java class that extends either:
● javax.servlet.GenericServletclass for generic client -server protocol.
● javax.servlet.http.HttpServlet class for HTTP protocol communicatio n
purpose.
Java servlet is mostly used for handling HTTP requests & response , by
overriding the HttpServlet’s doGet(), doPost() methods to handle GET and
POST methods to response, respectively.
The servlet container supplies an HttpServletRequest object and
HttpServletResponse object for dealing with the handling request and
response .
Servlet is usually used in conjunction with JSP for generating dynamic
content based on client’s requests.
 Annotations in servlet:
In Servlet Annotation represents the met adata. It will be prefix “@”
symbol in Servlet with Annotation,
When you use annotation (@WebServlet), deployment descriptor
(web.xml file) is not required. If we want to execute a servlet using
annotations you should have a tomcat7 and above web server to execute
the servlet. As it will not run in the previous versions of tomcat.
@WebServlet annotation is used to map the servlet with the specified
name(URL).
In Java Servlet uses the deployment descriptor (web.xml file) for
deploying/hosting your applicati on into a web server. In java 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. munotes.in

Page 66


Enterprise Java
66 If you use annotation, then the deployment descriptor (web.xml) is not
required. But you should use tomcat7 or any latest version of tomcat.
Annotations can replace equivalent XML file configuration in the web
deployment descriptor file (web.xml) such as servlet declaration,servlet
class,servlet url and servlet mappin g. Servlet containers will process the
annotated classes at deployment time.
Following are The list of annotation types introduced in Servlet 3.0 .: Sr. No. Annotation & Description 1 @WebServlet: To declare a servlet. 2 @WebInitParam:
To specify an ini tialization parameter. 3 @WebFilter:
To declare a servlet filter. 4 @WebListener :
To declare a WebListener 5 @HandlesTypes:
To declare the class types that a
ServletContainerInitializer can handle. 6 @HttpConstraint: 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. 7 @HttpMethodConstraint: This annotation is used within the ServletSecurity annotation to represent security constraints on specific HTTP protocol messages. 8 @MultipartConfig: 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. 9 @ServletSecurity: This annotation is used on a Servlet implementation class to specify security constraints to be enforced by a Servlet container on HTTP protocol message.

munotes.in

Page 67


Working with Servlets
67 5.4 USING ANNOTATIONS INSTEAD OF DEPLOYMENT DESCRIPTOR 1) A Program of simple servlet by annotation without web.xml file
(Deployment Descriptor):
SimpleExample.java :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax .servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/SimpleExample") //Annotations
public class SimpleExample extends Http Servlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("");
out.print("< h3>Hello Servlet");
out.print("");
}
}
Output:

munotes.in

Page 68


Enterprise Java
68 5.5 -SERVLET PROGRAM 2) A Program Design Student Registration process using servlet by
annotation without web.xml file:
TO Designing a servlet we have to create the three pages.
1. register.html
2. Register.java
1) Student Register.html:
In this page, we have input from the user using text fields and combobox.
The information entered by the user is forwarded to the Register servlet.



Enter Student Name:


Enter Password:


Enter Email Id:


Select Country:








2) Register.java:
This servlet class receives all the data entered by the user and stores it into
the database. Here, we are performing the database logic. But you may
separate it, which will be better for the web application.
import java.io.*;
import javax.servlet.http.*;
import java.io.IOException; munotes.in

Page 69


Working with Servlets
69 import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebSer vlet("/register")
public class Register extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.g etWriter();
String uname=request.getParameter("userName");
String upass=request.getParameter("userPass");
String uemail=request.getParameter("userEmail");
String uc=request.getParameter("userCountry");
PrintWriter out = response.getWriter();
out.println("

User name=" +uname + "

");
out.println("

User pass=" +upass+ "

");
out.println("

User email=" +uemail+ "

");
out.println("

User country=" +uc+ "

");
}
}
Output:
1) Input screen: StudentRegister.html

munotes.in

Page 70


Enterprise Java
70 2) Output Scre en : Register.java :

5.6 QUESTIONS 1. Explain what is the use of “annotation” in Java.
2. Explain in detail @WebServlet annotation in java.
3. What is needed to use annotations except web.xml.
4. Explain @override annotations in java.
5. Explain @Depreca ted annotations in java.
6. Explain in detail the flow of executing annotations.
7. List of annotations in servlet 3.0
8. Write a servlet program for calculate simple & compound interest.
9. Write a servlet program for Display entered Username .
5.7 SUMMAR Y Java Annotation is a tag that represents the metadata i.e. attached with
class, interface, methods or fields to indicate some additional information
which can be used by java compiler and JVM.
Annotations in Java are used to provide additional informatio n, so it is an
alternative option for XML and Java marker interfaces.
The servlet container supplies an HttpServletRequest object and
HttpServletResponse object for dealing with the handling request and
response .
In Servlet Annotation represents the metad ata. It will be prefix “@”
symbol in Servlet with Annotation,
When you use annotation (@WebServlet), deployment descriptor
(web.xml file) is not required. If we want to execute a servlet using
annotations you should have a tomcat7 and above web server to execute
the servlet.
munotes.in

Page 71


Working with Servlets
71 5.8 REFERENCE FOR FURTHER READING 1. The Complete Reference -Java E nterprise Edition (Black Book) ,
Author:Herbert schildt.
2. Java EE 7 The Big Picture by - Dr. Danny Coward Publisher - Oracle
press.
3. Advanced Java by -Balaguruswamy .


*****




munotes.in

Page 72

72 6
WORKING WITH DATABASE S
Unit structure
6.1 Objectives
6.2 What Is JDBC
6.3 JDBC Architecture
6.3.1 Two -tier Architecture
6.3.2 Three -tier Architecture
6.4 Accessing Database
6.5 The Servlet GUI and Database Example
6.6 Questions
6.7 Summary
6.8 Refer ence for further reading
6.1 OBJECTIVES 1) JDBC is useful for A DataSource object that is used to establish
connections .
2) Using Objects of JDBC classes & interfaces to be executing SQL
Statements .
3) Extracting metadata of a data source via JDBC driver.
4) JDBC Dr iver Manager can also be used to establish a connection
between Java & Database .
5) Using JDBC API we can Design & Develop GUI Web Application in
Java.
6.2 WHAT IS JDBC JDBC stands for Java Database Connectivity JDBC basically used in java
programming for c reate/implement connection betw een java application &
database . Java API provides JDBC Driver is a software component /
module that enables java applications to connect with the database. JDBC
is a Java API to connect and execute the SQL query with the da tabase.
JDBC API uses JDBC drivers to connect with the database and java
application.
Following are the types of JDBC drivers:
1. JDBC -ODBC Bridge Driver,
2. Native Driver,
3. Network Protocol Driver, and munotes.in

Page 73


Working with Databases
73 4. Thin Driver :
In a java application we can use JDBC API to a ccess tabular/structured
data stored in any relational database. With the help of JDBC API, we can
save, update, delete and fet ch data from the database. JDBC like Open
Database Connectivity (ODBC) provided by Microsoft.

Fig: 6.2 JDBC Connection
The java .sql package contains classes and interfaces for JDBC API.
How to import java.sql package in to java application
E.g Import java.sql.*;
Following are the list of popular interfaces of JDBC API :
1. Driver interface:
In JDBC API the JDBC Driver interfac e provides powerful
implementations of the abstract classes provided by the JDBC API for
connection . JDBC driver must provide implementations of the java.sql.
CallableStatement, PreparedStatement, Connection, Statement, ResultSet.
2. Connection interface:
In JDBC API a Connection interface is the session between a Java
application and database. The Connection interface is a factory of
PreparedStatement, Statement, and DatabaseMetaData , that means objects
of Connection can be used to get the object of Statem ent and
DatabaseMetaData.
Commonly used methods of Connection interface:
A) public Statement createStatement():
In Java creates a statement object that can be used to execute SQL queries.
munotes.in

Page 74


Enterprise Java
74 B) public Statement createStatement(int resultSetType,int
resultS etConcurrency):
Creates a Statement object that will generate ResultSet objects with the
given type.
C) public void close():
closes the connection and Releases a JDBC resources immediately.
1. Statement interface:
The Statement interface provides methods to execute queries with the
database. The statement interface is a factory of ResultSet i.e. it provides a
factory method to get the object of ResultSet.
Following are the important methods of Statement interface:
A) public ResultSet executeQuery(String s ql):
In Java is used to execute SELECT query. It returns the object of
ResultSet when executing the query.
B) public int executeUpdate(String sql):
In Java is used to execute specified query, it may be create, drop, insert,
update, delete.
C) public boo lean execute(String sql): is used to execute queries that
may return multiple results from a database.
1. PreparedStatement interface:
The PreparedStatement interface is a subinterface of Statement. It is used
to execute parameterized queries.
example of para meterized query:
String sql="insert into emp values(?,?,?)";
In the above example , we are passing parameters (?) for the values. Its
value will be set by calling the setter methods of PreparedStatement.
Why use PreparedStatement?:
● Improves performance: The performance of the application will be
faster if you use PreparedStatement interface because the query is
compiled only once.
Methods of PreparedStatement interface. munotes.in

Page 75


Working with Databases
75 Following are the important methods of PreparedStatement interface
are given below: Method Description public void setInt(int paramIndex, int value) In This method sets the integer value to the given parameter index. public void setString(int paramIndex, String value) In This method sets the String value to the given parameter index. public void setFloat(int paramIndex, float value) In This method sets the float value to the given parameter index. public void setDouble(int paramIndex, double value) In This method sets the double
value to the given parameter index. public int executeUpdate() In This method executes the query.
It is used for create, drop, insert,
update, delete etc. public ResultSet executeQuery() In This method executes the select
query. It returns an instance of
ResultSet.
2. CallableStatement interface:
In JDBC API Call ableStatement interface is used to call the stored
procedures and functions. We can have business logic on the database by
the use of stored procedures and functions that will make the performance
better because these are precompiled.
Suppose you need to g et the age of the employee based on the date of
birth, you may create a function that receives date as the input and returns
age of the employee as the output.
Following are the differences between stored procedures and
functions: Procedure Function is used to perform business logic. is used to perform calculations. must not have the return type. must have the return type. may return 0 or more values. may return only one value. We can call functions from the procedure. Procedure cannot be called from function. Procedure supports input and output parameters. Function supports only input parameters. Exception handling using try/catch block can be used in stored procedures. Exception handling using try/catch can't be used in user defined functions. munotes.in

Page 76


Enterprise Java
76 3. Resul tSet interface:
The object of ResultSet maintains a cursor pointing to a row of a table.
Initially, the cursor points to the first row.
But we can make this object to move forward and backward direction by
passing either TYPE_SCROLL_INSENSITIVE or
TYPE_SCR OLL_SENSITIVE in createStatement(int,int) method as well
as we can make this object as updatable by:
Following are the Commonly used methods of ResultSet interface: Methods Description 1) public boolean next(): This method is used to move the cursor to the one row next from the current position. 2)public boolean previous(): This method is used to move the cursor to the one row previous from the current position. 3) public boolean first(): This method is used to move the cursor to the first row in the result set object. 4) public boolean last(): This method is used to move the cursor to the last row in the result set object. 5) public boolean absolute(int row): This method is used to move the cursor to the specified row number in the ResultSet object. 6) public boolean relative(int row): This method is used to move the cursor to the relative row number in the ResultSet object, it may be positive or negative. 7) public int getInt(int columnIndex): This method is used to return the data of specified column index of the current row as int. 8) public int getInt(String columnName): This method is used to return the data of the specified column name of the current row as int. munotes.in

Page 77


Working with Databases
77 9) public String getString(int columnIndex): This method is used to return the data of the specified column index of the current row as String. 10) public String getString(String columnName): This method is used to return the data of the specified column name of the current row as String
Following are the a popular classes of JDBC API :
DriverManager class:
In JDBC API the DriverManager class acts as an interface between user
and drivers for implementing bridge between Java Application &
Database . It keeps track of the drivers that are available and handles
establishing a connection b etween a database and the driver.
Following are the methods of DriverManager class: Method Description 1) public static void registerDriver(Driver driver): This method is used to register the given driver with DriverManager. 2) public static void deregisterDriver(Driver driver): This method is used to deregister the given driver (drop the driver from the list) with DriverManager. 3) public static Connection getConnection(String url): This method is used to establish the connection with the specified url. 4) public static Connection getConnection(String url, String userName, String password): This method is used to establish the connection with the specified url, username and password.
6.3 JDBC ARCHITECTURE The JDBC API supports both two -tier and three -tier architecture of sql
processing models for database access data .

munotes.in

Page 78


Enterprise Java
78 6.3.1 Two -tier Architecture:
In the JDBC two -tier architecture model, a Java applet or application talks
directly to the data source. This requires a JDBC driver that can
communicate with the particular data source/database being accessed.
A client sends a request to execute the database or other data source, and
the results of those statements are sent back to the user. The data source
may be located on another machine to which th e user is connected via a
network. This is referred to as a client/server configuration where they can
communicate to each other .

Figure 1: 6.3.1 Two -tier Architecture for Data Access.
6.3.2 Three -tier Architecture:
In Java JDBC is a three -tier archite cture model, commands are sent to a
"middle tier" of services, which then sends the commands to the data
source/database. The data source /database processes the commands and
sends the results back to the middle tier, which then sends them to the
user.
In this three -tier model is very attractive because the middle tier makes it
possible to maintain control over access and the kinds of updates that can
be made to corporate data. One more advantage is that it simplifies the
deployment of java bapplications. Three -tier architecture can provide
performance advantages.

Figure 2: 6.3.2 Three -tier Architecture for Data Access. munotes.in

Page 79


Working with Databases
79 The JDBC API is being used more and more in the middle tier of a three -
tier architecture. In JDBC various features that make JDBC a serve r
technology are its support for connection pooling, distributed transactions.
The JDBC API is also what allows access to a data source/database from
a Java middle tier.
6.4 ACCESSING DATABASE A) Insert Records in Database(MySql):
In this example how to i nsert records in a table using the JDBC
application.
Required Steps:
The following are the steps to create a new Da tabase using JDBC
application:
1. Import the packages : import keywords specify that you include the
packages containing the JDBC classes nee ded for database
programming. Most often, using import java.sql.* will suffice.
2. Register the JDBC driver : Requires that you initialize a driver so
you can open a communications channel with the database.
3. Open a connection : Open() method used in the
DriverManager.getConnection() method to create and open a
Connection object, which represents a physical connection with a
database .
1. Execute a query : execute() method used for an object of type
Statement for building and submitting an SQL statement to insert
records into a desired table.
2. Cleaning up the environment with resources automatically closes the
resources.
Sample Code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertData
{
String DB_URL = "jdbc:mysql://localhost/Umesh";
String USER = "guest";
String PASS = "guest123";
public static void main(String[] args) munotes.in

Page 80


Enterprise Java
80 {
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER,
PASS);
Statemen t stmt = conn.createStatement();
Try
{
// Execute a query
System.out.println("Inserting records into the table...");
String sql = "insert into UserRegistration VALUES (100, 'Umesh',
'Waghmare', 30)";
stmt.executeUpdate(sql);
sql = "inse rt into UserRegistration VALUES (101, 'Shreya', 'Patil', 25)";
stmt.executeUpdate(sql);
sql = "insert into UserRegistration VALUES (102,’Nilima’, 'Adagale',
30)";
stmt.executeUpdate(sql);
sql = "insert into UserRegistration VALUES(103, 'Mimu', 'Mittal', 25)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac InsertData.java
C:\>
When you run InsertDat a, it produces the following result −
C:\>java InsertData
Inserting records into the table...
Inserted records into the table...
C:\>
munotes.in

Page 81


Working with Databases
81 B) Retrieve/Access Records from Database(MySql):
In java JDBC API specify to select/ fetch records from a table using JD BC
Driver/application.
Following are the Required Steps:
The following steps are required to create a new Database using JDBC
application:
1. Import the packages : import keywords that include the packages
containing the JDBC classes needed for database rela ted programming.
E.g import java.sql.*;
2. Open a connection : Open() method used in the
DriverManager.getConnection() method to create a Connection object,
which represents a physical connection with a database .
3. Execute a query : executeQuery() method used as an object of type
Statement for building and submitting an SQL statement to select (i.e.
fetch/access ) records from a table.
4. Extract Data : SQL query is executed successfully , you can
fetch/access records from the table.
5. Clean up the environment : try with resources automatically.
Sample Code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class AccessData
{
String DB_URL = "jdbc:mysql://localhost/ume sh";
String USER = "guest";
String PASS = "guest123";
String QUERY = "SELECT id, first, last, age FROM Registration";
public static void main(String[] args)
{
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER,
PASS);
Stateme nt stmt = conn.createStatement(); munotes.in

Page 82


Enterprise Java
82 ResultSet rs = stmt.executeQuery(QUERY);
try {
while(rs.next())
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.println(", Last: " + rs. getString("last"));
}
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
Execute example as follows :
C:\>javac AccessData.java
C:\>
When you run AccessData, i t produces the following result:
C:\>java AccessData
ID: 100, Age: 30, First: Umesh, Last: Waghmare
ID: 101, Age: 25, First: Shreya, Last: Patil
ID: 102, Age: 30, First: Nilima, Last: Adagale
ID: 103, Age: 25, First: Mimu, Last: Mittal
6.5 THE SERVLET GUI AND DATABASE EXAMPLE: To start with basic concept, let us create a simple table and create few
records in that table as follows −
Create Table
To create the Employees table in TEST database, use the following steps –
Step 1 :
Open a Command Prompt and change to the installation directory as
follows −
C:\> munotes.in

Page 83


Working with Databases
83 C:\>cd Program Files \MySQL \bin
C:\Program Files \MySQL \bin>
Step 2 :
Login to database as follows
C:\Program Files \MySQL \bin>mysql -u root -p
Enter password: ********
mysql>
Step 3 :
Create the table Student in teststudent database as follows −
mysql> use teststudent;
mysql> create table Student (
id int not null,
age int not null,
first varchar (255),
last varchar (255)
);
Query OK, 0 rows affected (0.08 sec)
mysql>
Create Data Records
Finally you create few records in Student table as follows −
mysql> INSERT INTO Student VALUES (100, 30, 'Umesh',
'Waghmare');
Query OK, 1 row affected (0.05 sec)
mysql> INSERT INTO Student VALUES (101, 25, 'Shreya', 'Patil');
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO Student VALUES (102, 30, 'Nilima', 'Adagale');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Student VALUES (103, 28, 'Mimu', 'Mittal');
Query OK, 1 row affected (0.00 sec)
mysql>
Accessing a Database
Here is an example which shows how to access teststudent database using
Servlet.
// Loading required libraries munotes.in

Page 84


Enterprise Java
84 import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class DatabaseAccess extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
// JDBC driver name and database URL
String JDBC_DRIVER = "com.mysql.jdbc.Driver";
String DB_URL="jdbc:mysql://localhost/teststudent";
// Database credentials
String USER = "root";
String PASS = "root";
// Set response content type
response.setConten tType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
out.println(
" \n" +
"" + title + " \n" +
"\n" +
"

" + title + "

\n");
try
{
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL, USER,
PASS);
// Execute SQL query
Statement stmt = conn.createStatement();
String sql; munotes.in

Page 85


Working with Databases
85 sql = "SELECT id, first, last, age FROM Student";
ResultSet rs = stmt.executeQuery(sql);
// Extract data from result set
while(rs.next())
{
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getS tring("last");
//Display values
out.println("ID: " + id + "
");
out.println(", Age: " + age + "
");
out.println(", First: " + first + "
");
out.println(", Last: " + last + "
");
}
out.println("");
// Clean -up environment
rs.close( );
stmt.close();
conn.close();
}
catch(Exception e)
{
//Handle errors for Class.forName
e.printStackTrace();
}
}
}
Now let us compile above servlet and create following entries in web.xml
....

DatabaseAccess
DatabaseAccess

munotes.in

Page 86


Enterprise Java
86
DatabaseAccess
/DatabaseAccess

Now call this servlet using URL http://localhost:8080/DatabaseAccess
which would display following response −
Database Result :
ID: 100, Age: 30, First: Umesh, Last: Waghmare
ID: 101, Age: 25, First: Shreya, Last: Patil
ID: 102, Age: 30, First: Nilima, Last: Adagale
ID: 103, Age: 25, First: Mimu, Last: Mittal
Example of Fetching Result for the given country :
Here, you will learn how to fetch results for the given country. I am
assuming that there is a table as given below:
CREATE TABLE `registeruser` (
`uname` varchar(50) NOT NULL,
`upass` varchar(45) DEFAULT NULL,
`email` varchar (45) DEFAULT NULL,
`country` varchar(45) DEFAULT NULL
);
We are assuming there are many records in this table. In this example, we
are getting the data from the database in servlet and Display on screen.
In this example, we have create three files :
1. index.html
2. Search.java
3. web.xml
1) index.html :
This page gets rollno from the user and forwards this data to servlet which
is responsible to show the records based on the given country.



Enter your Country:
munotes.in

Page 87


Working with Databases
87



2) Search.java :
This is the servlet file which gets the input from the user and maps this
data with the database and prints the record for the match ed data. In this
page, we are displaying the column name of the database along with data,
so we are using the ResultSetMetaData interface.
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Search extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String country =request.getParameter("country");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/teststudent","root","root");
//here teststudent is database name, root is username an d password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from registeruser where country
like +country+");
while(rs.next())
System.out.println(rs.getString(1)+" "+rs.getString(2)+"
"+rs.getString(3));
con.close( );
}
catch(Exception e)
{ munotes.in

Page 88


Enterprise Java
88 System.out.println(e);
}
}
}
3) web.xml file
This is the configuration file which provides information of the servlet to
the container.


Search
Search< /servlet -class>


Search
/servlet/Search


Output:
1) Input Screen

2) Output Screen :

6.7 SUMMARY JDBC is basically used in java programming for creating/implementing
connections betwee n java applications & databases . In Java API JDBC
Driver is a software component that enables java applications to connect
with the database. JDBC is a Java API to conne ct and execute the SQL munotes.in

Page 89


Working with Databases
89 query with the database. JDBC is a part of JavaSE (Java Standard
Edition). JDBC API uses JDBC drivers to connect with the database.
6.6 QUESTIONS 1 What is the use of JDBC?
2 Explain Architecture of JDBC.
3 Explain Two Tier Architec ture.
4 Explain types of JDBC drivers.
5 Explain Three Tier Architecture.
6 Discuss steps to connect java to a database.
7 Design a Employee registration (HTML form) insert records in the
EmployeeDetails table and display all records.
8 Design Result (HTML form) and a servlet program for calculating
student results with grades and display on browser.
6.8 REFERENCE FOR FURTHER READING 1. The Complete Reference -Java Enterprise Editio n (Black Book) ,
Author:Herbert schildt.
2. Java EE 7 The Big Picture by - Dr.Danny Coward Publisher - Oracle
press.
3. Advanced Java by -Balaguruswamy .

*****
munotes.in

Page 90

90 UNIT II
7
REQUEST DISPATCHER
Unit Structure
7.0 Objectives
7.1 RequestDispatcher interface
7.2 Request Methods Dispatcher
7.3 Request Sender’s Request
7.4 Summary
7.5 References
7.6 Questions
7.0 OBJECTIVES The servlet container forms a RequestDis patcher object, which is used as a
cover around a server resource located in a particular path or named. This
link is intended for wrapping servlets, but the servlet container can create
RequestDispatcher items to wrap any type of app.
7.1 REQUESTDISPATCHE R INTERFACE • A RequestDispatcher is an extremely important Java class that allows
you to "include" content in a request / response or to "forward" a
request / response to a resource. As a typical example, a servlet can
use a RequestDispatcher to include or forward a request / response to
a JSP.
• A RequestDispatcher object can forward a client's request to a
resource or include the resource itself in the response to the client. A
resource can be another servlet, an HTML file or a JSP file, and so on.
• You can a lso think of a RequestDispatcher object as a container for
the resource located on a given path given as an argument to the
getRequestDispatcher method.
• To construct a RequestDispatcher object, you can use the
ServletRequest.getRequestDispatcher () method or the
ServletContext.getRequestDispatcher () method. They both do the
same thing, but impose slightly different constraints on the path of the
topic. For the former, it looks for the resource in the same web
application that the invocation servlet belongs to, and the path name
specified can be relative to the invocation servlet. For the latter, the
path name must start with '/' and is interpreted in relation to the root of
the web application. munotes.in

Page 91


Request Dispatcher
91 7.2 METHODS OF THE REQUESTDISPATCHER INTERFACE  public void forw ard (ServletRequest request, ServletResponse
response) throws ServletException, java.io.IOException:
Forwards a request for a servlet to another resource (servlet, JSP file,
or HTML file) on the server.
 public void include (ServletRequest request, Servlet Response
response) throws ServletException, java.io.IOException:
Include the content of a resource (servlet, JSP page, or HTML file) in the
response.


How to get the RequestDispatcher object :
• The getRequestDispatcher () method of the ServletRequest inte rface
returns the RequestDispatcher object.
How to get a RequestDispatcher object :
• RequestDispatcher rs = request.getRequestDispatcher ("hello.html");
rs.forward (request, response);
munotes.in

Page 92


Enterprise Java
92 RequestDispatcher rs = request.getRequestDispatcher ("hello.html");
rs.include (request, response);

7.3 REQUEST THE SENDER'S REQUEST • In this example, we are validating the password entered by the user. If
the password is a servlet, it will forward the request to the
WelcomeServlet; otherwise it will display an error messag e: sorry,
wrong username or password!
In this example, we have created the following files:
 index.html file: to obtain information about the user.
 Access file.java: a servlet class to process the response. If the
password is admin123, it will send the requ est to the welcome servlet.
 WelcomeServlet.java file: a servlet class to display the welcome
message.
 web.xml file: a deployment descriptor file that contains servlet
information.

index.html :

Name: "text" name = "user">
munotes.in

Page 93


Request Dispatcher
93  Password:


Validate.java :
import java.io. *;
import javax.servlet. *;
import javax.servlet.http. *;
Validate public class extend s HttpServlet {
protected void doPost (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType ("text / html; character set = UTF -8");
PrintWriter out = response.getWriter ();
to deal {
String name = request.getParameter ("user");
Password string = request.getParameter ("pass");
if (password.equal ("admin123"))
{
RequestDispatcher rd = request.getRequestDispatcher ("Welcome");
rd.forward (request, response);
} the rest
{
out.printl n (" You entered an incorrect password
");
RequestDispatcher rd = request.getRequestDispatcher ("index.html");
rd.include (request, response);
}
} Long last {
out.close ();
}
}
}
Welcome.java :
import java.io. *;
import javax.servlet. *;
import javax.servlet.http. *;
The public class welcome extends HttpServlet munotes.in

Page 94


Enterprise Java
94 {
protected void doPost (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType ("text / html; character set = UTF -8");
PrintWriter out = response.getWriter ();
to deal
{
out.println ("

Welcome user

");
}
Long last
{
out.close (); }}}
7.4 SUMMARY The RequestDispatcher interface provides the facility of dispatching the
reque st to another resource it may be html, servlet or jsp. This interface
can also be used to include the content of another resource also. It is one
of the ways of servlet collaboration.
7.5 REFERENCES  https://www.javatpoint.com/java -tutorial
 https://www.tutorialspoint.com/java/index.htm
 https://www.geeksforgeeks.org/java/
 https://www.oracle.com/in/java/technologies/java -ee-glance.html
 https://developers.redhat.com/topics/enterprise -java
 https://www.javacodegeeks.com/enterprise -java-tutorials
7.6 QUESTIONS 1. Explain the RequestDispatcher interface with its methods and
diagram.
2. How to get the RequestDispatcher ob ject with syntax.
3. Provide an example to validate the password entered by the user.
*****
munotes.in

Page 95

95 8
COOKIES
Unit Structure
8.1 Introduction
8.1.1 Types of cookies
8.1.2 Where are cookies used?
8.1.3 Servlet cookie methods
8.2. Cookie settings with Servlet
8.3. Where are cookies used?
8.3.1 Applications
8.4 Where are cookies placed?
8.5 Simple example of a servlet cookie
8.6 Summary
8.7 References
8.8 Questions
8.1 INTRODUCTION  Cookies are text files stored on the customer's computer and are saved
for various information tracking purposes. Java Servlet transparently
supports HTTP cookies.
 There are three steps involved in identifying recurring users:
 The server script sends a series of cookies to the browser. For
example, name, age or identification number, etc.
 The browser stores this information on the local machine for future
use.
 The nex t time the browser sends a request to the web server, it will
send the cookie information to the server and the server will use that
information to identify you.
 A servlet will access the cookie via the request.getCookies () request
method which returns an array of Cookie objects.
Some of the common uses of cookies are:
1. Session authentication uses cookies :
2. Personalized response to the customer based on their preferences, for
example, we can set the background color as a cookie in the
customer's browser and then use it to customize the background color
of the response, image, etc. munotes.in

Page 96


Enterprise Java
96

8.1.1 Types of cookies :
There are 2 types of cookies in servlets :
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie :
It is valid for one session only. It is removed ev ery time the user closes the
browser.
Persistent cookie :
It is valid for multiple sessions. It is not removed every time the user
closes the browser. It is removed only if the user logs out or logs out.
Advantage of cookies :
1. The simplest technique for main taining the state.
2. Cookies are stored on the client side.
Disadvantage of cookies :
1. It will not work if cookies are disabled in the browser.
2. Only textual information can be set in the Cookie object.
3. Cookie class
4. javax.servlet.http.Cookieclass provides the f unctionality of using
cookies. Provides many useful methods for cookies.
5. Cookie class constructor Builder Description Cracker() build a biscuit. Cookie (string name, string value) constructs a cookie with a specified name and value.


munotes.in

Page 97


Cookies
97 1.2 How do cooki es work?

By default, each request is considered a new request. In the cookie
technique, we add cookies with the response of the servlet. The cookies
are then stored in the browser cache. Subsequently, if the user submits the
request, the cookie is added with the request by default. Therefore, we
recognize the user as the previous user.
8.1.3 Cookie Servlet Modes :
public void setDomain (string schema)
• This method sets the domain to which the cookie applies, for example
google.com.
public String getDomain ()
• This method gets the domain to which the cookie applies, for example
google.com.
public void setMaxAge (expiration int)
• This method sets the time (in seconds) that must elapse before the
cookie expires.
public int getMaxAge ()
• This method returns th e maximum age of the cookie, specified in
seconds. By default, -1 indicates that the cookie will persist until the
browser is deactivated.
public String getName ()
• This method returns the name of the cookie. The name cannot be
changed after creation.
publ ic void setValue (String newValue)
• This method sets the value associated with the cookie. munotes.in

Page 98


Enterprise Java
98 public String getValue ()
• This method gets the value associated with the cookie.
public void setPath (String uri)
• This method sets the path to which this cookie ap plies.
public String getPath ()
• This method gets the path to which this cookie is applied.
public void setSecure (boolean flag)
• This method sets the Boolean value that indicates whether the cookie
should be sent only over encrypted connections (i.e. SSL) .
public void setComment (purpose of string)
• This method specifies a comment that describes the purpose of a
cookie. The comment is useful if the browser presents the cookie to
the user.
public string getComment ()
• This method returns the comment describ ing the purpose of this
cookie or null if the cookie contains no comments.
8.2 COOKIE SETTINGS WITH SERVLET Setting up cookies with servlets involves three steps:
(1) Creation of a Cookie object :
You call the cookie constructor with a cookie name and a co okie value,
both are strings.
Cookie cookie = new Cookie ("name", "value");
Note that neither the name nor the value must contain spaces or any of the
following characters: [] () =, "/? @:;
(2) Set the maximum age :
Use setMaxAge to specify how long (in se conds) the cookie should be
valid. The following would set a cookie for 24 hours.
cookie.setMaxAge (60 * 60 * 24);
(3) Sending the cookie to the HTTP response headers :
Use response.addCookie to add cookies in the HTTP response header as
follows
response .addCookie (cookie); munotes.in

Page 99


Cookies
99 8.3 WHERE ARE COOKIES USED?  Create a temporary session where the site remembers in some way in
the short term what the user was doing or had chosen from the
requests of the web page, for example:
 Who the user is currently logged into.
 What the user has ordered in an online shopping cart.
 To remember low -security information more permanently, for
example:
 A user's search results preferences.
 What topic did the user browse during the user's last visit?
 For advertising purposes or to impr ove the functionality of a site.
 Identify a user during an e -commerce session.
 To avoid entering your username and password to access the site.
8.3.1 Applications :
 Shopping cart request
 Bank online
 Generation of a visitor's profile
 Generation of a visitor' s profile
 Website monitoring
8.4 WHERE ARE COOKIES PLACED?  By default, all cookies generated are stored on the hard drive of the
user's local computer.
 The locations are different but the cookie format is the same.
 Use the search function to get the cook ie directory.
 It expires after a certain time.
How to create a cookie? :
Cookie ck =new one Cracker("user", "sonoo jaiswal"); // creation of a
cookie object
response.addCookie (ck);// adding cookies in response
How to delete the cookie?
Cookie ck =new one Cracker("Username", ""); // removing the value of
the cookie munotes.in

Page 100


Enterprise Java
100 ck.setMaxAge (0); // change the maximum age to 0 seconds
response.addCookie (ck);// adding cookies in response
How to get cookies?
Cookie ck [] = request.getCookies ();
from(In t i =0; i out.print"
" + ck [i] .getName () + "" + ck [i] .getValue ()); // print the
name and value of the cookie
}
8.5 SIMPLE EXAMPLE OF A SERVLET COOKIE In this example, we are storing the user's name in the cookie object and
accessing it in another servlet. As we all know, that session corresponds to
the particular user. So, if you log in from too many browsers with different
values, you will get a different value.

index.html

Name:



FirstServlet.java
importjava.io. *;
importjavax.servlet. *;
importjavax.servlet.http. *;
public class FirstServlet it extends HttpServlet {
public empty doPost (HttpServletRe quest request, HttpServletResponse
response) {
to deal{
response.setContentType ("text / html");
PrintWriter out = response.getWriter (); munotes.in

Page 101


Cookies
101 String n = request.getParameter ("Username");
out.print"Welcome" + n);
Cookie ck =new one Cracker("one", n ); // creation of a cookie object
response.addCookie (ck);// adding cookies in response
// create the submit button
out.print"

");
out.print"");
out.print"
");
out.close ();
}capture(Exception e) {System.out.println (e);}
}
}
SecondServlet.java
importjava.io. *;
importjavax.servlet. *;
importjavax.servlet.http. *;
public class SecondServlet it extends HttpServlet {
public empty doPost (HttpServletRequest request, HttpServlet Response
response) {
to deal{
response.setContentType ("text / html");
PrintWriter out = response.getWriter ();
Cookie ck [] = request.getCookies ();
out.print"Hello" + ck [0] .getValue ());
out.close ();
} capture(Exception e)
{
System.out.p rintln (e);
}
}
}
8.6 SUMMARY A cookie is a bit of information sent by a web server to a browser that can
later be read back from that browser. When a browser receives a cookie, it
saves the cookie and thereafter sends the cookie back to the server eac h munotes.in

Page 102


Enterprise Java
102 time it accesses a page on that server, subject to certain rules. Because a
cookie's value can uniquely identify a client, cookies are often used for
session tracking.
8.7 REFERENCES  https://www. javatpoint.com/java -tutorial
 https://www.tutorialspoint.com/java/index.htm
 https://www.geeksforgeeks.org/java/
 https://www.oracle.com/in/java/technologies/java -ee-glance.html
 https://developers.redhat.com/topics/enterprise -java
 https://www.javacodegeeks.com/enterprise -java-tutorials
8.8 QUESTIONS 1. Explain the cookies with your use.
2. What types of cookies are there? Provide advantages and
disadvantages of coo kies with their builders.
3. How do cookies work? Explain your methods.
4. Where are cookies used? Give your applications. Explain the syntax
to create and delete the obtained cookies.
5. Provide an example of Cookie.



*****







munotes.in

Page 103

103 9
SESSIONS
Unit Structure
9.1 Introduction
9.1.1 Advantages of stateless nature
9.1.2 Disadvantages of the stateless nature
9.1.3 Solutions
9.2 How the session works
9.2.1 HttpSession interface
9.2.2 How to get the HttpSession object?
9.2.3 Commonly us ed methods of the HttpSession interface
9.2.4 Solution
9.3 Session ID
9.3.1 Session life cycle
9.3.2 Session Monitoring API
9.3.3 Session Monitoring Methods
9.3.4 Session Management API
9.3.5 Example of using HttpSession
9.4 Summary
9.5 References
9.6 Questions
9.1 INTRODUCTION  Session simply means a particular time interval.
 Session monitoring it is a way to maintain the state (data) of a user.
Also known as servlet session management.
 The HTTP protocol is stateless, so we need to maintain state thro ugh
session tracking techniques. Each time the user requests the server,
the server treats the request as a new request. Therefore, we need to
maintain a user's status to recognize a particular user.
 HTTP is stateless, which means that each request is trea ted as the new
request.
 All requests and responses are independent. But sometimes it is
necessary to monitor customer activity on multiple requests. For
example. When a user logs into your website, regardless of which
web page they visit after logging in, their credentials will remain on
the server until they log off. Then this is handled by creating a
session.
 The session is used to store everything we can get from the client of
all the requests the client makes. munotes.in

Page 104


Enterprise Java
104 9.1.1 Advantages of stateless nature :
 Keep s the protocol simple and straightforward
 Consume fewer resources on the web server.
 Can admit simultaneous visitors.
9.1.2 Disadvantages of the stateless nature :
 The increased overhead required a new connection to be created with
each request.
 The inabili ty to track a single visitor crossing a website.
 The web server cannot automatically accept the browser request with
a particular session.
9.1.3 Alternative solutions :
Web applications have used several techniques to circumvent HTTP
stateless operations:
1. The client is identified each time it makes a request and the server
stores and retrieves data related to that client - Sessions
2. The server sends the data to the client and forces the client to return
them at each request made - Cookies
9.2 HOW THE SESSION WORKS

 The concept behind the session is that, whenever a user starts using
our application, we can save unique identifying information about
him, in an object available throughout the application, until it is
destroyed. So wherever the user goes, we wil l always have his
information and we can always manage which user is doing what.
Whenever a user wants to exit your application, destroy the object
with its information. munotes.in

Page 105


Sessions
105  On the client's first request, the web container generates a unique
session ID and ret urns it to the client with a response. This is a
temporary session created by the web container.
 The client returns the session ID with each request. It makes it easier
for the web container to identify where the request is coming from.
 The web container u ses this ID, finds the session that matches the ID,
and associates the session with the request.
9.2.1 HttpSession interface :

9.2.2 How to get the HttpSession object? :
The HttpServletRequest interface provides two methods to get the
HttpSession object:
publicHttpSessiongetSession ():
Returns the current session associated with this request or, if the request
does not have a session, create one.
publicHttpSessiongetSession (boolean creation):
Returns the current HttpSession associated with this request or, if there is
no current session and create is true, it returns a new session.
9.2.3 Commonly used methods of the HttpSession interface :
public string getId ():
Returns a string that contains the unique identifier value.
long public getCreationTime ():
Retu rns the time this session was created, measured in milliseconds since
midnight on January 1, 1970 GMT.

munotes.in

Page 106


Enterprise Java
106 public long getLastAccessedTime ():
Returns the last time the client sent a request associated with this session,
as the number of milliseconds since m idnight January 1, 1970 GMT.
public void invalidate ():
Replace this session and then unlink all objects linked to it.
In a typical stateless protocol transaction, the client:
1. Establishes a connection to the web server
2. Submit a request
3. Get an answer
4. Close connection
Because a persistent connection is not maintained between such requests,
the connection from the web servers to the client is broken after the
connection is closed. Disconnection between a client and the web server
entails the following limitat ions:
• If the web server requires client authentication, for example a client
needs to log in, the client needs to log in again on each request. The
web server does not realize that it has already authenticated this client
because the connection between the two has been lost.
• The web server cannot distinguish one client from another.
9.2.4 Solution :
• Establish a permanent connection between the client and the web
server.
• Visitor's web browser requests.
• The web server assigns session IDs to each request.
• The w eb server identifies visitors through virtual connections called
sessions.
9.3 SESSION ID A session ID is a unique number that a website server assigns to a specific
user during that user's visit (session). The session ID can be stored as a
cookie, form f ield or URL (Uniform Resource Locator). Some web servers
generate session IDs simply by incrementing static numbers. However,
most servers use algorithms that involve more complex methods, such as
taking into account the date and time of the visit along wi th other variables
defined by the server administrator.
munotes.in

Page 107


Sessions
107 9.3.1 Session life cycle :
• A visitor, using a web browser, requests a resource from the web
server.
• The web server offers the authentication form which causes the
visitor's web browser to display a lo gin form.
• The web browser returns the username and password, which are then
returned to the web server.
• The web server returns a valid session ID to uniquely identify this
visitor.
• The visitor's web browser sends any number of requests to the web
server. T he web server identifies users based on session IDs.
• The visitor closes the browser without explicitly logging out.
9.3.2 Session Monitoring API :
• The session monitoring API is based on the first four methods. This is
to help the developer minimize the over head of session monitoring.
This type of session tracking is provided by the underlying
technology. Let's take the example of the Java servlet. The servlet
container handles session tracking activity and the user does not need
to explicitly do this using J ava servlets. This is the best of all
methods, because all handling and errors related to session monitoring
will be handled by the container itself.
• Each server client will be mapped to a javax.servlet.http.HttpSession
object. Java servlets can use the se ssion object to store and retrieve
Java objects during the session. Session monitoring is best when
implemented using the session monitoring API.
• A session is a collection of HTTP requests, over a period of time. A
session is user specific and a new sessio n is created for each user to
track all user requests. In the servlet session, tracing can be used to
track user state. Session monitoring is also known as session
management, it is a mechanism used to maintain a user's state within a
set of requests for a period of time. We can say that session
monitoring is a means of keeping track of session data. This data
represents the data that is transferred in a session.
9.3.3 Session Monitoring Methods :
• User authentication : This is the very common way that the use r can
provide authentication credentials from the login page and then we
can pass the authentication information between the server and the
client to maintain the session. This is not a very effective method
because it will not work if the same user is log ged in from different
browsers. munotes.in

Page 108


Enterprise Java
108 • HTML hidden field : We can create a unique hidden field in the
HTML and when the user starts browsing we can set its unique value
for the user and keep track of the session. This method cannot be used
with bindings because it requires the form to be submitted each time a
client -to-server request is made with the field hidden. Also, it's not
safe because we can get the hidden field value from the HTML source
and use it to hack the session.
• URL rewrite : We can add a session iden tifier parameter with each
request and response to keep track of the session. This is very tedious
because we have to keep track of this parameter in every response and
make sure it doesn't collide with other parameters.
• Cookies : Cookies are small pieces o f information sent by the web
server in the response header and stored in the browser's cookies.
When the client makes an additional request, it adds the cookie to the
request header and we can use it to track the session. We can maintain
a session with co okies, but if the client disables cookies, it will not
work.
9.3.4 Session Management API :
The Session Management API builds on the previous methods for session
monitoring. Some of the major disadvantages of all of the above methods
are:
1. Most of the time we don't just want to keep track of the session, we
need to store some data in the session that we can use in future
requests. This will require a lot of effort if we try to implement it.
2. All of the above methods are not complete by themselves, they will
not all work in a particular scenario. So we need a solution that can
use these session tracking methods to provide session management in
all cases.
9.3.5 Example of using HttpSession :
In this example, we're setting the session -scope attribute in one servl et and
getting that value from the session -scope in another servlet. To set the
attribute within the session, we used the setAttribute () method of the
HttpSession interface and to get the attribute we used the getAttribute
method.
index.html :


User:

Password:


Validate.java :
import java.io. *; munotes.in

Page 109


Sessions
109 importjavax.servlet. *;
importjavax.serv let.http. *;
Public class ValidateextendsHttpServlet
{
protected void doPost (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType ("text / html; character set = UTF -8");
String name = request.getParameter ("user");
String pass = request.getParameter ("pass");
if (pass.equal ("1234"))
{
HttpSessionsession = request.getSession (); session.setAttribute ("user",
name); response.sendRedirect ("Welcome");
}}}
Welcome.java :
import java.io. *;
importjavax.servlet. *;
importjavax.servlet.http. *;
public class WelcomeextendsHttpServlet
{
protected void doGet (HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType ("text / html; character set = UTF -8");
PrintWriterout = response.getWriter ();
HttpSessionsession = request.getSession ();
String user = (String) session.getAttribute ("user"); out.println ("Hello" +
user);
}}
9.4 SUMMARY The session object is used to record the acces s status of each client within
the session scope, so that it is easy to track the operation status of each
client, and the information stored in the session can obtain the valid data
of these sessions when the browser makes subsequent requests.
In the jsp page, you can use the session object directly (built -in object of
jsp), or you can go back to the session object through pageContext. munotes.in

Page 110


Enterprise Java
110 getSession () or request. getSession. Session can save user information and
implement shopping cart and other functions.
9.5 REFERENCES  https://www.javatpoint.com/java -tutorial
 https://www.tutorialspoint.com/java/index.htm
 https://www.geeksforgeeks.org/java/
 https://www.oracle.com/in/java/technologies/java -ee-glance.html
 https://developers.redhat.com/topics/enterprise -java
 https://www.javacodegeeks.com/enterprise -java-tutorials
9.6 QUESTIONS 1. Define the sessions. Explain sessi on monitoring with the advantages
and disadvantages of the stateless nature of the HTTP protocol.
2. How does the session work? Explain with the diagram.
3. How does the HTTP session work? Explain with the diagram.
4. Explain the steps for the stateless protocol tr ansaction with its
limitations and solutions.
5. Define the session ID. Explain the session life cycle.
6. What is the Session Monitoring API? Provide methods for session
monitoring.
7. Provide an example of an HTTP session to validate the user's
password.

*****
munotes.in

Page 111

111 10
WORK WITH FILES
Unit Structure
10.1 File upload
10.2 Downloading files
10.3 Servlet annotations
10.4 References
10.5 Questions
10.6 Summary
10.1 FILE UPLOAD You can use a servlet with an HTML form tag to allow users to upload
files to the server. An uploaded file can be a text file or an image file or
any document.
Creating a file upload form
The following HTM code below creates an upload form. The following
are the important points to note:
 The form method attribute must be set to POSTmethod and t he GET
method cannot be used
 The form enctype attribute must be set to multipart / form -data.
 The module action attribute should be set to a servlet file that would
handle uploading files to the backend server. The following example
uses the UploadServlet servlet to upload the file.
 To upload a single file, you need to use a single tag with
attribute type = "file". To allow multiple file uploads, include more
than one input tag with different values for the name attribute. The
browser associates each of them with a Browse button.

File upload module

Upload file:


Select a file to upload:




munotes.in

Page 112


Enterprise Java
112

This will display the following output wh ich will allow you to select a file
from the local PC and when the user clicks "Upload File" the form will be
sent along with the selected file.

Write backend servlet
Below is the UploadServlet servlet that would take care of accepting the
uploaded file and storing it in the /
webapps / data directory. This directory name can also be added using an
external setting such as a context -param element in web.xml as follows:

....

L ocation to store the uploaded file
upload file

c: \ apache -tomcat -5.5.29 \ webapps \ data \


....

Below is the UploadServlet source code, which can h andle uploading
multiple files at the same time. Before proceeding, you should make sure
of the following:
 The following example depends on FileUpload, so make sure you
have the latest version of the commons -fileupload.xxjar file in your
classpath. You can download it
from https://commons.apache.org/fileupload/ . munotes.in

Page 113


Work with Files
113  FileUpload depends on Commons IO, so make sure you have the
latest version of the commons -io-xxjar file in your classpath. You can
download i t from https://commons.apache.org/io/ .
 When testing the following example, a file smaller than maxFileSize
must be loaded; otherwise the file will not be loaded.
 Make sure you have created the c: \ temp and c: \ apache -tomcat8.0.28
\ webapps \ data directories well in advance.
// Import the necessary Java libraries
import java.io. *;
import java.util. *;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpS ervlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFile ItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.output. *;
The UploadServlet public class extends HttpServlet {
isMultipart private boolean;
FilePath private string;
private int maxFileSize = 50 * 1024;
private int maxMemSize = 4 * 1024;
private archive file;
public void init () {
// Get the location of the file where it would be stored.
filePath = getServletContext (). getInitParameter ("file upload");
}
public void doPost (HttpServletReque st request, HttpServletResponse
response)
throw ServletException, java.io.IOException {
// Check that we have a request to upload the file
isMultipart = ServletFileUpload.isMultipartContent (required);
response.setContentType ("text / html"); munotes.in

Page 114


Enterprise Java
114 java.io. PrintWriter out = response.getWriter ();
if (! isMultipart) {
out.println ("");
out.println ("");
out.println (" Loading servlet ");
out.println ("");
out.println ("");
out.println ("

No files uploaded

");
out.println ("");
out.println ("");
Return;
}
DiskFileItemFactory factory = new DiskFileItemFactory ();
factory.setSizeThreshold (maxMemSize); // maximum size to be stored in
memory factory.setRepository (new File ("c: \\ temp")) ; // Location to
save data larger than maxMemSize.
ServletFileUpload upload = new ServletFileUpload (factory); // Create a
new file upload controller
upload.setSizeMax (maxFileSize); // maximum size of the file to upload.
to deal {
List fileItems = uploa d.parseRequest (required); // Parse the request to get
the elements of the file.
Iterator i = fileItems.iterator (); // Process the elements of the uploaded file
out.println ("");
out.println ("");
out.println (" Loading servlet </tit le>"); <br> out.println ("</head>"); <br> out.println ("<body>"); <br> while (i.hasNext ()) { <br> FileItem fi = (FileItem) i.next (); <br> if (! fi.isFormField ()) { <br> // Get the parameters of the uploaded file <br> String fieldName = fi.getFieldName (); <br> String filename = fi.g etName (); <br> String contentType = fi.getContentType (); <br> isInMemory = fi.isInMemory (); munotes.in</p> </div> <div class="post"> <h2>Page 115</h2> <p> <br> Work with Files <br>115 long sizeInBytes = fi.getSize (); <br> // Write the file <br> if (fileName.lastIndexOf (" \\")> = 0) { <br> file = new file (file path + file name.substring (file name.lastIndexOf <br>("\\"))); <br> } the rest { <br> file = new file (file path + file name.substring (file name.lastIndexOf <br>("\\") + 1)); <br> } <br> fi.write (file); <br> out.println ("Uploaded file name:" + file name + "<br>"); <br> } <br> } <br> out.println ("</body>"); <br> out.println ("</html>"); <br> } catc h (ex exception) { <br> System.out.println (es); <br> }} <br> public void doGet (HttpServletRequest request, HttpServletResponse <br>response) <br> throw ServletException, java.io.IOException { <br> throw a new ServletException ("GET method used with" + <br> getClass () .getName () + ": POST method is required."); <br> }}} <br>10.2 DOWNLOADING FILES In this example, we are creating three files: <br> index.html <br> DownloadServlet.java <br> web.xml <br>index.html <br>This file provides a link to download the file. <br><a href="servlet/DownloadServlet"> download the jsp file </a> <br>DownloadServlet.java <br>importjava.io. *; <br>import javax.servlet.ServletException; munotes.in</p> </div> <div class="post"> <h2>Page 116</h2> <p> <br> Enterprise Java <br>116 importjavax.servlet.http. *; <br>public class DownloadServlet extends HttpServlet { <br>public void doGet (HttpServletRequest request, HttpServletResponse <br>response) throws ServletException, IOException { <br>response.setContentType ("text / html"); <br>PrintWriter out = response.getWriter (); <br>String filename = "home.jsp"; <br>String file path = "e: \\"; <br>response.setContentType ("APPLICATION / OCTETO -STREAM"); <br>response.setHeader (" Content -Disposition", "attachment; filename = \" "+ <br>filename +" \ ""); <br>FileInputStream fileInputStream = new FileInputStream (file path + file <br>name); <br>In t I; <br>weather ((i = fileInputStream.read ())! = -1) { <br>out.write (i); <br>} <br>fileInputStream.close (); <br>out.close (); <br>}} <br>web.xml file <br><web -app> <br><servlet> <br><servlet -name> DownloadServlet </servlet -name> <br><servlet -class> DownloadServlet </servlet -class> <br></servlet> <br><mapping -servlet> <br><servlet -name> DownloadServlet </servlet -name> <br><url-pattern> / servlet / DownloadServlet </url -pattern> <br></servlet -mapping> <br></web -app> <br>10.3 SERVLET ANNOTATIONS  Servlet uses the deployment descriptor (web.xml file) to deploy the <br>application to a web server. Servlet API 3.0 introduced a new package <br>called javax.servlet.annotati on. Provides annotation types that can be <br>used to annotate a servlet class. If you use annotation, the deployment munotes.in</p> </div> <div class="post"> <h2>Page 117</h2> <p> <br> Work with Files <br>117 descriptor (web.xml) is not required. But you should be using <br>Tomcat7 or any later version of Tomcat. <br> Annotations can override the equivalent XML configuration in the <br>web deployment descriptor file (web.xml), such as the servlet <br>declaration and servlet mapping. Servlet containers will process the <br>classes noted at the time of deployment. The types of annotations <br>introduced in Servlet 3.0 are: Sr.No. Annotation and description 1 @WebServlet: Declare a servlet. 2 @WebInitParam: To specify an initialization parameter. 3 @WebFilter: Declare a servlet filter. 4 @WebListener: To declare a WebListener 5 @HandlesTypes: Declare the types of classes th at a <br>ServletContainerInitializer can handle. 6 @HttpConstraint: This annotation is used within the <br>ServletSecurity annotation to represent security <br>restrictions that will apply to all HTTP protocol methods <br>for which a corresponding HttpMethodConstraint <br>element is NOT produced within the ServletSecurity <br>annotation. 7 @HttpMethodConstraint: This annotation is used within the ServletSecurity annotation to represent security restrictions on specific HTTP protocol messages. 8 @MultipartConfig: An annotation that can be specified in a Servlet class, indicating that Servlet instances expect requests that conform to the multipart / form-data MIME type. 9 @ServletSecurity: This annotation is used in a Servlet implementation class to specify the security restrictions that a Servlet container must apply on HTTP protocol messages. <br>10.4 REFERENCES  https://www.javatpoint.com/java -tutorial <br> https: //www.tutorialspoint.com/java/index.htm <br> https://www.geeksforgeeks.org/java/ <br> https://www.oracle.com/in/java/technologie s/java -ee-glance.html <br> https://developers.redhat.com/topics/enterprise -java <br> https://www.javacodegeeks.com/ente rprise -java-tutorials <br> munotes.in</p> </div> <div class="post"> <h2>Page 118</h2> <p> <br> Enterprise Java <br>118 10.6 SUMMARY <br> <br> <br>10.5 QUESTIONS 1. Take an example to upload a file. <br>2. Take an example to download a file. <br>3. Explain the different servlet annotations <br>***** <br>munotes.in</p> </div> <div class="post"> <h2>Page 119</h2> <p> 113 11 <br>NON-BLOCKING <br>Unit Structure <br>11.1 Introduction to I / O <br>11.1.1 Why NIO? <br>11.2 Stream against blocks <br>11.3 Integrated I / O integrated <br>11.4 I / O. blocking and non -blocking <br>11.5 Read from a file <br>11.5.1 Write to file <br>11.6 Listeners <br>11.7 Steps to im plement WriteListener <br>11.8 Steps to implement ReadListener <br>11.9 Summary <br>11.10 References <br>11.11 Questions <br>11.1 INTRODUCTION TO I / O  I / O, or input / output, refers to the interface between a computer and <br>the rest of the world, or between a single progra m and the rest of the <br>computer. It is such a crucial element of any computer system that <br>most of any I / O is built into the operating system. Individual <br>programs generally do most of the work for them. <br> In Java programming, I / O has until recently been do ne using a flow <br>metaphor. All I / O is considered to be moving individual bytes, one <br>at a time, through an object called Stream. Stream I / O is used to <br>contact the outside world. It is also used internally, to convert objects <br>to bytes and then back to obj ects. <br> NIO has the same function and purpose as the original I / O, but uses <br>a different metaphor: block I / O. As you will learn in this tutorial, <br>block I / O can be much more efficient than streaming I / O. <br>11.1.1 Why NIO? : <br>NIO was created to allow Java p rogrammers to implement high -speed I / <br>O without having to write custom native code. NIO shifts more time -<br>consuming I / O tasks (that is, buffering and flushing) to the operating <br>system, allowing for a noticeable increase in speed. <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 120</h2> <p> <br> Enterprise Java <br>114 11.2 STREAM AGAINST BL OCKS  The most important distinction between the original I / O library <br>(found in java.io. *) and NIO has to do with how data is packaged and <br>transmitted. As mentioned earlier, the original I / O takes care of the <br>data in streams, while the NIO takes care o f the data in chunks. <br> A flow -oriented I / O system handles data one at a time. An input <br>stream produces one byte of data and an output stream consumes one <br>byte of data. It is very easy to create filters for the transmitted data. It <br>is also relatively easy to chain multiple filters together so that each <br>plays its part in a unique and sophisticated processing mechanism. On <br>the other hand, streaming -oriented I / O is usually quite slow. <br> A block -oriented I / O system manages the data in blocks. Each <br>operation p roduces or consumes a block of data in a single step. The <br>data processing by the block can be much faster than the byte <br>processing (transmitted). But block -oriented I / O lacks the elegance <br>and simplicity of flow -oriented I / O. <br>11.3 INTEGRATED I / O INTEG RATED  The original I / O package and NIO have been well integrated into <br>JDK 1.4. java.io. * was redeployed using NIO as a base, so you can <br>now take advantage of some NIO features. For example, some of the <br>classes in the java.io package. * contain methods f or reading and <br>writing data in blocks, leading to faster processing even on more <br>flow-oriented systems. <br> You can also use the NIO library to implement standard I / O <br>functions. For example, you can easily use I / O blocks to move data <br>one byte at a time. Bu t as you will see, NIO also offers many benefits <br>that are not available in the original I / O package. <br>11.4 IO BLOCKING AND NON -BLOCKING  Various Java I / O streams are blocked. This means that when a thread <br>calls alight() or write(), that thread is blocked until there is no data to <br>read or until the data is completely written. The thread can't do <br>anything else in the meantime. <br> Java NIO's non -blocking mode allows a thread to request to read data <br>from a channel and get only what is currently available, or not hing, if <br>no data is currently available. Instead of getting stuck until the data is <br>available for reading, the thread can continue with something else. <br> The same goes for non -blocking writing. A thread may request some <br>data to be written to a channel, but n ot wait for it to be fully written. <br>The thread can continue and do something else in the meantime. <br> Whereas threads spend their idle time when they aren't blocked during <br>I / O calls, they are generally doing I / O on other channels in the munotes.in</p> </div> <div class="post"> <h2>Page 121</h2> <p> <br> Non-Blocking <br>115 meantime. That is, a single thread can now handle multiple input and <br>output channels. <br>11.5 READ FROM A FILE  If we were using the original I / O, we would simply create a <br>FileInputStreamand read it. In NIO, however, things work a little <br>differently: first we get aChannel obj ect of FileInputStreamand then <br>use that channel to read the data. <br> Whenever you perform a read operation on a NIO system, you are <br>reading from a channel, but not reading directly from a channel. Since <br>all data ultimately resides in the buffer, it is read fr om a channel to a <br>buffer. <br> So, reading from a file involves three steps: (1) getting the Channel <br>from FileInputStream; (2) create theBumper; and (3) reading <br>theCannel to Bumper. Now, let's see how it works. <br>Three simple steps: <br>Our first step is to get a cha nnel. We take the channel <br>fromFileInputStream: FileInputStream fin = new FileInputStream ("readandshow.txt"); FileChannel fc = fin.getChannel (); <br>The next step is to create a buffer: ByteBuffer buffer = ByteBuffer.allocate (1024); <br>And finally, we ne ed to read from channel to buffer, as shown here: fc.read (buffer); <br>11.5.1 WRITE TO FILE Writing to a file in NIO is similar to reading from one. Let's start by <br>getting a channel from toFileOutputStream: FileOutputStream fout = new FileOutputStream ("writesomebytes.txt"); FileChannel fc = fout.getChannel (); munotes.in</p> </div> <div class="post"> <h2>Page 122</h2> <p> <br> Enterprise Java <br>116 Our next step is to create a buffer and insert data into it; in this case the <br>data will be taken from a named arrayMessage A containing the ASCII <br>bytes for the string "Some bytes". ByteBuffer buff er = ByteBuffer.allocate (1024); <br> for (int i = 0; i <message.length; ++ i) { <br> buffer.put (message [i]); <br>} <br>buffer.flip (); <br> Our last step is to write to the buffer: fc.write (buffer); <br>11.6 LISTENERS Java EE provides non -blocking I / O support for servlet s and filters when <br>processing requests in asynchronous mode. The following steps <br>summarize how to use non -blocking I / O to process requests and write <br>responses within the service's methods. <br> Put the request in asynchronous mode as described in Asynchronous <br>Processing. <br> Get an inflow and / or outflow from the request and response objects <br>in the service method. <br> Assign a read listener to the input stream and / or a write listener to <br>the output stream. <br> Process the request and response within the listener's callb ack <br>methods <br>Non-blocking I / O support in javax.servlet.ServletInputStream Method Description void setReadListener (ReadListener rl) Associate this input stream with a listener that contains callback methods to read the data asynchronously. Provide the listener as an anonymous class or use another mechanism to pass the input stream to the read listener. boolean isReady () Returns true if the data can be read without blocking. munotes.in</p> </div> <div class="post"> <h2>Page 123</h2> <p> <br> Non-Blocking <br>117 boolean isFinished () Returns true when all data has been read. Non-blocking I / O support in javax.servlet.ServletOutputStream Method Description void setWriteListener (WriteListener wl) Associate this output stream with a listener that contains callback methods for writing data asynchronously. Provide the write listener as an anonymous class or use another mechanism to pass the output stream to the write listener boolean isReady () Returns true if the data can be <br>written without locks. Listening interfaces for non -blocking I / O support Interface methods Description Read Listener void onDataAvailable () <br>void suAllDataRead () <br>void onError <br>(Throwable t) TO ServletInputStream The <br>instance calls these methods <br>on its listener when data is <br>available to read, when all <br>data has been read, or when <br>an error occurs. Write Listener void onWritePossible () void onError (Throwable t) TO ServletOutputStream The instance calls these methods in its listener when it can write data without blocking or when an error occurs. <br>11.7 S TEPS TO IMPLEMENT WRITELISTENER 1. In the Projects tab, right -click on your project and say Html5 and <br>Servlet 3.1 and select New> Other. <br> munotes.in</p> </div> <div class="post"> <h2>Page 124</h2> <p> <br> Enterprise Java <br>118 2. In the New File dialog box, complete the following steps on the <br>Choose File Type page: <br>a. Select Java in Categories. <br>b. Select Java Class in File Types. <br>c. Click Next. <br> <br>3. On the New Java Class page , do the following: <br>a. Pay in Write ListenerImpl as the name of the class. <br>b. Pay in com.example as the package name. <br>c. Click Finish. <br> <br>4. Import the following packages: <br>Import java.io.IOException; <br>importjava.util.Queue; munotes.in</p> </div> <div class="post"> <h2>Page 125</h2> <p> <br> Non-Blocking <br>119 importjavax.servlet.AsyncContext; <br>importjavax.s ervlet.ServletOutputStream; <br>import javax.servlet.WriteListener; <br>5. Modify the class to implement the Write Listener Interface. <br>The public class WriteListenerImpl implements WriteListener { <br>6. Declare the following variables: <br>ServletOutputStreamprivateoutput=null ; <br>privatequeue=null; <br>private AsyncContext context = null; <br> <br>7. Add a constructor to the class: <br>WriteListenerImpl (ServletOutputStream s os, Queue q, AsyncContext c) { <br>output=sos; <br>tail=q; <br>context = c; } <br> <br>8. Add the onWritePossible () method: <br>publicvoidonWritePossi ble()throwsIOException{ <br>while (queue.peek ()! = null && output.isReady ()) <br>Datastring= (String)queue.poll (); <br> output.print (data); munotes.in</p> </div> <div class="post"> <h2>Page 126</h2> <p> <br> Enterprise Java <br>120 } <br> if (queue.peek () == null) { <br> context.com complete (); <br> }} <br> <br>9. Add the onError method. <br>public void onError (final Thro wable t) { <br> context.complete (); <br>t.printStackTrace (); } <br> <br>11.8 STEPS TO IMPLEMENT READLISTENER Perform the following steps to implement the ReadListenerImpl class: <br>1. On the Projects tab, right -click Html5 and Servlet3.1 and select New> <br>Other. munotes.in</p> </div> <div class="post"> <h2>Page 127</h2> <p> <br> Non-Blocking <br>121 <br> <br>2. In the New File dialog box, complete the following steps on the <br>Choose File Type page: <br>a. Select Java in Categories. <br>b. Select Java Class in File Types. <br>c. Click Next. <br>3. On the New Java Class page, do the following: <br>a. Pay in ReadListenerImpl as the name of the class. <br>b. Pay in com.e xample as the package name. <br>c. Click Finish. <br>4. Import the following packages: <br>import java.io.IOExc eption; import java.util.Queue; <br>import java.util.concurr ent.LinkedBlockingQueue; import <br>javax.servlet.AsyncContext; import jav ax.servlet.ReadListener; import <br>javax .servlet.ServletInputStream; import <br>javax.serv let.ServletOutputStream; import <br>javax.Lxistepnervlet.Write.Write .HttpServletResponse; <br>5. Modify the class to implem ent the Read Listener Interface: <br>The public ReadListenerImpl class implements ReadListener <br> <br> munotes.in</p> </div> <div class="post"> <h2>Page 128</h2> <p> <br> Enterprise Java <br>122 6. Decl are the following variables: <br>private entry ServletInputStream = null; Private HttpServletResponse res <br>= null; Private AsyncContext ac = null; private queue queue = new <br>LinkedBlockingQueue (); <br> <br>7. Add a constructor to the class: <br>ReadListenerImpl (ServletInputS treamin, ttpServletResponser, <br>AsyncContext c) {input = in; re = r; ac = c; } <br> <br>8. Add the onDataAvailable () method: <br>public void onDataAvailable () throws IOException {System.out.println <br>("Dataisavailable"); <br>StringBuilder sb = new StringBuilder (); int len = -1; byte b [] = new byte <br>[1024]; while (input.isReady () && (len = input.read (b))! = -1) {String <br>data = new String (b, 0, len); sb.append (data); } queue.add (sb.toString <br>()); } <br> munotes.in</p> </div> <div class="post"> <h2>Page 129</h2> <p> <br> Non-Blocking <br>123 9. Añade el onAllDataRead ()method: <br>public void onAllDataRead () throws IO Exception {System.out.println <br>("All data is read"); // now all data has been read, set a WriteListener to <br>write the output ServletOutputStream = res.getOutputStream (); <br>WriteListener writeListener = new WriteListenerImpl (output, queue, ac); <br>output.setWrit eListener (writeListener);} <br> <br>10. Add the onError method. : <br>public void onError (final Throwable t) {ac.complete (); t.printStackTrace <br>(); } <br> <br>After ServletInputStream.setReadListener is called, Read Listener in <br>DataAvailablecalled immediately if there is data to read. Otherwise, it is <br>invoked when the data is ready. When all the data has been read,Read <br>Listener establishes a Write Listener to write data in non -blocking mode. <br>11.9 SUMMARY Java NIO's non -blocking mode enables a thread to request reading data <br>from a channel, and only get what is currently available, or nothing at all, <br>if no data is currently available. Rather than remain blocked until data <br>becomes available for reading, the thread can go on with something else. <br> munotes.in</p> </div> <div class="post"> <h2>Page 130</h2> <p> <br> Enterprise Java <br>124 11.10 REFERENCES  https://www.javatpoint.com/java -tutorial <br> https://www.tutorialspoint.com/java/index.htm <br> https://w ww.geeksforgeeks.org/java/ <br> https://www.oracle.com/in/java/technologies/java -ee-glance.html <br> https://de velopers.redhat.com/topics/enterprise -java <br> https://www.javacodegeeks.com/enterprise -java-tutorials <br>11.11 Questions 1. Explain I / O and NIO. Differentiate between flows and blocks. <br>2. Explain embedded I / O with the difference between blocking and <br>non-blocking I / O. <br>3. How to read and write files? Give an example. <br>4. Tell listeners how to read and write a file. <br>5. Explain the steps to implement WriteListener. <br>6. Explain the steps for ReadListener. <br> <br> <br>***** <br> <br>munotes.in</p> </div> <div class="post"> <h2>Page 131</h2> <p> 125 UNIT III <br>12 <br>INTRODUCTION TO JAVA SERVER <br>PAGES <br>Unit Structure <br>12.0 Objectives <br>12.1 Introduction to Java Server Pages <br>12.2 Why use Java Server Pages? <br>12.3 Disadvantages of JSP <br>12.4 JSP v/s Servlets <br>12.5 Lifecycle of a JSP Page <br>12.6 How does a JSP fu nction? <br>12.7 How can a JSP Program be executed? <br>12.8 Directory Structure of JSP <br>12.9 Summary <br>12.10 List of References <br>12.11 Questions <br>12.0 OBJECTIVES After going through this chapter, you will: <br> Understand the basics of Java Server Pages technology <br> Learn the advantages and disadvantages of JSP <br> Differentiate between JSP and Servlets <br> Understand lifecycle of a JSP program <br> Learn how to execute a JSP program <br>12.1 INTRODUCTION TO JAVA SERVER PAGES Java Server Pages (JSP), a server side technology, which is a pa rt of Java <br>EE framework, is used for creating dynamic web applications in a very <br>simple yet powerful way. JSP technology allows you to develop JSP pages <br>which are text based documents that processes a request and generates a <br>response. It has access to the powerful enterprise Java API including the <br>JDBC API and hence can be used to access enterprise databases. <br>A JSP Page consists of both static and dynamic content. The static content <br>can be written using plain HTML or XML and dynamic content can be <br>written either using the regular java style of programming embedded in <br>specific elements or using the tag style approach. This eliminates the need <br>of writing multiple println statements that generate HTML like in Servlets. munotes.in</p> </div> <div class="post"> <h2>Page 132</h2> <p> <br> Enterprise Java <br>126 JSP provides developers with the ability to cleanly separate the application <br>logic from the presentation logic. In other words, JSP can easily <br>differentiate the coding in the view layer and application logic layer. <br>Hence any requirement changes that is needed to be done in the look and <br>feel of t he web application can very easily be done as it would require <br>changes only in the HTML part of code and not the logical part written in <br>java, thus eliminating the need to recompile the entire web application <br>again. <br>It also supports unified expression lan guage (UEL) to access server <br>objects without having explicit need to declare them. <br>The file extension for JSP pages is .jsp <br>12.2 WHY USE JAVA SERVER PAGES JSP has the following benefits: <br>1. Nobody can borrow the code : <br>Since JSP page are written, runs and r emains on the server, nobody can <br>copy the logic written in a jsp page even if they wanted to. Thus, security <br>of the code is maintained. <br>2. Faster loading of pages : <br>Response page customization as requested by the user is done at the server <br>side itself thus no extra code or content is sent to the client side resulting <br>in faster loading of pages. <br>3. No Browser compatibility issues : <br>Since JSP runs on the server side, the developer ends up sending standard <br>HTML to the user browser. This largely eliminates cross browser <br>compatibility issues. <br>4. JSP Support : <br>JSP is supported by a number of Web Servers. Built -in Support for JSP is <br>available in Java Web Server from Oracle. <br>5. Compilation : <br>In JSP technology, each JSP page is compiled into executable code the <br>first ti me it is requested and invokes the resulting code directly on all <br>subsequent requests. When coupled with a persistent JVM, this allows the <br>server to process request to JSP pages much faster. <br>6. Similarity to HTML : <br>A JSP page looks a lot like a HTML or XML page except for the business <br>logic written either in scripting elements or JSP tags or both. Writing the <br>business logic in JSP tags brings consistency to the coding style used on <br>the entire JSP page. munotes.in</p> </div> <div class="post"> <h2>Page 133</h2> <p> <br> Introduction to Java Server Pages <br>127 7. Separation of logic from view <br>It enables to separat e presentation layer with the business logic layer in the <br>web application. <br> 12.3 DISADVANTAGES OF JSP The disadvantages of JSP are: <br> 1. Attractive Java code : <br>Putting Java code within a webpage is really bad design, but JSP makes it <br>tempting to do just that . Avoid this as far as possible. <br>2. Java Code Required : <br>To do relatively simple things in JSP can actually demand putting Java <br>code in a page. Assume a page needs to determine the context root of the <br>current web application, perhaps to create a link to the web <br>applications,home page. This is done using Java code in JSP. <br><a href=’<%=request.getContextPath()%> /index.html’>Home Page</a> <br>Java code can be avoided by using <jsp:getProperty> but that makes the <br>code spec even more complex. <br><a href=’<jsp:getPropert y name=”request” <br>property=”contextPath”/>/index.html’>Home Page</a> <br>3. Simple Tasks are Hard to Code : <br>Even including page headers and footers is a bit difficult with JSP. In JSP <br>the best way to do this is as follows: <br><% @include file=”/header.jsp”;%> <br>/*Som e content here*/ <br><% @include file=”/footer.jsp”;%> <br>4. Occupies a lot of space : <br> JSP pages require about double the disk space to hold the page. Because <br>JSP pages are translated into class files, the server has to store the resultant <br>class files with the JS P pages. <br>5. Debugging not easy : <br>It is hard to trace JSP pages error because JSP pages are translated to <br>servlet before the compilation process. <br>6. Difficult Looping in JSP : <br>Looping in JSP is a bit complicated. <br> munotes.in</p> </div> <div class="post"> <h2>Page 134</h2> <p> <br> Enterprise Java <br>128 7. Database Connection not easy : <br>Database co nnectivity is not as easy as it should be. Most of the servlet <br>engine vendors do not support connection pooling natively, as of this day. <br>Consequently, one has to write a lot of custom code to do the job. <br>12.4 JSP V/S SERVLETS Servlets provide the ability to build dynamic content for websites using <br>Java and is supported by all Web Servers. Servlet JSP Servlets run faster than JSP. JSP runs slower than servlet as it takes time to compile the program and convert into servlets. It is hard to write code in servlet. It’s easier to code in JSP compared to servlets. In MVC architecture, servlet works as a controller. In MVC architecture, JSP works as a view for displaying output. It should be use when there is more data processing involved. JSP is generally used when there is no involvement of much data processing. There is no custom tag writing facility in servlets. You can easily build custom tags that can directly call Java beans. Servlet is a java code. JSP is a HTML-based code. It can accept all protocol requests, including HTTP. It can only accept HTTP requests. You can override the service() method. In JSP, you can’t override the service() method. In Servlet, by default, session management is not enabled, user has to enable it explicitly. In JSP, session management is automatically enabled. In Servlet, you have to implement both business logic and presentation logic in the single file. In JSP, business logic is split from presentation logic. Modification in Servlet file is a time consuming due to reloading, recompiling, and restarting the server. JSP modification is fast, as you just need to click one refresh button. munotes.in</p> </div> <div class="post"> <h2>Page 135</h2> <p> <br> Introduction to Java Server Pages <br>129 12.5 LIFECYCLE OF A JSP PAGE A JSP life cycle is defined as the process from its creation till the <br>destruction. This is similar to a servlet life cycle with an additional step <br>which is required to compile a JSP into servlet. <br>When the browser asks for a JSP, JSP engine first checks whether it needs <br>to compile the page. If the JSP is last compiled or the recent modifi cation <br>is done in JSP, then the JSP engine compiles the page. <br>Compilation process of JSP page involves three steps: <br> Parsing of JSP <br> Turning JSP into servlet <br> Compiling the servlet <br>JSP Lifecycle follows the following steps: <br>1. Translation of JSP page <br>2. Compilatio n of JSP page(Compilation of JSP page into _jsp.java) <br>3. Classloading (_jsp.java is converted to class file _jsp.class) <br>4. Instantiation(Object of generated servlet is created) <br>5. Initialisation(_jspinit() method is invoked by container) <br>6. Request Processing(_jspserv ice() method is invoked by the container) <br>7. Destroy (_jspDestroy() method invoked by the container) <br>1. Translation of the JSP Page: <br>A Java servlet file is generated from a JSP source file. This is the fi rst step <br>of JSP life cycle. In translation phase, container validates the syntactic <br>correctness of JSP page and tag files. <br>The JSP container interprets the standard directives and actions, and the <br>custom actions referencing tag libraries used in this JSP p age. <br>For example, a program named demo.jsp as shown below: <br>demo.jsp <br><html> <br><head> <br><title>Demo JSP

<%
int demovar=0;%> munotes.in

Page 136


Enterprise Java
130
Count is:
<% out.println(demovar++); %>


will get translated into demo_jsp.java as below:

In the ab ove example,
 demo.jsp, is a JSP where one variable is initialized and incremented.
This JSP is converted to the servlet (demo_jsp.class ) wherein the JSP
engine loads the JSP Page and converts to servlet content.
 When the conversion happens all template text is converted to
println() statements and all JSP elements are converted to Java code.
2. Compilation of the JSP Page :
 The generated java servlet file is compiled into java servlet class
 The translation of java source page to its implementation class can
happen at any time between the deployment of JSP page into the
container and processing of the JSP page.
 In the above pictorial description demo_jsp.java is compiled to a class
file demo_jsp.class
3. Class loading :
 Servlet class that has been loaded from JS P source is now loaded into
the container
4. Instantiation :
 In this step the object i.e. the instance of the class is generated.
 The container manages one or more instances of this class in the
response to requests and other events. Typically, a JSP containe r is
built using a servlet container. A JSP container is an extension of
servlet container as both the container support JSP and servlet. munotes.in

Page 137


Introduction to Java Server Pages
131  A JSPPage interface which is provided by container provides init()
and destroy () methods.
 There is an interface HttpJ SPPage which serves HTTP requests, and it
also contains the service method.
5. Initialization :
public void jspInit()
{
//initializing the code
}
 _jspinit() method will initiate the servlet instance which was
generated from JSP and will be invoked by the con tainer in this phase.
 Once the instance gets created, init method will be invoked
immediately after that
 It is only called once during a JSP life cycle, the method for
initialization is declared as shown above
6. Request processing :
void _jspservice(HttpSer vletRequest request HttpServletResponse
response)
{
//handling all request and responses
}
 _jspservice() method is invoked by the container for all the requests
raised by the JSP page during its life cycle
 For this phase, it has to go through all the above phases and then only
service method can be invoked.
 It passes request and response objects
 This method cannot be overridden
 The method is shown above: It is responsible for generating of all
HTTP methods i.eGET, POST, etc.
7. Destroy :
public void _jspdestr oy()
{
//all clean up code
}
_jspdestroy() method is also invoked by the container munotes.in

Page 138


Enterprise Java
132  This method is called when container decides it no longer needs the
servlet instance to service requests.
 When the call to destroy method is made then, the servlet is ready for
a garbage collection
 This is the end of the life cycle.
 We can override jspdestroy() method when we perform any cleanup
such as releasing database connections or closing open files.

Whenever the JSP file changes ,the Web Server automatically detects the
change and rebuilds the corresponding servlet. The JSP to Servlet
compilation phase imposes a slight delay the first time a page is retrieved.
Many web servers permit pre -compilation of JSPs to get around this
problem.
12.6 HOW DOES JSP FUNCTION: JSP code spec can be broken into two categories:
 Elements that are processed by the JSP Engine on the Web Server
 Template data or everything other than such elements that the JSP
engine ignores.
A JSP page is executed by a web server that either has a built -in JSP
engine or accesses a third party JSP engine,which it is configured to use.
When a client asks for a JSP page , the Web Server sends that request and
delivers it to the JSP engine along with a response object.
The JSP engine then processes the client’s request and delivers the output
back to the Web Server for further delivery to the client.
Let’s look into a simple example to understand the functioning of a JSP
page. In this example, we are creating a html page to accept a name from
the user and submit it to the Server. The Web Server will process the
request which will consist the name entered by the user and in return print
a “Hello “ name on the client’s browser.
Example: Program to understand the basic functioning of a JSP page.
Index.html
munotes.in

Page 139


Introduction to Java Server Pages
133
User Page



Enter Your Name





When viewed in a browser,the HTML page looks like:

When the user cli cks Submit ,the data entered on the form will be sent as
a request to the JSP page on the Web Server for further processing.
The Web Server accepts the data returned from the browser and passes it
as a parameter to hello.jsp which creates the response HT ML page which
will be sent back to the client’s browser.

Hello.jsp
<%@page contentType="text/html" pageEncoding="UTF -8"%>


JSP Page munotes.in

Page 140


Enterprise Java
134

Hello
<%=request.getParameter("name")%>


In the above Hello.jsp page, the first line :
<%@page contentType="text/html" pageEncoding="UTF -8"%>
is a JSP directive (denoted by <%@). Hence the JSP engine recognizes
that:
 The MIME type is text/html for JSP Style JSP tag.
 The char acter encoding is UTF -8 for XML style tags.
The next part of code <%=request.getParameter("name")%> is a block of
expression tag which is used to evaluate the expression after = and return
the value .
Thus the output of the above code will be Hello followe d by the name
entered by the user on index.html.
The response from the web server displayed in the user browser is :

12.7 HOW DOES JSP PROGRAM EXECUTE? The following happens when a user browser requests index.jsp.
The browser sends its request to the We b Server as
http://localhost:8080/Sample/index.jsp?numtimes=5
This specifies the value of numtimes as a GET parameter.
Web Server recognizes index.jsp in the URL sent in by the browser. Web
Server recognizes index.jsp as a jsp page by its extension and that the
information delivered by the browser encoded in the URL must be passed
onto index.jsp.
Index.jsp is then translated into a java class by the JSP engine, This
translation and compilati on phase occurs only when the JSP is first called.
(or it is subsequently changed)Hence there will be slight delay the first
time when index.jsp is run. munotes.in

Page 141


Introduction to Java Server Pages
135 For every subsequent request for that JSP page thereafter, there is no delay
because the request is for warded directly to the servlet already in the
memory.

12.8 DIRECTORY STRUCTURE OF JSP The directory structure of JSP page is same as Servlet. We contain the JSP
page outside the WEB -INF folder or in any directory.

12.9 SUMMARY  Java Server Pages is a se rver side technology used for creating
dynamic web application.
 Tags are used to insert JAVA code into HTML pages.
 JSP is first converted into servlet by JSP container before processing
the client’s request. munotes.in

Page 142


Enterprise Java
136  JSP easily separates the presentation logic from the business logic
 JSP code can be easily modified to incorporate any look and feel
changes to the application
12.10 LIST OF REFERENCES Java EE 7 for Beginners, Sharanam Shah, Vaishali Shah, First Edition,
SPD
Web References :
1. https://www.guru99.com
12.11 QUESTIONS Q1. How does JSP differ from Servlets?
Q2. Write a note on lifecycle of a JSP.
Q3. What are the advantages and disadvantages of using JSP for
developing web applications?
Q4. How are JSP pages executed?
*****

munotes.in

Page 143

137 13
GETTING STARTED WITH JAVA SERVER
PAGES, ACTION ELEMENTS
Unit Structure
13.0 Objectives
13.1 Introduction
13.2 Comments in JSP
13.3 JSP Documents
13.4 JSP Elements
13.5 JSP Directives
13.5.1 Page directive
13.5.2 Include directive
13.5.3 Tag lib directive
13.6 JSP Scripting Elements
13.6.1 Scriptlets Tag
13.6.2 Expressions Tag
13.6.3 Declarations Tag
13.7 JSP Action Elements
13.7.1
13.7.2
13.7.3
13.7.4
13.7.5
13.8 JSP GUI Example
13.9 Summary
13.10 List of References
13.11 Questions
13.0 OBJECTIVES After going through this chapter, you will:
 Understand Java Server Pages documents
 Learn the various elements that can be used in a JSP page
 Lean how to inclu de and forward JSP pages
 Understand what are Java Beans and why it is used? munotes.in

Page 144


Enterprise Java
138 13.1 INTRODUCTION A JSP Page looks very similar to a HTML or XML page. It consists of
both static and dynamic content. The static content can be written using
plain HTML or XML and dynamic content can be written either using the
regular java style of programming embedded in specific elements or using
the tag style approach.
JSP tags are nothing but holders of Java code spec in an HTML page. This
code spec is then executed by the we b server whenever the page is
requested.
13.2 COMMENTS IN JSP Comments are text that is written for maintaining JSP pages. These are
ignored by the JSP engine when it translates the JSP page into a Servlet.
The comment will therefore not be sent to the us er (Web Browser) in the
response and thus will not be visible using the browser’s View Source
option.
There are 2 syntax of writing comments in a JSP page:
1) <%-- This is JSP comment --%>
This comment will be ignored by the JSP engine :
2)
This is a HTML comment and will be ignored by the browser.
Example: Program showing how to write JSP comments


JSP Program to show comments


Hello World!
<%-- This is a JSP co mment and will not be processed by JSP Engine
--%>


13.3 JSP DOCUMENTS A JSP document can use either the traditional JSP style syntax or XML
style JSP syntax within its source file.
JSP pages uses the traditional or short -hand syntax, whereas JSP
documents are completely XML -compliant. munotes.in

Page 145


Getting Started With Java Server Pages, Action Elements
139 JSP documents are also referred to as JSP pages using XML syntax.
Following are the advantages of using JSP documents:
1. JSP documents can be easily verified as well -formed XML/HTML.
2. JSP documents can be validated against an XML -Schema.
3. JSP documents can be readily written and parsed using standard XML
tools.
4. JSP uses XML compliant include and forward actions as well as
custom tags.
5. JSP documents require slightly more developer discipline th an JSP
pages. This makes the code spec more readable and maintainable
especially to those to whom JSP is new.
13.4 JSP ELEMENTS JSP page usually provide dynamic behaviour. This means they are
supposed to change the response as per specific client requests.
JSP pages can be given dynamic behaviour by embedding Java code in
them. To clearly separate JSP elements are used. It helps to inform the JSP
translator which part of code is java and which part is HTML.
JSP Elements enclose the Java code in a JSP page a nd are categorized
as follows:
1. Directives
2. Scripting Elements
3. Action Elements
13.5 JSP DIRECTIVES JSP directives serve special processing information about the page to the
JSP Server.
A JSP directive affects the overall structure of the servlet class. They do
not produce any output that is visible to the client.
It usually has the following form :
<%@ directive attribute = "value" %>
Directives can have a number of attributes which you can list down as
key-value pairs and separated by commas.
The blanks between the @ symbol and the directive name, and between
the last attribute and the closing %>, are optional.
munotes.in

Page 146


Enterprise Java
140 There are three types of directive tag: Sr.No. Directive & Description 1 <%@ page ... %> Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. 2 <%@ include ... %> Includes a file during the translation phase. 3 <%@ taglib ... %>
Declares a tag library, containing custom actions, used in the
page
13.5.1 Jsp Page Directive :
The page direct ive is used to provide instructions to the container. These
instructions pertain to the current JSP page. You may code page directives
anywhere in your JSP page. By convention, page directives are coded at
the top of the JSP page.
Following is the basic sy ntax of the page directive :
<%@ page attribute = "value" %>
You can write the XML equivalent of the above syntax as follows −

The following are the most common attributes associated with the page
directive: Sr.No. Attribute and Example 1 language Defines the programming language used in the JSP page. Eg: <%@ page language="java"%> 2 import Specifies a list of packages or classes for use in the JSP as the Java import statement does for Java classes. Eg: <%@ page import="java.util.Date" %> 3 contentType Defines the character encoding scheme. Eg: <%@ page contentType=application/msword %> 4 extends Specifies a superclass that the generated servlet must extend. Eg: <%@ page extends = "somePackage.SomeClass" %>
munotes.in

Page 147


Getting Started With Java Server Pages, Action Elements
141 5 isErrorPage Indicates if this JSP page is a URL specified by another JSP page's errorPage attribute. Eg: <%@ page isErrorPage="true" %> 6 session Specifies whether or not the JSP page participates in HTTP sessions. Eg: <%@ page session = "true" %>
7 info The info attribute lets you provide a description of the JSP. <%@ page info = "This is a JSP Page" %>
Example:
<%@ page contentType="text/html" %>


Today is: <%= new java.util.Date()%>


13.5.2 JSP Include Directive :
The include directive is used to include a file during the translation phase.
This directive tells the container to merge the content of other external
files with the current JSP during the translation phase. You may code the
include directives anywhere in your JSP page.
The general usage form of this directive is as follows :
<%@ include file = "relative url" >
The filename in the include directive is actually a relative URL. If you just
specify a filename with no associated pat h, the JSP compiler assumes that
the file is in the same directory as your JSP.
You can write the XML equivalent of the above syntax as follows :

The file attribute :
A page -relative or context -relative URI pat h to the file that will be
included at the current position in the file. This attribute includes a static
file ,merging its content with the including page before the combined
result is converted to a JSP page implementation class. A page can contain
multi ple include directives.

munotes.in

Page 148


Enterprise Java
142 Example:


<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>


13.5.3 JSP Taglib Directive :
The taglib directive declares that your JSP page use s a set of custom tags,
identifies the location of the library, and provides means for identifying
the custom tags in your JSP page. Custom Tags allow developers to hide
complex server side code spec from web designers.
A taglib directive in a JSP is a lin k to an XML document that describes a
set of custom tag. This XML document also determine which Tag Handler
class implements the action of each tag. The XML document names the
tag library which holds the custom tags.The JSP engine uses this tag
library to determine what to do when it comes across custom tags
The taglib directive follows the syntax given below :
<%@ taglib uri = "uri" prefix = "prefixOfTag" >
You can write the XML equivalent of the above syntax as follows :

The uri attribute :
A Uniform Resource Identifier (URI) that identifies the Tag Library
Descriptor ,which is used to uniquely name the set of custom tags and
inform the server what to do with the specified tags.
The prefix attribute :
It defines the prefix string in : pair and informs the
JSP container which bits of markup are custom tags.
Example :
<%@ taglib uri = "http://www.abc.com/mylib" prefix = "mytag" %>


munotes.in

Page 149


Getting Started With Java Server Pages, Action Elements
143

13.6 SCRIPTING ELEMENTS The scripting elements provides the ability to insert java code inside the
jsp. There are three types of scripting elements:
 Declaration tag
 Expression tag
 Scriptlet tag
These elements allow declaring variables and methods,including scrip ting
code and evaluating an expression.
13.6.1 Declarations Tag :
The JSP declaration tag is used to declare fields and methods. The code
written inside the jsp declaration tag is placed outside the service() method
of auto generated servlet. So it doesn't get memory at each request.
The Syntax of JSP declaration tag is as follows:
<%!
Java variable and method declaration(s)
%>
You can write the XML equivalent of the above syntax as follows :

Java variable and method declaration(s)

Example:
<%!
int num=0;
public void count(){
{
int num=10;
}
%>

munotes.in

Page 150


Enterprise Java
144 13.6.2 Scriptlets Tag:
A scriptlet is a block of Java code spec that is executed at runtime.
Scriptlets also known as JSP code fragments are embedded within <% ….
%> tags.
A Scriptlet can produce output passed through an output stream back to
the client.
The Syntax of JSP Scriptlets tag is as follows:
<%
Scriptlet code Spec
%>
You can write the XML equivalent of the above syntax as follows :

Scriptle t code Spec

The following example program prints “Welcome to JSP” on the page.
Example :


<% out.print("Welcome to jsp"); %>


13.6.3 Expressions Tag :
It is mainly used to print the values of variable or method. The code
placed within JSP expression tag is written to the output stream of the
response. So you need not write out.print() to write data.
After an expression is evaluated, the result is converted to a string and
displayed.
The Syntax of JSP Exp ression tag is as follows:
<%= statement %>
You can write the XML equivalent of the above syntax as follows :

Statements :
munotes.in

Page 151


Getting Started With Java Server Pages, Action Elements
145 Example:


Current Time: <%= java.util.Calendar.getInstance().getTime() %>


13.7 ACTION ELEMENTS JSP Action tags are used to control the flow between pages and to use Java
Bean.
JSP Action Elements are processed during the request processing phase as
opposed to JSP directives which are processed during translation. Act ions
use construct in XML syntax.It looks like a regular HTML tag and does
not follow the <% … %> syntax.
There are many JSP action tags or elements. Each JSP action tag is used to
perform some specific tasks. JSP Action Tags Description jsp:forward forwards the request and response to another resource. jsp:include includes another resource. jsp:useBean creates or locates bean object. jsp:setProperty sets the value of property in bean object. jsp:getProperty prints the value of property of the bean. jsp:plugin embeds another components such as applet. jsp:param sets the parameter value. It is used in forward and include mostly. jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin.
13.7.1 JSP: forward Action T ag:
The forward action terminates the action of the current page and forwards
the request to another resource such as a static page, another JSP page, or munotes.in

Page 152


Enterprise Java
146 a Java Servlet. It is same as forwarding to resources using
RequestDispatcher interface in Servlets.
Syntax:
”>

value=””/>

page attribute :
It is a string or an expression representing the relative URL of the
component to which the request is forwarded.
tag
It is used to send one or more name=value pairs as parameters to a
dynamic resource such as JSP,Servlets or other resources.
Example without parameter
Index.jsp


The forward JSP example





Example with parameter
Index.jsp


Forwarding with Parameters




munotes.in

Page 153


Getting Started With Java Server Pages, Action Elements
147

date.jsp


<%out.print("Today is:" +
java.util.Calendar.getInstance().getTime());%>
<%= request.getParameter("name")%>


13.7.2 JSP: Include Action Tag :
The include action terminate s the action of the current page an d forwards
the request to another resource such as a st atic page, another JSP page, or
a Java Servlet. It is same a s forwarding to resources using
RequestDispatcher interface in Servlets.
Syntax:
” >
” value=””/>

page attribute :
It is a string or an expression representing the relative URL of the
component to which the request is forwarded.
tag :
It is used to send one or more name=value pairs as parameters to a
dynamic resource such as JSP,Servlets or other resources.
Example without parameter
Index.jsp


The include JSP example

munotes.in

Page 154


Enterprise Java
148


Example with parameter
Index.jsp


Including with Parameters







date.jsp


<% out.print("Today is:" + java.util.Calendar.getInstance().getTime());%>
<%= request.getParameter("name")%>


Note:
 The difference between jsp include directive and include action tag is
Include action includes response of a resource into the response of the
JSP page
 Include directive includes resources in a JSP page at translation time. munotes.in

Page 155


Getting Started With Java Server Pages, Action Elements
149


13.7.3 jsp: useBean Action Tag:
Before understanding what is ,we need to first understand
JavaBean.
JavaBean
A J avaBean is a Java class that should follow the following
conventions:
 It should have a no -arg constructor.
 It should be Serializable.
 It should provide methods to set and get the values of the properties,
known as getter and setter methods.
Example of Java Bean class :
//Employee.java munotes.in

Page 156


Enterprise Java
150 package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
To access the JavaBean class, we should use getter and setter
methods.
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Steve");//setting value to the object
System.out.println(e.getName());
}
}
Action Tag :
In JSP, is used to access the bean.
instantiates an object of the class spec ified by the class and binds it to a
variable with the name specified by ID.A new object is instantiated only if
there is no existing one with the same ID and scope. Once a bean exists,
its properties can be modified using or by using a
scriptlet and calling a method explicitly. Existing properties can be read in
a JSP or scriptlet by using .
makes a JavaBean available to a JSP Page and ensures that
the bean object is available for an appropriate scope specif ied in the
element.
Syntax of jsp:useBean action tag :
class= "packageName.className" type= "packageName.className" munotes.in

Page 157


Getting Started With Java Server Pages, Action Elements
151 beanName="packageName.className | <%= expression >" >

Attributes and Usage of jsp:useBean action tag :
1. id: is used to identify the bean in the specified scope.
2. scope: represents the scope of the bean. It may be page, request,
session or application. The default scope is page.
o page: specifies th at you can use this bean within the JSP page. The
default scope is page.
o request: specifies that you can use this bean from any JSP page that
processes the same request. It has wider scope than page.
o session: specifies that you can use this bean from any J SP page in the
same session whether processes the same request or not. It has wider
scope than request.
o application: specifies that you can use this bean from any JSP page in
the same application. It has wider scope than session.
3. class: instantiates the sp ecified bean class (i.e. creates an object of the
bean class) but it must have no -arg or no constructor and must not be
abstract.
4. type: provides the bean a data type if the bean already exists in the
scope. It is mainly used with class or beanName attribut e. If you use it
without class or beanName, no bean is instantiated.
5. beanName: instantiates the bean using the
java.beans.Beans.instantiate() method.
Example:
Calculator.java (a simple Bean class)
package com.javatpoint;
public class Calculator{
public int cube(int n){return n*n*n;}
}
index.jsp file

<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
munotes.in

Page 158


Enterprise Java
152 13.7.4 Action Tag :
is used in conjuncti on with and sets the
value of simple and indexed properties in a bean.
The propert ies in a bean can be set either :
 At request time from parameters in the request object or
 At request time from an evaluated expression or
 From a specified strin g(or hard coded in the page)
Syntax of jsp:setProperty Action Tag
property="propertyName" param="parameterName" |
property="propertyName" value="{ string | <%= expression %>}"
/>
Examp le:



Example :


Here, invokes getName() available in the Student class.
13.8 JSP GUI EXAMPLE Create a registration and login JSP application to register and authenticate
the user based on username and password using JDBC.
Initial. html :
Sign up for New User

munotes.in

Page 159


Getting Started With Java Server Pages, Action Elements
153 Login for Existing User
Index.html


Registration Page



New User Registration Page


Enter UserName

Enter Password

Re-Enter Password>

Enter Email

Enter Country Name






Regis ter.jsp
<%@page contentType="text/html" pageEncoding="UTF -8"
import="java.sql.*"%>



Registration JSP Page


<%
String uname = request.getParameter("txtName");
String pass1 = request.getParameter("txtPass1");
String pass2 = request.getParameter("txtPass2");
String email = request.getParameter("txtEmail");
String ctry = request.getParameter("txtCon"); munotes.in

Page 160


Enterprise Java
154 if (pass1.equals(pass2)) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection("jdbc:derby: //localhost:1527/mydb",
"root", "root");
PreparedStatement stmt = con.prepareStatement("insert into
UserDetails values(?,?,?,?)");
stmt.setString(1, uname);
stmt.setString(2, pass1);
stmt.setString(3, email);
stmt.setString(4, ctry);
int row = stmt.executeUpdate();
if (row == 1) {
out.println("

Registration Successful!!!

");
out.println("
Login here");
} else {
out.println("

Registration Failed!!!

");
%>

<%
}
} catch (Exception e) {
out.println(e);
}
} else {
out.println("

Password Mismatch!!!

");
%>

<% }
%>


Login.html

munotes.in

Page 161


Getting Started With Java Server Pages, Action Elements
155 Login Application



Login Application


Enter Username


Enter Password







login.jsp
<%@page contentType="text/html" pageEncoding= "UTF -8"
import="java.sql.*"%>




Login JSP Page


<%
String uname = request.getParame ter("t1");
String pass = request.getParameter("t2");
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connection con =
DriverManager.getConnection("jdbc:derby://localhost:1527/my db",
"root", "root");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select password from
UserDetails where username='" + uname + "'");
rs.next();
if (pass.equals(rs. getString(1))) {
out.println("

Welcome"+uname+"

"); munotes.in

Page 162


Enterprise Java
156 } else {
out.println("

Login Failed!!!

");
%>

<%
}
} catc h (Exception e) {
out.println("

User does not exist!!!!!

");
%>

<%
}
%>


13.9 SUMMARY  JSP comments are ignored by the JSP engine when it translat es the
JSP page into a Servlet.
 A JSP document can use either the traditional JSP style syntax or
XML style JSP syntax within its source file.
 JSP Elements enclose the Java code in a JSP page and are categorized as
follows:
1. Directives
2. Scripting Eleme nts
3. Action Elements
 JSP directives serve special processing information about the page to
the JSP Server.
 The scripting elements provides the ability to insert java code inside
the jsp. There are three types of scripting elements:
1. Declaration tag
2. Expression tag
3. Scriptlet tag
 JSP Action tags are used to control the flow between pages and to use
Java Bean. munotes.in

Page 163


Getting Started With Java Server Pages, Action Elements
157 13.10 LIST OF REFERENCES 1. Java EE 7 for Beginners, Sharanam Shah, Vaishali Shah, First
Edition, SPD
Web References :
1. https://www.javatpoint.com
2. https://www.tutorialspoint.com
3. https://www.guru99.com
13.11 QUESTIONS Q1. What are the different ways of writing comments in Java?
Q2. What are the various attributes used in the page directive?Explain
with an example.
Q3. What is the benefit of using taglib directive?
Q4. What are the various Scripting elements available in JSP? Why are
they used?
Q5. What is the difference b etween include directive and include action
tag?
Q6. What is a JavaBean?Why is it used?Explain with an example.
Q7. How is action tag used to set and access properties of a
JavaBean?
*****
munotes.in

Page 164

158 14
IMPLICIT OBJECTS, SCOPE AND EL
EXPRESSIONS
Unit Structure
14.0 Objectives
14.1 Implicit Objects
14.2 Scope
14.3 Character Quoting Conventions
14.4 Unified Expression Language (UEL)
14.4.1 Types of UEL
14.4.2 Method Expressions
14.4.3 Operators
14.5 Summary
14.6 List of References
14.7 Questions
14.0 OBJECTIVES After going through this chapter, you will:
 You will understand what are the various implicit objects in JSP
 Learn the various scope of objects in JSP
 Know what are character quoting co nventions and how to write them
 Learn what is Unified Expression Language and the benefits of using
them
14.1 IMPLICIT OBJECTS Java Scripting Elements provide a great deal of power and flexibility to
the developer to achieve dynamic website content deliver y.To achieve
this, JSP engine exposes a number of internal Java objects to the
developer. These objects do not need to be declared or instantiated by the
developer but are provided by the JSP engine in its implementation and its
execution.
All implicit obj ects are available only to scriptlets or expressions.They are
not available in declarations.


munotes.in

Page 165


Implicit Objects, Scope And EL Expressions
159 There are 9 implicit objects in JSP as follows: Object Type out JspWriter request HttpServletRequest response HttpServletResponse config ServletConfig application ServletContext session HttpSession pageContext PageContext page Object exception Throwable
1. out :
This is the JspWriter object associated with the output stream of the
response.For writing any data to the buffer, JSP provides an implicit
object named out. It is the object of JspWriter. In case of servlet you need
to write:
PrintWriter out=response.getWriter();
But in JSP, you don't need to write this code as out is pre -defined.
Example


<% out.print("This is Enterprise Java ”); %>


Here, we are simply printing the line “ This is Enterprise Java” as the
response.
2. Request :
The JSP request is an implicit object of type HttpServletRequest i.e.
created for each jsp request by the web container. It can be used to get
request information such as parameter, header information, remote
address, server name, server port, content type, character encoding etc.
It can also be used to set, get and remove attributes from the jsp request
scope.
Example
index.html


munotes.in

Page 166


Enterprise Java
160


welcome.jsp
<%
String name=request.getParameter( "uname" );
out.print( "welcome "+name);
%>
3. response :
In JSP, response is an implicit object of type HttpServletResponse. The
instance of HttpServletResponse is created by the web container for each
jsp request.
It can be used to add or manipulate response such as redirect response to
another resource, send error etc.
Let's see the example of respon se implicit object where we are redirecting
the response to the Google.
Example of response implicit object
index.html






welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
4) config :
In JSP, config is an implicit object of type ServletConfig. This object can
be used to get initialization parameter for a particular JSP page. The
config object is created by the web container for each jsp page.
Generally, it is used to get initialization parameter from the web.xml file.
Example :
index.html




munotes.in

Page 167


Implicit Objects, Scope And EL Expressions
161 web.xml file


sonoojaiswal
/welcome.jsp

dname
sun.jdbc.odbc.JdbcOdbcDriver



sonoojaiswal

/welcome


welcome.jsp :
<%
out.print("Welcome "+request.getParameter("uname"));
String driver =config .getInitParameter("dname");
out.print("dri ver name is="+driver);
%>
5) application :
In JSP, application is an implicit object of type ServletContext.
The instance of ServletContext is created only once by the web container
when application or project is deployed on the server.
This object can be used to get initialization parameter from configuaration
file (web.xml). It can also be used to get, set or remove attribute from the
application scope.
t("driver nam Example:
index.html






web.xml file munotes.in

Page 168


Enterprise Java
162

sonoojaiswal
/welcome.jsp


sonoojaiswal
/welcome


dname
sun.jdbc.odbc.JdbcOdbcDriver


welcome.jsp
<%
out.print("Welcome "+request.getParameter("unam e"));
String driver=application.getInitParameter("dname");
out.prin e is="+driver);
%>
6. session :
In JSP, session is an implicit object of type HttpSession.The Java
developer can use this object to set,get or remove attribute or to get
session in formation.
Example
index.html









munotes.in

Page 169


Implicit Objects, Scope And EL Expressions
163 welcome.jsp


<%
String name=request.getParameter( "uname" );
out.print( "Welcome "+name);
session.setAttribute( "user" ,name);
second jsp page
%>


second.jsp


<%
String name=(String)session.getAttribute( "user" );
out.print( "Hello "+name);
%>


7. pageContext :
In JSP, pageContext is an implicit object of type PageContext class.The
pageContext object can be used to set,get or remove attribute from one of
the following scopes:
 page
 request
 session
 application
In JSP, page scope is the default scope.
Example
index.html


munotes.in

Page 170


Enterprise Java
164





welcome.jsp


<%
String name =request.getParameter( "uname" );
out.print( "Welcome "+name);
pageContext.setAttribute( "user" ,name,PageContext.SESSION_SCOPE);
second jsp page
%>


second.jsp


<%
String name=(String)pa geContext.getAttribute( "user" ,PageContext.SESSI
ON_SCOPE);
out.print( "Hello "+name);
%>


8) page :
In JSP, page is an implicit object of type Object class.This object is
assigned to the reference of auto generated servlet class. It is written as:
Object page=this;
For using this object it must be cast to Servlet type.For example:
<% (HttpServlet)page.log("message"); %>
Since, it is of type Object it is less used because you can use this object
directly in jsp.For example:
<% this.log( "message"); %> munotes.in

Page 171


Implicit Objects, Scope And EL Expressions
165 9) exception :
In JSP, exception is an implicit object of type java.lang.Throwable class.
This object can be used to print the exception. But it can only be used in
error pages.It is better to learn it after page directive. Let's see a simple
example:
Example
error.jsp
<%@ page isErrorPage= "true" %>


Sorry following exception occured:<%= exception %>


14.2 SCOPE OF JSP OBJECTS The availability of a JSP object for use from a particular place of the
application is defined as the scope of that JSP object. Every object created
in a JSP page will have a scope. Object scope in JSP is segregated into
four parts and they are page, request, session and application.
Page Scope :
Objects with page scope are acce ssible only within the page in which
they're created. The data is valid only during the processing of the current
response; once the response is sent back to the browser, the data is no
longer valid. If the request is forwarded to another page or the brows er
makes another request as a result of a redirect, the data is also lost.
//Example of JSP Page Scope

Request Scope :
Objects with request scope are accessible from pages processing the same
request in which they were created. Once the container has processed the
request, the data is released. Even if the request is forwarded to another
page, the data is still available though not if a redirect is required.
//Example of JSP Request Scope

Session Scope :
Objects with session scope are accessible from pages processing requests
that are in the same session as the one in which they were created. A
session is the time users spend u sing the application, which ends when munotes.in

Page 172


Enterprise Java
166 they close their browser, when they go to another Web site, or when the
application designer wants (after a logout, for instance). So, for example,
when users log in, their username could be stored in the session and
displayed on every page they access. This data lasts until they leave the
Web site or log out.
//Example of JSP Session Scope

Application Scope :
Objects with application scope are accessib le from JSP pages that reside in
the same application. This creates a global object that's available to all
pages.
Application scope uses a single namespace, which means all your pages
should be careful not to duplicate the names of application scope objec ts
or change the values when they're likely to be read by another page (this is
called thread safety). Application scope variables are typically created and
populated when an application starts and then used as read -only for the
rest of the application.
//Example of JSP Application Scope
/>
14.3 CHARACTER QUOTING CONVENTIONS Because certain character sequences are used t o represent start and stop
tags, the developer sometimes needs to esc ape a character so the JSP
engine does not interpret it as part of a special character sequence.
In a scripting element, if the character needs %> needs to be used,escape
the greater than sign with a backslash.
<%String message=” This is the %/> message”; %>
The backslash before the expression acts as an escape character and
informs the JSP engine to not evaluate it.
There are a number of cases where backslash needs to be used otherwise
characters will be treated specially by the JSP engine. Escape Characters Description \’ A single quote in an attribute that uses single quote \” A double quote in an attribute that uses double quote \\ A backslash in an attribute that uses backslash munotes.in

Page 173


Implicit Objects, Scope And EL Expressions
167 %\> Escaping the scriptlet end tag with a backslash <\% Escaping the scriptlet start tag with a backslash \$ Escaping the $ sign with a backslash
14.4 UNIFIED EXPRESSION LANGUAGE (UEL) JSP Expression Language provides a way to simplify expressions. It is a
simple language used for accessing implicit objects. Java classes a nd for
manipulating collections in an elegant manner. It is the newly added
feature in JSP technology version 2.0.
The expression language also allows page authors to use simple
expressions to dynamically read data from JavaBean components.
Unified Express ion Language allows usage of simple expressions to
perform the following tasks:
 Dynamically read application data stored in JavaBeans components,
various data structures and implicit objects.
 Dynamically write data such user input into forms to JavaBeans
components.
 Dynamically perform arithmetic operations.
14.4.1 Types o f Evaluation Expressions :
Unified EL supports two types of evaluation expressions: Immediate and
Deferred evaluation
Immediate Evaluation:
Immediate evaluation means that the expression i s evaluated and the result
returned as soon as the page is first rendered.
Syntax:
${}
Here, Expression stands for valid expression.
The following example shows a tag whose value attribute references an
immediate evaluation expression that upda tes the quantity of books
retrieved from the backing bean named catalog:

Deferred Evaluation:
Deferred evaluation means that the technology using the expression
language can use its own machinery to evaluate the expression sometime
later during the page’s lifecycle, whenever it is appropriate to do so. munotes.in

Page 174


Enterprise Java
168 Syntax:
#{}
Here, Expression stands for valid expression.
Because of its multiphase lifecycle, JavaServer Faces technology uses
mostly deferred ev aluation expressions. During the lifecycle, component
events are handled, data is validated, and other tasks are performed in a
particular order. Therefore, a JavaServer Faces implementation must defer
evaluation of expressions until the appropriate point in the lifecycle.
Other technologies using the EL might have different reasons for using
deferred expressions.
The following example shows a JavaServer Faces h:inputText tag, which
represents a field component into which a user enters a value. The
h:inputT ext tag’s value attribute references a deferred evaluation
expression that points to the name property of the customer bean:

14.4.2 Value Expressions :
The unified EL provides two types of value expressions :
 Rvalue Expressions:
Can only read data, but cannot write data. Expressions that use deferred
valuation syntax are always rvalue expressions.
 Lvalue Expressions:
Can read and write data. Expressions that uses deferred evaluation syntax
can act as both Rv alue and Lvalue expressions.
Consider the following two value expressions:
${customer.name}
#{customer.name}
The former uses immediate evaluation syntax, whereas the latter uses
deferred evaluation syntax. The first expression accesses the name
property, g ets its value, and passes the value to the tag handler. With the
second expression, the tag handler can defer the expression evaluation to a
later time in the page lifecycle if the technology using this tag allows.
In the case of JavaServer Faces technolog y, the latter tag’s expression is
evaluated immediately during an initial request for the page. During a
postback request, this expression can be used to set the value of the name
property with user input.
munotes.in

Page 175


Implicit Objects, Scope And EL Expressions
169 14.4.3 Method Expressions :
EL also supports defer red method expressions. A method expression is
used to refer to a public method of a bean and has the same syntax as an
lvalue expression.
A JSF component element usesmethod expressions, which in turn invokes
method that do some process on behalf of the co mponent element. For
standard components, these methods are necessary for handling events that
the components generates as well as validating component data.
Example
Solution:
Validator=”#{customer .validateFirstname}”/>
Explanation:
The validator attribute of references validateFirstnameid()
owned by a bean called customer.
specifies that validateFirstName() should be invoked
during the validation process phase of the JSF lifecycle.
Because a method can be invoked during different phases of the lifecycle,
method expressions must always use the deferred evaluation syntax.
14.4.4 Operators :
EL the following operators, most of which are usual operators available in
Java:
1. Arithmetic Operators :
The following are the arithmetic operators:
 +Addition
 [Binary]:(subtraction)
 :Multiplication
 / or div:Division
 % or mod:modulo[remainder]
 -[unary]:Negation of a value
Example
1. ${5*5+4}
2. ${1.2E4+1.4} munotes.in

Page 176


Enterprise Java
170 3. ${10 mod 4}
4. ${3 div 4}
Output:
1. 29
2. 12001.4
3. 2
4. 0.75
2. Logical Operators :
The following are the logical operators:
 && or AND: Test for logical AND
 || or OR : Test for logical OR
 ! or NOT :Unary Boolean complement
Example
<%-- Evaluates if variable is not empty --%>
${!empty}
3. Relational Operators :
The following are the relational operators:
== or eq :Test for equality
!= or ne: :Test for inequality
< or lt: Test for less than
> or gt : Test for greater than
<= or le : Test for less than or equal
>= or ge : Test for greater than or equal
Example:
${10>3}
${1>8}
${10 le 3}

munotes.in

Page 177


Implicit Objects, Scope And EL Expressions
171 4. Conditional Operators :
The following is the syntax for conditional operators:
Condition ? If true :If false
Solution
A?B:C
Here B is evaluated if A is true else is evaluated if A is false
5. The [Dot] Operator :
It is a shorthand for calling a JavaBeans property accessor for the property
whose name is on the right side of the operator.
Solution
${pageContext.servletContext.servletContextName}
6. The [] Operator :
Is is used for polymorphic indexing, which can be used for indexing
collections including Maps,Lists and Arrays. The value inside the brackets
is used as a key into a map or as a List or array index.
Example:
${colors[5]}
${colors[1]>colors[6]}
7. The empty operator :
It is a prefix operator that is used to determine if a value is null or empty.
Example
${empty Name}
This expression returns true if Name refers a null value.
14.4.5 JSP EL IMPLICIT OBJECTS :
The JSP expression language supports the following implicit objects : Sr. No. Implicit object & Description 1 pageScope Scoped variables from page scope 2 requestScope Scoped variables from request scope 3 sessionScope Scoped variables from session scope munotes.in

Page 178


Enterprise Java
172 4 applicationScope Scoped variables from application scope 5 param Request parameters as strings 6 paramValues Request parameters as collections of strings 7 header HTTP request headers as strings 8 headerValues HTTP request headers as collections of strings 9 initParam
Context -initialization parameters 10 cookie
Cookie values 11 pageContext
The JSP PageContext object for the
current page
14.5 SUMMARY  JSP provides a number of implicit objects which need not be declared
or instantiated by the developer.
 Implicit objects are available only to scriptlets or expres sions.They
are not available in declarations.
 JSP objects have 4 scopes: page,request,session and application
 The escape character backslash can be used to inform the JSP engine
not to evaluate certain expressions.
 Unified Expression Language provides a wa y to simplify expressions
and can be used for accessing implicit objects.
 UEL supports both immediate and deferred evaluation.
 UEL also supports various operators and can be used to call methods.
14.6 LIST OF REFERENCES Java EE 7 for Beginners, Sharanam S hah, Vaishali Shah, First Edition,
SPD
Web References :
1. https://www.javatpoint.com
2. https://www.java -samples.com munotes.in

Page 179


Implicit Objects, Scope And EL Expressions
173 14.7 QUESTIONS Q1. List the various implicit objects in JSP.
Q2. Explain the scope of JSP objects.
Q3. What is Immediate and Deferred Evaluation? Explain with an
example.
Q4. Write a note on character quoting conventions.
Q5. Explain Method Expressions in short.
Q6. What are the various operators supported by JSP EL?
*****

munotes.in

Page 180

174 15
JSP STANDARD TAG LIBRARIES
Unit Structure
15.0 Objectives
15.1 Introduction to Java Server Pages Standard Tag Libraries
15.2 Disadvantages of JSP Scriptlet Tags
15.3 Advantages of JSTL
15.4 Disadvantages of JSTL
15.5 How is JSTL different from Sc riptlets?
15.6 Types of Tag Libraries
15.6.1 Core Tag Library
15.6.2 Functions Tag Library
15.6.3 Database/SQL Tag Library
15.6.4 Formatting Tag Library
15.6.5 XML Tag Library
15.7 Summary
15.8 List of References
15.9 Questions
15.0 OBJECTIVES After go ing through this chapter, you will:
 Understand what is Java Server Pages Tag Libraries
 Understand the advantages and disadvantages of JSTL
 Learn what are the issues of using Scriptlet Tags
 Learn the various types of Tag Libraries and available tags
15.1 IN TRODUCTION TO JSP STANDARD TAG LIBRARIES JSTL was introduced to allow JSP programming developers to create web
applications using tags rather than scriptlets (Java code). It is a collection
of useful JSP tags which encapsulates the core functionality commo n to
many JSP applications. JSTL does nearly everything that a regular
scriptlet does.
JSTL has support for common, structural tasks such as iteration and
conditionals, tags for manipulating XML documents, internationalization
tags, and SQL tags. It also provides a framework for integrating the
existing custom tags with the JSTL tags.
munotes.in

Page 181


JSP Standard Tag Libraries
175 15.2 DISADVANTAGES OF JSP SCRIPTLET TAGS 1. The Java code embedded within the Scriptlet looks ugly and
inconsistent with the HTML tags.
2. The developer who does not know Java act ually cannot modify the
embedded Java code. Thus, this disadvantage nullifies the major
benefit of JSP, which is the empowerment of designers and business
people to update page content.
3. The Java code embedded within the scriptlets cannot be re -used by
another JSP Pages. So, the common logic code gets duplicated in
multiple JSP pages.
4. Accessing values from HTTP request and sessions needs to be
specifically typecasted to the object’s class, which should be known
to the JSP by importing or fully qualifying the class name.
15.3 ADVANTAGES OF JSTL 1. JSTL tags are XML based tags, they cleanly and consistently blend
into a page’s HTML markup tags.
2. JSTL tags are easier to use effectively as they do not require any
knowledge of Java programming.
3. JSTL tags can be reused in various pages unlike scriptlets which
needs to be repeated everywhere.
4. JSTL tags can reference objects in Request and Session objects
without knowing the object’s type with no typecasting required.
5. JSTL makes use of UEL which makes it easier to call th e getter and
setter methods on Java objects.
15.4 DISADVANTAGES OF JSTL 1. JSTL increases the processing burden on the server. Java scriptlet and
the tag libraries both are compiled into a servlet, whi ch is then
executed by the Servlet engine. Java code in sc riptlets is pretty much
just copied into Servlets but on the other hand , JSTL tags casue much
more code to be added to the Servlet.
2. JSTL provides a powerful set of reusable libraries to JSP developers
but JSTL cannot do everything that the Java code spec c an do.
15.5 HOW IS JSTL DIFFERENT FROM SCRIPTLETS An example of scriptlet -based programming, which counts to 10, is shown
here:
munotes.in

Page 182


Enterprise Java
176
Count to 10 in JSP scriptlet


<%
for(int i=1;i<=10;i++)
{
%>
<%=i%>

<%
}
%>


As you can see from the preceding example, using scriptlet code produces
page source code that contains a mix of HTML tags and Java statements
making the code looking non -consistent.
Consider the following example, which shows how to coun t from 1 to 10
using JSTL rather than scriptlet code.
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>


Count to 10 Example (using JSTL)









When you examine the preceding source code, you can see that the JSP
page consists entirely of tags thus bringing consistency and uniformity to
the code.
15.6 TYPES OF JSTL TAG LIBRARIES JSTL Tag L ibraries can be broken down into specific functional areas
belonging to an application. JSTL is composed of five tag libraries: munotes.in

Page 183


JSP Standard Tag Libraries
177  Core Tag Library
 Functions Tag Library
 Database/SQL Tag Library
 Formatting Tag Library
 XML Tag Library
Let’s understand the vari ous tags under each of the above Tag Libraries.
15.6.1 Core Tag Library :
The Core Tag Library contains tags that are essential to nearly any Web
application. Examples of core tag libraries are looping, evaluation of
expression and basic input and output.
The URI of the Core Tag Library is “http://java.sun.com/jsp/jstl/core ” and
prefix is c.
The syntax used for including JSTL Core tags library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
The Core Tag Library consists of four distinct functional sections:
A) General - Purpose Actions :
These actions allow adding and removing variables ,displaying variable
values and enclosing a group of tags within a try -catch block.
1.
The tag displays the result of an expression. This is almost similar
to the way <%= %> works.
Example:

This will print Hello World as a response.
2.
The tag sets the result of an expression ev aluation in a 'scope'.
Example

This will set a variable names session with the value 2000.
3.
The tag removes a scoped variable (from a particular scope,
if specified). munotes.in

Page 184


Enterprise Java
178 Example:

This will remove the variable named salary.
4.
The tag catches any Throwable that occurs in its body and
optionally exposes it.
Example:

<% int x = 5/0;%>

This code block will catch ArithmeticException.
B) Conditional Actions Or Flow Control Statements:
Conditi onal Actions are used for conditional processing within a JSP page.
1.
The tag evaluates an expression and displays its body content only
if the expression evaluates to t rue.
Example :

My salary is:



This will print the statement within tag if the condition mentioned
in test evaluates to true.
2. ,, :
The works like a Java switch statement in that it lets you
choose between a number of alternatives. Where the switch statement has
case statements, the tag has tags. Just as a switch
statement has the default clause to specify a def ault action, has
as the default clause.
Example:



munotes.in

Page 185


JSP Standard Tag Libraries
179
${"number1 is le ss than number2"}


${"number1 is less than equal to number2"}




Example





${"number1 is less than number2"}


${"number1 is less than eq ual to number2"}





C) Iterator Actions:
Iterator Actions simplify iteration through collection of objects.
1.
The tag is a commonly used tag because it repeats the nested
body content for fixed number of times or over collection.
Example

Item


munotes.in

Page 186


Enterprise Java
180 This will print the values from 1 to 5.
2.
The tag iterates over tokens which is separated by the
supplied delimeters. It is used for break a string into tokens and iterate
through each of t he tokens to generate output.
This tag has similar attributes as tag except one additional
attributes delims which is used for specifying the characters to be used as
delimiters.
Example



This will print the names as separate tokens.
D.) URL RELATED ACTIONS :
These actions are used to import resources, redirect HTTP responses
,create URLs or encode a request of parameters.
1.
The < c:redirect > tag redirects the browser to a new URL.
Example :

This will redirect to abc.com
2.
The < c:url > tag creates a URL with optional query parameter. It is used
for url encoding or url formatting. This tag automatically performs the
URL rewriting operation.
Example :

3.
The < c:param > tag add the parameter in a containing 'import' tag's URL.
Example :

munotes.in

Page 187


JSP Standard Tag Libraries
181 15.6.2 Functions Tag Library:
The Functions Tag Library provides a number of standard functions, most
of these functions are common string manipulation functions.
The URI of the Functions Tag Library is
“http://java.sun.com/jsp/ jstl/functions” and prefix is fn.
The syntax used for including JSTL Functions tags library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %> Tag Explanation Example Output fn:contains() It is used to test if an input string containing the specified substring in a program. ${fn:contains(‘Java’,’av’ )} True fn:containsIgnoreCase() It is used to test if an input string contains the specified substring as a case insensitive way. ${fn:containsIgnoreCase(‘Java’, 'AV')} True fn:endsWith() It is used to test if an input string ends with the specified suffix. ${fn:endsWith(‘JSP Program’, 'Program')} True fn:escapeXml() It escapes the characters that would be interpreted as XML markup. ${fn:escapeXml(‘It is second String.’)} It is second String. fn:indexOf() It returns an index within a string of first occurrence of a specified substring. ${fn:indexOf(‘Hello World’,’ ‘Hello’)} 0 fn:trim() It removes the blank spaces from both the ends of a string. ${fn:trim(Welcome to JSP programming )} Welcome to JSP programming fn:startsWith() It is used for checking whether the given string is started with a particular string value. ${fn:endsWith(‘JSP Program’, 'JSP')} True fn:split() It splits the string into an array of substrings. ${fn:split(Welcome-to-JSP-Programming, '-')} Welcome To JSP Programming fn:toLowerCase() It converts all the characters of a string to lower case. ${fn:toLowerCase("HELLO")} hello munotes.in

Page 188


Enterprise Java
182 fn:toUpperCase() It converts all the characters of a string to upper case. ${fn:toLowerCase("hello")} HELLO fn:substring() It returns the subset of a string according to the given start and end position. ${fn:substring("This is the first string.", 5, 17)} is the first fn:substringAfter() It returns the subset of string after a specific substring. ${fn:substringAfter(“Chris Kevin”, "Chris")} Kevin fn:substringBefore() It returns the subset of string before a specific substring. ${fn:substringBefore(“Chris Kevin”, "Kevin")} Chris fn:length() It returns the number of characters inside a string, or the number of items in a collection. ${fn:length(“Hello”)} 5 fn:replace() It replaces all the occurrence of a string with another string sequence. ${fn:replace(“Chris Kevin”, "Chris", "Steve")} Steve Kevin
15.6.3 Database/ SQL Tag Library :
The SQL tag library allows the tag to interact with RDBMSs (Relational
Databases) such as Microsoft SQL Server, mySQL, or Oracle.
The URI of the SQL Tag Library i s “http://java.sun.com/jsp/jstl/sql” and
prefix is sql.
The syntax used for including JSTL Database tags library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
1)
The tag is used to create the data source variable
directly from JSP and it is stored inside a scoped variable. It can be used
as input for other database actions.
Example :
user="root" password="1234"/>
This code is used for setting the connection with database server.
munotes.in

Page 189


JSP Standard Tag Libraries
183 2)
The tag is used for executing the SQL query defined in its sql
attribute or the body. It is used to execute an SQL SELECT statement and
saves the result in scoped variable.
Example:

SELECT * from Students;

3)
The tag is used for executing the SQL DML query defined in
its sql attribute or in the tag bod y. It may be SQL UPDATE, INSERT or
DELETE statements.
Example:

INSERT INTO Students VALUES (154,’Chris’, 'Kevin', 25);

4.
The tag sets the parameter value in SQL state ment.
It is used as nested tag for and to provide the
value in SQL query parameter. If null value is provided, the value is set at
SQL NULL for value attribute.
Example:


DELETE FROM Students WHERE Id = ?


5.
The is used to set the specified date for SQL query
parameter.
It is used as nested tag for and < sql:query> to provide the
date and time value for SQL query parameter.
If null value is provided, the value is set at SQL NULL. munotes.in

Page 190


Enterprise Java
184 Example:
<%
Date DoB = new Date("2000/10/16");
int studentId = 151;
%>

UPDATE Student SET dob = ? WHERE Id = ?



6.
The tag is used for transaction management. It is used to
group multiple into common transaction. If you group
multiple SQL queries in a single transaction, database is hit only once.
It is used for ensuring that the database modifications are performed by the
nested actions which can be either rolled back or committed.
Example:
<%
Date DoB = new Date("2000/10/16");
int studentId = 151;
%>


UPDATE Student SET First_Name = ‘Ann’ WHERE Id = 150


UPDATE Student SET Last_Name= ‘Seema’ WHERE Id = 153


INSERT INTO Student VALUES (101,'Kate', 'David', '2021/10/7');


15.6.4 Formatting Ta g Library :
The formatting tags provide support for message formatting, number and
date formatting etc. munotes.in

Page 191


JSP Standard Tag Libraries
185 The url for the formatting tags is http://java.sun.com/jsp/jstl/fmt and prefix
is fmt .
The syntax used for including JSTL FORMATTING tags library in your
JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
1.
The tag is used to Parses the string representation of a
currency, percentage, or number. It is based on the customized formatting
pattern.
Example :
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>


Amo unt is:



Amount is:


2.
The tag is used to format the numerical value using
the specific format or precision. It is used to format percentages,
currencies, and numbers according to the customized formatting pattern.
Example :
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>

Formatting of Number:



Formatted Number -1:


Formatted Number -2:


Formatted Number -3:

munotes.in

Page 192


Enterprise Java
186

Formatted Number -4:


Formatted Number -5:


Formatted Number -6:



3.
The tag parses the string representation of a time and
date. It is used to format the time and date according to a customized
formatting pattern.
Example :
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fm t" uri="http://java.sun.com/jsp/jstl/fmt" %>


fmt:parseDate Tag


Parsed Date:







4.
The tag loads the resource bundle which is used by its tag
body. This tag will make the specified bundle available for all
tags that occurs between t he boundary of
and
tags.
It is used to create the ResourceBundle objects which will be used by their
tag body. munotes.in

Page 193


JSP Standard Tag Libraries
187 Let us define the default resource bundle Simple.java as follows:
package com.javatpoint;
import java.util.ListResou rceBundle;
public class Simple extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = { { "colour.Violet", "Violet" },
{ "colour.Indigo", "Indigo" }, { "colour.Blue", "Blue" }, };
}
Now you can use the below JSTL tags to display the three colors as
follows:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>


fmt:bundle Tag












Output:
1. Violet
2. Indigo
3. Blue
5.
The t ag store the time zone inside a time zone
configuration variable. It is used for copy a time zone object inside a
specified scope variable.
Let's see the simple example to understand the formatting
tag: munotes.in

Page 194


Enterprise Java
188 <%@ taglib uri="http://java.sun.com /jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>


fmt:setTimeZone Tag



Date and Time in Indian Standard Time(IST) Zone:
e="long" />



Date and Time in GMT -
10 time Zone:
type="both" timeS tyle="long" dateStyle="long" />




6. and
The tag is used to load the resource bundle and store
their value in the bundle configuration variable or the name scope
variable.
It is used for creating the ResourceBundle object which will be used by
tag body.
The tag is used for displaying an internationalized
message. It maps the key of localized message to return the value using a
resource bundle specified in the bundle attribute .
Let us define the default resource bundle Main.java as follows:
package com.javatpoint;
import java.util.ListResourceBundle;
public class Main extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = { { "vegetable.Potato", "Potato" },
{ "vegetable.Tomato", "Tomato" }, { "vegetable.Carrot", "Carrot" }, };
} munotes.in

Page 195


JSP Standard Tag Libraries
189 Now, compile the above class as Main.class and make it available in
CLASSPATH of your Web application folder. Now you ca n use the below
JSTL tags to display the three vegetables as follows:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>


fmt:setBundle Tag











15.6.5 XML TAG LIBRARY :
The JSTL XML tags are used for providing a JSP -centric way of manipulating
and creating XML documents. The xml tags provide flow control, transformation
etc.
The url for the xml tags is http://java.sun.com/jsp/jstl/xml and prefix is x.
The JSTL XML tag library h as custom tags used for interacting with
XML data. The syntax used for including JSTL XML tags library in your
JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
1. and tag
The tag is used for displaying the result of an xml Path expression
and writes the result to JSP writer object.
The tag is used for parse the XML data specified either in the
tag body or an attribute. It is used for parse the xml content and the result
will stored inside specifie d variable.
Let's see the simple example to understand the xml and
tag:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

munotes.in

Page 196


Enterprise Java
190 XML Tags


Vegetable Information:





onion
40/kg


Potato
30/kg


Tomato
90/kg




Name of the vegetable is:


Price of the Potato is:



2.
The tag is used to set a variable with the value of an XPath
expression. It is used to store the resul t of xml path expression in a scoped
variable.
Example

munotes.in

Page 197


JSP Standard Tag Libraries
191 3. , ,
The tag is a conditional tag that establish a context for
mutually exclusive conditional operations. It works like a Java switch
statement in which we choose between a numbers of alternatives.
The is subtag of that will include its body if the
condition evaluated be 'true'.
The is also subtag of < x:choose> it follows tags
and runs only if all the prior condition evaluated is 'false'.
The and works like if -else statement. But it must
be placed inside tag.
Example :
<%@ taglib prefix="c" uri="http://java.sun. com/jsp/jstl/core" %>
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>


x:choose Tag


Books Information:





Three mistak es of my life
Chetan Bhagat
200


Tomorrow land
Brad Bird
2000




munotes.in

Page 198


Enterprise Java
192
Book is written by Chetan bhagat


Book is written by Brad Bird


The author is unknown...




Output :
Books Information:
Book is written by Brad Bird
4.
The tag is used for evaluating the test XPath expression. It is a
simple conditional ta g which is used for evaluating its body if the supplied
condition is true.
Example :

Vegetables prices are very low.

15.7 SUMMARY JSTL allows JSP programming developers to create web appli cations
using tags rather than scriptlets (Java code).
1. JSTL tags are XML based tags, they cleanly and consistently blend
into a page’s HTML markup tags.
2. JSTL makes use of UEL which makes it easier to call the getter and
setter methods on Java objects.
3. JSTL increases the processing burden on the server.
4. JSTL is composed of five tag libraries:
a. Core Tag Library munotes.in

Page 199


JSP Standard Tag Libraries
193 b. Functions Tag Library
c. Database/SQL Tag Library
d. Formatting Tag Library
e. XML Tag Library
15.8 LIST OF REFERENCES 1. Java EE 7 for Beginners, Sharanam Shah, V aishali Shah, First
Edition, SPD
Web References :
1. https://www.tutorialspoint.com
2. https://www.javatpoint.com
15.9 QUESTIONS Q1. What are the various advantages of usin g JSTL over scriptlets?
Q2. What are the various disadvantages of using JSTL?
Q3. Explain , and tags with example.
Q4. Explain how database connection can be established and queries can
be executed using Database Tag Library.
Q5. Explain any 5 tags of Formatting Tag Library.
Q6. What are the various conditional and iteration tags in Core Tag
Library?
*****
munotes.in

Page 200

194 UNIT IV
16
INTRODUCTION TO ENTERPRISE
JAVABEANS
Unit Structure
16.0 Objectives
16.1 Introduction
16.1.1 When to use Enterprise Java Beans?
16.1.2 Advantages of Enterprise Java Beans
16.1.3 Disadvantages of Enterprise Java Beans
16.2 Architecture of EJB
16.2.1 Enterprise bean server
16.2.2 Enterprise bean container
16.2.3 Enterprise bean
16.2.4 Enterprise bean clients
16.3 Container and its types
16.4 Types of Enterprise Java Beans
16.4.1 Session Bean
16.4.2 Entity Bean
16.4.3 Message Driven Beans
16.5 Accessing Enterprise Bean’
16.6 How to use Beans in Clients
16.6.1 Remote Clients
16.6.2 Local Clients
16.6.3 Characteristics of Remote clients
16.6.4 Characteristics of Local clients
16.7 Summary
16.8 Refe rences
16.9 Unit End Questions
16.0 OBJECTIVES After going through this chapter, you will be able to:
• Understand use, advantage, disadvantage of EJB
• Analysis architecture of EJB.
• Type of Java Beans
• How to access and use beans in clients munotes.in

Page 201


Introduction to Enterprise Javabeans
195 16.1 INTROD UCTION What is EJB?:
EJB stands for Enterprise Java Bean.
An Enterprise Java Bean is in its basic form any POJO (Plain Old Java
Object) that is registered with the container in which it is deployed.
Enterprise Java Beans are deployed into an EJB container . The EJB
container is governed by the EJB specification.
EJB (Enterprise Java Bean) is used to develop scalable, robust and secured
enterprise applications in java.
EJB is a server -side software element that summarizes business logic of an
application.
Enterprise Java Beans (EJB) is a development architecture for building
highly scalable and robust enterprise level applications to be deployed on
J2EE compliant Application Server such as JBOSS, Web Logic etc.
EJB 3.0 is being a great shift from EJB 2.0 and makes development of
EJB based applications quite easy.
EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE
platform. J2EE platform has component based architecture to provide
multi -tiered, distributed and highly transactional features to enterprise
level applications.
EJB provides an architecture to develop and deploy component based
enterprise applications considering robustness, high scalability, and high
performance. An EJB application can be deployed on any of the
application serve r compliant with the J2EE 1.3 standard specification.
16.1.1 When to use Enterprise Java Beans?:
• Application needs Remote Access: In other words, it is distributed.
• Application needs to be scalable: EJB applications supports load
balancing, clustering and fail -over.
• Application needs encapsulated business logic: EJB application is
differentiated from demonstration and persistent layer.
16.1.2 Advantages of Enterprise Java Beans:
• Interoperability:
EJB architecture is mapped to standard CORBA.EJB make it work with
components developed in different language like VC++ and CORBA.
The EJB client view interface serves as well -defined integration point
between components built using different programming languages.
munotes.in

Page 202


Enterprise Java
196 • One business logic having many presentat ion logic:
EJB performs a separation between business logic and presentation logic.
This separation makes it possible to develop multiple presentation logic
for the same business process.
• Complete Focus only on Business Logic:
This allows the server vend or to concentrate on system level
functionalities, while the developer can concentrate more on only the
business logic for the domain specific applications.
Developer need not code for these hardcore services. The results of
application get more quickly.
• Server -Side Write Once, Run Anywhere:
EJB uses java language which is portable across multiple platforms. They
can be developed once and then deployed multiple platforms without
recompilation or source code modification.
• EJB provides Distributed Transac tion support:
EJB provides transparency for distributed transactions. This means that a
client can begin a transaction and then invoke methods on Beans present
within two different servers, running on different machines, platforms or
JVM.
• It provides of vendor specific enhancements:
Since the EJB specification provides a lot of flexibility for the vendors to
create their own enhancements, the EJB environment may end being
feature rich.
16.1.3 Disadvantages of Enterprise Java Beans:
• The EJB specificatio n is an inconvenient tool because of its vast
documentation and complex nature. A good developer must take the
time to read and study the EJB specification - even if some
information is irrelevant to EJB code writing and deployment.
• EJB requires more dev elopment and debugging resources than basic
Java coding, as it is difficult to determine whether a bug is inside the
code or EJB container.
• EJB implementation is complex. For example, a developer may write
10 or more files (versus one) for a simple appli cation, such as printing
simple text like "hello world."
• EJB specification changes result in obsolete code. Thus, making code
compatible with a new EJB container requires extra effort and higher
costs. munotes.in

Page 203


Introduction to Enterprise Javabeans
197 16.2 ARCHITECTURE OF EJB EJB Architecture:
The Enter prise JavaBeans (EJB) component architecture is designed to
enable enterprises to build scalable, secure, multiplatform, business -
critical applications as reusable, server -side components.
EJB architecture is at the heart of the Java 2 platform, Enterprise Edition
(J2EE). With the growth of the Web and the Internet, more and more
enterprise applications are now Web based, including both intranet and
extranet applications.

Together, the J2EE and EJB architectures provide superior support for
Web -based ent erprise applications.
EJB architecture is composed of:
17 Enterprise bean server
18 Enterprise bean container
19 Enterprise bean
20 Enterprise bean clients
16.2.1 Enterprise Bean Server:
An EJB server is a component transaction server. It supports the EJB
server side component model for developing and deploying distributed
enterprise level applications in multi -tiered environment.
The key responsibilities of an Application Server are:
• Management API
• Process and thread management
• Database connection po oling and caching
• System Resources management munotes.in

Page 204


Enterprise Java
198 16.2.2 Enterprise Bean Container:
The EJB container is one of the logical constructs which makes up the Full
Java EE profile. An EJB container manages the enterprise beans contained
within it. EJB server prov ides one or more containers. From our
architecture diagram, we saw that the EJB container construct is the
second outmost construct of the architecture. Furthermore, its key
responsibilities are:
• It provides a runtime environment for Enterprise Java Bean s
• It provides persistence management
• It is responsible for the Lifecycle management of EJBs
• It is in charge of ensuring that all EJBs are secured
16.2.3 Enterprise Bean:
Enterprise Beans are reu sable modules code that combine related tasks
into well -defined interface.
These enterprise bean EJB components contain the methods that execute
business login and access data sources. Business component developed
using EJB architecture are called as Enterprise Beans.
EJBS are server -side components for encaps ulating application's business
logic. An EJB can offer specific enterprise service either alone or in
conjunction with other EJBs.
16.2.4 Enterprise Bean Clients:
There are two types of client view:
• Remote Client View
• Local Client View
1. Remote Client View:
The remote client view specification became available beginning with EJB
1.1. The remote client view of an enterprise bean is location independent.
A client running in the same JVM as a bean instance uses the same API to
access the bean as a client running in a different JVM on the same or
different machine.
Remote interface: The remote interface specifies the remote business
methods that a client can call on an enterprise bean.
Remote home interface: The remote home interface specifies the
methods u sed by remote clients for locating, creating, and removing
instances of enterprise bean classes.
munotes.in

Page 205


Introduction to Enterprise Javabeans
199 2. Local Client View:
Unlike the remote client view, the local client view of a bean is location
dependent. Local client view access to an enterprise bean req uires both the
local client and the enterprise bean that provides the local client view to be
in the same JVM.
The local client view therefore does not provide the location transparency
provided by the remote client view.
Local interfaces and local home in terfaces provide support for lightweight
access from enterprise bean that are local clients.
Session and entity beans can be tightly couple with their clients, allowing
access without the overhead typically associated with remote method calls.
The local cl ient view specification is available in EJB 2.0 or later.
Local interface:
The local interface is a lightweight version of the remote interface, but for
local clients. It includes business logic methods that can be called by a
local client.
Local home inte rface:
The local home interface specifies the methods used by local clients for
locating, creating, and removing instances of enterprise bean classes.
16.3 CONTAINER AND ITS TYPES EJB Containers:
Enterprise beans (EJB components) are Java programming lang uage
server components that contain business logic. The EJB container provides
local and remote access to enterprise beans.
The container is responsible for creating the enterprise bean, binding the
enterprise bean to the naming service so other applicatio n components can
access the enterprise bean, ensuring only authorized clients have access to
the enterprise bean’s methods, saving the bean’s state to persistent storage,
caching the state of the bean, and activating or passivating the bean when
necessary.
It is responsible for all the operations of the EJB applications.
The container acts as an intermediary action between the business logic of
the bean and the rest of the world of the enterprise application.
 One or more EJB modules can be installed within a single EJB
container.
 The role of EJB container is to perform transactional actions such as, munotes.in

Page 206


Enterprise Java
200 1. Starting a transaction.
2. Rollback a transaction or commit a transaction.
3. Managing various connection pools for the database resources.
4. Bean’s inst ance variables with corresponding data items which are
stored in a database will be synchronized.
The four types of container that J2EE supports:
1. EJB container
2. Web Container
3. Application client container
4. Applet client container
1) EJB Contain er:
 An EJB container will provide the runtime environment for EJB
applications within the application server.
 It is responsible for all the operations of the EJB applications.
 The container acts as an intermediary action between the business
logic of the b ean and the rest of the world of the enterprise
application.
 One or more EJB modules can be installed within a single EJB
container. The role of EJB container is to perform transactional
actions such as,
1. Starting a transaction.
2. Rollback a transacti on or commit a transaction.
3. Managing various connection pools for the database resources.
4. Bean’s instance variables with corresponding data items which are
stored in a database will be synchronized.
2) Web Container:
 A web container implements a we b component such as servlet
container.
 A servlet container supports the operations of a servlet.
 It supports the web server operations and the client java operations
such as JRE,maps the URL specific requests into servlet requests.
 The servlet cotainers ha ve the ability to dynamically add or remove
servlets from the system. munotes.in

Page 207


Introduction to Enterprise Javabeans
201  Individual servlets will get registered by the servlet container.
 The servlet API is provided by different vendors for a specific servlet
standard.
3) Application Client Container:
 An ap plication client container includes set of java classes, libraries
and the set of files that are needed and distributed among various java
client applications which executes on their own JVMs.
 The ACC is responsible for managing the applications execution by
providing all the system services that are needed for the execution of
java client programs.
 It is light -weighted and communicates with different application
servers.
4) Applet client container:
 Like application client container, applet container execut es the client
applications.
 The difference is an applet executes the application in a separate
browser.
 They execute on their own JVMs.
 It supports the applet programming model.
 JEE client may use java plug -in to provide the required environment
that execu tes the applet.
Develope r classes vs. container classes:
 The developer classes are the classes that are authored by the
developers
 The container classes are the classes which supports the container to
manage the container specific functionality.
16.4 TYPES OF ENTERPRISE JAVA BEANS
munotes.in

Page 208


Enterprise Java
202 The EJB 2.0 specification defines three types of Enterprise JavaBeans: the
session bean, the entity bean, and the message -driven bean.
Session beans contain business -processing logic. Entity beans contain
data-processing logic. Message -driven beans allow clients to
asynchronously invoke business logic.
16.4.1 Session Bean :
 Session beans are Java beans which encapsulate the business logic in
a centralized and reusable manner such that it can be used by a
number of clients.
 A ses sion bean objects are short -lived.
 Are not persistent in a database.
 They can be stateful or stateless.
 Execute for a single client.
 Can be transaction aware.
As its name suggests, session beans implement a conversation between a
client and the server side . Session beans execute a particular business task
on behalf of a single client during a single session. They implement
business logic such as workflow, algorithms, and business rules.
Session beans are analogous to interactive sessions. Just as an interac tive
session isn’t shared among users, a session bean is not shared among
clients. Like an interactive session, a session bean isn’t persistent (that is,
its data isn’t saved to a database). Session beans are removed when the
EJB container is shut down or crashes.
You can think of a session bean object as an extension of the client on the
server side. It works for its client, sparing the client from complexity by
executing business tasks inside the server.
Session beans typically contain business process lo gic and workflow, such
as sending an email, looking up a stock price from a database, and
implementing compression and encryption algorithms.
There are 3 types of Session beans :
 Stateless
 Stateful
 Singleton
I. Stateless Session Beans:
A stateless session bean, by comparison, does not maintain any
conversational state. Stateless session beans are pooled by their container
to handle multiple requests from multiple clients. munotes.in

Page 209


Introduction to Enterprise Javabeans
203 II. Stateful Session Beans :
A stateful session bean acts on behalf of a single client and maintains
client -specific session information(called conversational state) across
multiple method calls and transactions. It exists for the duration of a single
client/server session.
III. Singleton Session Beans:
Provide shared data to client and co mponents within an access application
and are instantiated only once per application.
16.4.2 Entity Beans:
If you’ve worked with databases, you’re familiar with persistent data. The
data in a database is persistent; that is, it exists even after the databa se
server is shut down.
Entity beans are persistent objects. They typically represent business
entities, such as customers, products, accounts, and orders. Typically, each
entity bean has an underlying table in a relational database, and each
instance of the bean corresponds to a row in that table.
The state of an entity bean is persistent, transactional, and shared among
different clients. It hides complexity behind the bean and container
common services. Because the clients might want to change the same data,
it’s important that entity beans work within transactions. Entity beans
typically contain data -related logic, such as inserting, updating, and
removing a customer record in the database.
Two types of entity beans are relevant to persistence:
• conta iner-managed persistence (CMP)
• bean -managed persistence (BMP).
In a CMP entity bean, the EJB container manages the bean’s persistence
according to the data -object mapping in the deployment descriptor. Any
change in the entity bean’s state will be autom atically saved to the
database by the container. No code is required in the bean to reflect these
changes or to manage the database connection. On the other hand, a BMP
entity bean has to manage both the database connections and all the
changes to the bean ’s state.(Entity bean that manage their own persistence
are called BMP entity bean.)
16.4.3 Message Driven Beans:
Message -driven beans are enterprise beans that receive and process JMS
messages. Unlike session or entity heans, message -driven be ans have no
interfaces. They can be accessed only through messaging and they do not
maintain any conversational state. munotes.in

Page 210


Enterprise Java
204 Message -driven beans allow asynchronous communication between the
queue and the listener, and provide separation between message
processing and busi ness logic.
Message driven beans are:
 Do not have home and component interface.
 Do not have business methods but define message listener method
which the EJB container invokes to deliver messages.
 Do not hold any state between calls of the message listener method.
 Are relatively short -lived.
 Can be Transaction aware.
 Do not represent directly shared data in the database, but they can
access and update this data.
In synchronous communication, the client blocks until the server -side
object completes processin g. In asynchronous communication, the client
sends its message and does not need to wait for the receiver to receive or
process the message. Session and entity beans process messages
synchronously.
Message -driven beans, on the other hand, are stateless com ponents that
are asynchronously invoked by the container as a result of the arrival of a
Java Message Service (JMS) message. A message -driven bean receives a
message from a JMS destination, such as a queue or topic, and performs
business logic based on the message contents, such as logic to receive and
process a client notification.
An example of a message -driven bean is when a shopper makes an online
purchase order; an order bean could notify a credit verification bean. A
credit verification bean could che ck the shopper’s credit card in the
background and send a notification message for approval. Because this
notification is asynchronous, the shopper doesn’t have to wait for the
background processing to complete.
16.5 ACCESSING ENTERPRISE BEANS Enterprise b eans are accessed by the client in two ways either through a
no-interface view or through a business interface.
• No-interface view :
A no -interface view of an enterprise bean exposes the public methods of
the enterprise bean implementation class to clients .
Clients using the no -interface view of an enterprise bean may invoke any
public methods in the enterprise bean implementation class or any
superclasses of the implementation class. munotes.in

Page 211


Introduction to Enterprise Javabeans
205 • Business interface :
A business interface is a standard Java programmi ng language interface
that contains the business methods of the enterprise bean.
To use a session bean client will have to required either bean's business's
interface methods or enterprise bean's public methods which has a no -
interface view.
Session beans can have more than one business interface. Session beans
should, but are not required to, implement their business interface or
interfaces.
16.6 HOW TO USE ENTERPRISE BEANS IN CLIENTS The client of an enterprise bean obtains a reference to an instance of an
enterprise bean through either dependency injection, using Java
programming language annotations, or JNDI lookup, using the Java
Naming and Directory Interface syntax to find the enterprise bean
instance.
Dependency injection is the simplest way of obta ining an enterprise bean
reference. Clients that run within a Java EE server -managed environment,
Java Server Faces web applications, JAX -RS web services, other
enterprise beans, or Java EE application clients, support dependency
injection using the javax. ejb.EJB annotation.
Applications that run outside a Java EE server -managed environment,
such as Java SE applications, explicit lookup. JNDI supports a must
perform an global syntax for identifying Java EE components to simplify
this explicit lookup.
16.6.1 Remote or Local Access :
1. Local Clients :
A local client has these characteristics .
• It must run in the same application as the enterprise bean it accesses.
• It can be a web component or another enterprise bean.
• To the local client, the location of th e enterprise bean it accesses is not
transparent.
Accessing Local Enterprise Beans Using the No -Interface View :
Client access to an enterprise bean that exposes a local, no -interface view
is accomplished through either dependency injection or JNDI lookup.
To obtain a reference to the no -interface view of an enterprise bean
through dependency injection, use the javax.ejb.EJB annotation and
specify the enterprise bean's implementation class munotes.in

Page 212


Enterprise Java
206 @EJB
ExampleBean exampleBean;
To obtain a reference to the no -interfa ce view of an enterprise bean
through JNDI lookup, use the javax.naming.InitialContext interface's
lookup method:
ExampleBean exampleBean=(ExampleBean)
InitialContext.lookup("java:module/ExampleBean");
Clients do not use the new operator to obtain a new i nstance of an
enterprise bean that uses a no -interface view.
16.6.2 Remote Clients :
A remote client of an enterprise bean has the following characteristics.
It can run on a different machine and a different JVM from the enterprise
bean it accesses. (It is not required to run on a different JVM.)
It can be a web component, an application client, or another enterprise
bean.
To a remote client, the location of the enterprise bean is transparent.
The enterprise bean must implement a business interface. That is, remote
clients may not access an enterprise bean through a no -interface view.
Accessing Remote Enterprise Beans Using the business Interface
View :
Client access to an enterprise bean that implements a remote business
interface is
accomplished through eit her dependency injection or JNDI lookup.
To obtain a reference to the remote business interface of an enterprise
bean through
dependency injection, use the javax.ejb.EJB annotation and specify the
enterprise bean's remote business interface name:
@EJB
Exam ple:
To obtain a reference to a remote business interface of an enterprise bean
through JNDI lookup, use the javax.naming.InitialContext interface's
lookup method:
ExampleRemote example=(ExampleRemote)
InitialContext.lookup("java:global/myApp/ExampleRemote "); munotes.in

Page 213


Introduction to Enterprise Javabeans
207 16.6.3 Characteristics of Local clients :
• They must run in the same application.
• Clients can be a web component or other enterprise bean.
• To the local client the location of the enterprise bean it accesses is not
transparent.

16.6.4 Characterist ics of Remo te clients :
• An enterprise bean which will access the client, called remote client if
it run on an other machine or JVM however, running on different
JVM is not necessary.
• Clients can be a web component, an application client, or other
enterp rise bean.
• To the Remote client the location of the enterprise bean it accesses is
transparent
• Remote clients which will use an enterprise bean that, enterprise bean
will must have to implement the business interface.

EnterpriseBeanApplication/Packag ingEnterpriseBeans

munotes.in

Page 214


Enterprise Java
208 16.7 SUMMARY EJB stands for Enterprise Java Beans . EJB is an essential part of a J2EE
platform. J2EE platform has component based architecture to provide
multi -tiered, distributed and highly transactional features to enterprise
level a pplications.
EJB provides an architecture to develop and deploy component based
enterprise applications considering robustness, high scalability, and high
performance. An EJB application can be deployed on any of the
application server compliant with the J 2EE 1.3 standard specification
16.8 REFERENCES 1. Java EE for beginners by -Sharanam Shah
2. Advanced Java Programming by -Uttan Kumar Roy
3. Java EE 8 by -Elder Moreas
4. www.javatutorial.com
16.9 UNIT END QUESTIONS 1. Explain EJB with advantages and disadvantages?
2. Explain different types of EJB?
3. How to use Enterprise Beans in clients?
4. Explain characteristics of local clients?
*****









munotes.in

Page 215

209 17
WORKING WITH SESSION BEANS AND
MESSAGE DRIVEN BEAN
Unit Structure
17.0 Objectives
17.1 Introduction
17.1.1 What is Session Beans?
17.1.2 When to use Session Bean?
17.2 Types of Session Beans
17.3 Remote and local Interface
17.4 Accessing Interfaces
17.5 Accessing Local Enterprise Beans That Implement Business
Interfaces
17.6 When to Use Message -Driven Beans
17.7 The Lifecycle of a Message -Driven Bean
17.8 Message Driven Bean Example
17.9 Summary
17.10 References
17.11 Uni t End Questions
17.0 OBJECTIVES After going through this chapt er, you will be able to :
• Understand use, advantage, disadvantage of Session Beans
• When to use session beans.
• Type of Session Beans
• How to access and beans in different interfaces
• Under stand what is message Driven Beans
• Life Cycle of Message Driven Beans
• Use of Message Driven Beans
17.1 INTRODUCTION 17.1.1 What is Session Bean? :
A session bean is an EJB 3.0 or EJB 2.1 enterprise bean component
created by a client for the duration of a single client/server session. The
session bean performs work for its client, shielding it from complexity by
executing business tasks inside the server. munotes.in

Page 216


Enterprise Java
210 A session bean is not persistent. (That is, its data is not saved to a
database.)
A session bean encapsulates business logic that can be invoked
programmatically by a client over local, remote, or web service client
views.
17.1.2 When to Use Session Beans :
Stateful session beans are appropriate if any of the following conditions
are true.
• The bean’s s tate represents the interaction between the bean and a
specific client.
• The bean needs to hold information about the client across method
invocations.
• The bean mediates between the client and the other components of the
application, presenting a simpli fied view to the client.
• Behind the scenes, the bean manages the work flow of several
enterprise beans.
To improve performance, you might choose a stateless session bean if it
has any of these traits.
• The bean’s state has no data for a specific client.
• In a single method invocation, the bean performs a generic task for all
clients. For example, you might use a stateless session bean to send an
email that confirms an online order.
• The bean implements a web service.
Singleton session beans are appropr iate in the following circumstances.
• State needs to be shared across the application.
• A single enterprise bean needs to be accessed by multiple threads
concurrently.
• The application needs an enterprise bean to perform tasks upon
application startup a nd shutdown.
• The bean implements a web service.
17.2 TYPES OF SESSION BEANS Session beans are of three types: stateful, stateless, and singleton.
Stateful Session Beans :
The state of an object consists of the values of its instance variables. In a
statef ul session bean, the instance variables represent the state of a unique munotes.in

Page 217


Working with Session Beans and Message Driven Bean
211 client/bean session. Because the client interacts (“talks”) with its bean, this
state is often called the conversational state .
As its name suggests, a session bean is similar to an in teractive session. A
session bean is not shared; it can have only one client, in the same way
that an interactive session can have only one user. When the client
terminates, its session bean appears to terminate and is no longer
associated with the client.
The state is retained for the duration of the client/bean session. If the client
removes the bean, the session ends and the state disappears. This transient
nature of the state is not a problem, however, because when the
conversation between the client an d the bean ends, there is no need to
retain the state.
Stateless Session Beans :
A stateless session bean does not maintain a conversational state with the
client. When a client invokes the methods of a stateless bean, the bean’s
instance variables may cont ain a state specific to that client but only for
the duration of the invocation. When the method is finished, the client -
specific state should not be retained. Clients may, however, change the
state of instance variables in pooled stateless beans, and this state is held
over to the next invocation of the pooled stateless bean. Except during
method invocation, all instances of a stateless bean are equivalent,
allowing the EJB container to assign an instance to any client. That is, the
state of a stateless se ssion bean should apply across all clients.
Because they can support multiple clients, stateless session beans can offer
better scalability for applications that require large numbers of clients.
Typically, an application requires fewer stateless session b eans than
stateful session beans to support the same number of clients.
A stateless session bean can implement a web service, but a stateful
session bean cannot.
Singleton Session Beans :
A singleton session bean is instantiated once per application and exi sts
for the lifecycle of the application. Singleton session beans are designed
for circumstances in which a single enterprise bean instance is shared
across and concurrently accessed by clients.
Singleton session beans offer similar functionality to statel ess session
beans but differ from them in that there is only one singleton session bean
per application, as opposed to a pool of stateless session beans, any of
which may respond to a client request. Like stateless session beans,
singleton session beans ca n implement web service endpoints.
Singleton session beans maintain their state between client invocations but
are not required to maintain their state across server crashes or shutdowns. munotes.in

Page 218


Enterprise Java
212 Applications that use a singleton session bean may specify that the
singleton should be instantiated upon application startup, which allows the
singleton to perform initialization tasks for the application. The singleton
may perform cleanup tasks on application shutdown as well, because the
singleton will operate throughou t the lifecycle of the application.
17.3 REMOTE AND LOCAL INTERFACES 1. Local interface :
The local interface is used for Local client. Local interface are the type of
interface that are used for making local connections to EJB. @Local
annotation is used fo r declaring interface as Local. Javax.ejb.Local
package is used for creating Local interface.
Syntax:
@Local
public interface InterfaceName { ... }
Example:
Package ejb;
import javax.ejb.Local;
@Local
Public interface SessionLocal
{
}
2. Remote interface :
The Remote interface is used for Remote client. Remote interface are the
interface that has the methods that relate to a particular bean instance.
@Remote annotation is used for declaring interface as Remote.
Javax.ejb.Remote package is used for creating Remote interface.
Syntax:
@Remote
public interface InterfaceName { ... }
Example:
Package ejb;
import javax.ejb.Remote;
@Remote
Public interface SessionRemote munotes.in

Page 219


Working with Session Beans and Message Driven Bean
213 {
String getMessage();
String getAddress();
}
17.4 ACCESSING INTERFACES Accessing Loc al Enterprise Beans Using the No -Interface View :
Client access to an enterprise bean that exposes a local, no -interface view
is accomplished through either dependency injection or JNDI lookup.
• To obtain a reference to the no -interface view of an enterpri se bean
through dependency injection, use the javax.ejb.EJB annotation and
specify the enterprise bean’s implementation class:
• @EJB
ExampleBean exampleBean;
• To obtain a reference to the no -interface view of an enterprise bean
through JNDI lookup, use t he javax.naming.InitialContext interface’s
lookup method:
• ExampleBean exampleBean = (ExampleBean)
InitialContext.lookup("java:module/ExampleBean");
Clients do not use the new operator to obtain a new instance of an
enterprise bean that uses a no -interface view.
17.5 ACCESSING LOCAL ENTERPRISE BEANS THAT IMPLEMENT BUSINESS INTERFACES Client access to enterprise beans that implement local business interfaces
is accomplished through either dependency injection or JNDI lookup.
• To obtain a reference to th e local business interface of an enterprise
bean through dependency injection, use the javax.ejb.EJB annotation
and specify the enterprise bean’s local business interface name:
• @EJB
Example example;
• To obtain a reference to a local business interface o f an enterprise
bean through JNDI lookup, use the javax.naming.InitialContext
interface’s lookup method:
• ExampleLocal example = (ExampleLocal)
InitialContext.lookup("java:module/ExampleLocal"); munotes.in

Page 220


Enterprise Java
214 17.6 WHEN TO USE MESSAGE -DRIVEN BEANS A message dr iven bean (MDB) is a bean that contains business logic. But,
it is invoked by passing the message. So, it is like JMS Receiver.
MDB asynchronously receives the message and processes it.
A message driven bean receives message from queue or topic, so you mus t
have the knowledge of JMS API.
A message -driven bean is an enterprise bean that allows Java EE
applications to process messages asynchronously. This type of bean
normally acts as a JMS message listener, which is similar to an event
listener but receives JMS messages instead of events. The messages can be
sent by any Java EE component (an application client, another enterprise
bean, or a web component) or by a JMS application or system that does
not use Java EE technology. Message -driven beans can process JMS
messages or other kinds of messages.

Session beans allow you to send JMS messages and to receive them
synchronously but not asynchronously. To avoid tying up server
resources, do not to use blocking synchronous receives in a server -side
component; in general, JMS messages should not be sent or received
synchronously. To receive messages asynchronously, use a message -
driven bean.
17.7 THE LIFECYCLE OF A MESSAGE -DRIVEN BEAN Figure illustrates the stages in the lifecycle of a message -driven bean.
Figure illustrates Lifecycle of a Message -Driven Bean :
munotes.in

Page 221


Working with Session Beans and Message Driven Bean
215 The EJB container usually creates a pool of message -driven bean
instances. For each instance, the EJB container performs these tasks.
1. If the message -driven bean uses dependency injection, the container
injects these references before instantiating the instance.
2. The container calls the method annotated @PostConstruct, if any.
Like a stateless session bean, a message -driven bean is never passivated
and has only two states: nonexistent and ready to receiv e messages.
At the end of the lifecycle, the container calls the method annotated
@PreDestroy, if any. The bean’s instance is then ready for garbage
collection
17.8 MESSAGE DRIVEN BEAN EXAMPLE To create the message driven bean, you need to declare @Message Driven
annotation and implement MessageListener interface.
In eclipse ide, create EJB Project then create a class as given below:
File: MyListener.java
1. package com.javatpoint;
2. import javax.ejb.MessageDriven;
3. import javax.jms.*;
4.
5. @Mes sageDriven(mappedName="myTopic")
6. public class MyListener implements MessageListener{
7. @Override
8. public void onMessage(Message msg) {
9. TextMessage m=(TextMessage)msg;
10. try{
11. System.out.println("mes sage received: "+m.getText());
12. }catch(Exception e){System.out.println(e);}
13. }
14. }
17.9 SUMMARY A message -driven bean is an enterprise bean that allows Java EE
applications to process messages asynchronously. This type of bean
normally acts as a JMS message listener, which is similar to an event
listener but receives JMS messages instead of events. The messages can be
sent by any Java EE component (an application client, another enterprise munotes.in

Page 222


Enterprise Java
216 bean, or a web component) or by a JMS ap plication or system that does
not use Java EE technology. Message -driven beans can process JMS
messages or other kinds of messages.
The most visible difference between message -driven beans and session
beans is that clients do not access message -driven bean s through
interfaces. Unlike a session bean, a message -driven bean has only a bean
class. A session bean encapsulates business logic that can be invoked
programmatically by a client over local, remote, or web service client
views. To access an application that is deployed on the server, the client
invokes the session bean’s methods .
17.10 REFERENCES 1. Java EE for beginners by -Sharanam Shah
2. Advanced Java Programming by -Uttan Kumar Roy
3. Java EE 8 by -Elder Moreas
4. www.javatutorial.com
17.11 UNIT END QUESTIONS 1. What is session beans? Explain use of session beans.
2. What are the types of session beans?
3. Explain local and remote interfaces
4. What is Message Driven Beans with its uses?
5. Explain Lifecycle of Message Driven Beans?
6. Write a program to show implementation of Message Driven Beans ?
***** munotes.in

Page 223

217 18
INTERCEPTORS
Unit Structure
18.0 Objectives
18.1 Introduction
18.2 Interceptor Metadata Annotations
18.3 Interceptor Classes
18.4 Interceptor Lifecycle
18.5 The Interceptor Application
18.6 Running the interceptor Example
18.7 Services
18.7.1Na ming Service
18.7.2 Directory Service
18.8 Characteristics of Directory Services
18.9 Architecture
18.10 Different Packages
18.11 Resources and JNDI Naming
18.12 Summary
18.13 References
18.14 Unit End Questions
18.0 OBJECTIVES After going through this chapter, you will be able to :
• Understand what is interceptors
• LifeCycle of interceptors
• Different annotations of interceptors
• Understand what is naming directory
• Different packages of directory
• Its Architecture
18.1 INTRODUCTION Intercept ors are used in conjunction with Java EE managed classes to
allow developers to invoke interceptor methods on an associated target
class , in conjunction with method invocations or lifecycle events.
Common uses of interceptors are logging, auditing, and pro filing. An
interceptor can be defined within a target class as an interceptor method ,
or in an associated class called an interceptor class . Interceptor classes munotes.in

Page 224


Enterprise Java
218 contain methods that are invoked in conjunction with the methods or
lifecycle events of the tar get class.
Interceptor classes and methods are defined using metadata annotations, or
in the deployment descriptor of the application containing the interceptors
and target classes.
18.2 INTERCEPTOR METADATA ANNOTATIONS Interceptor Metadata Annotation Description javax.interceptor.AroundInvoke Designates the method as an interceptor method. javax.interceptor.AroundTimeout Designates the method as a timeout interceptor, for interposing on timeout methods for enterprise bean timers. javax.annotation.PostConstruct Designates the method as an interceptor method for post-construct lifecycle events. javax.annotation.PreDestroy Designates the method as an interceptor method for pre-destroy lifecycle events.
18.3 INTERCEPTOR CLASSES Interceptor classes may be designated with the optional
javax.interceptor.Interceptor annotation, but interceptor classes aren’t
required to be so annotated. An interceptor class must have a public, no -
argument constructor.
The target class can have any number of interceptor classes associated
with it. The order in which the interceptor classes are invoked is
determined by the order in which the interceptor classes are defined in the
javax.interceptor.Interceptors annotation. However, this order can be
overridden in the deployment de scriptor.
Interceptor classes may be targets of dependency injection. Dependency
injection occurs when the interceptor class instance is created, using the
naming context of the associated target class, and before any
@PostConstruct callbacks are invoked.
18.4 INTERCEPTOR LIFECYCLE Interceptor classes have the same lifecycle as their associated target class.
When a target class instance is created, an interceptor class instance is also
created for each declared interceptor class in the target class. That is , if the
target class declares multiple interceptor classes, an instance of each class
is created when the target class instance is created. The target class
instance and all interceptor class instances are fully instantiated before any
@PostConstruct call backs are invoked, and any @PreDestroy callbacks munotes.in

Page 225


Interceptors
219 are invoked before the target class and interceptor class instances are
destroyed.
18.5 THE INTERCEPTOR APPLICATION The interceptor example demonstrates how to use an interceptor class,
containing an @Around Invoke interceptor method, with a stateless session
bean.
The HelloBean stateless session bean is a simple enterprise bean with two
business methods, getName and setName, to retrieve and modify a string.
The setName business method has an @Interceptors ann otation that
specifies an interceptor class, HelloInterceptor, for that method.
@Interceptors(HelloInterceptor.class)
public void setName(String name) {
this.name = name;
}
The HelloInterceptor class defines an @AroundInvoke interceptor
method, modifyG reeting, that converts the string passed to
HelloBean.setName to lowercase.
@AroundInvoke
public Object modifyGreeting(InvocationContext ctx) throws Exception {
Object[] parameters = ctx.getParameters();
String param = (String) parameters[0];
param = param.toLowerCase();
parameters[0] = param;
ctx.setParameters(parameters);
try {
return ctx.proceed();
} catch (Exception e) {
logger.warning("Error calling ctx.proceed in modifyGreeting()");
return null;
}
}
The parameters to HelloBean.setName are retrieved and stored in an
Object array by calling the InvocationContext.getParameters method.
Because setName has only one parameter, it is the first and only element
in the array. The string is set to lowercase and stored in the parameters
array, then passed to InvocationContext.setParameters. To return control
to the session bean, InvocationContext.proceed is called. munotes.in

Page 226


Enterprise Java
220 The user interface of interceptor is a JavaServer Faces web application
that consists of two Fa celets views: index.xhtml, which contains a form
for entering the name, and response.xhtml, which displays the final name.
18.6 RUNNING THE INTERCEPTOR EXAMPLE You can use either NetBeans IDE or Ant to build, package, deploy, and
run the interceptor exampl e.
To Run the interceptor Example Using NetBeans IDE :
1. From the File menu, choose Open Project.
2. In the Open Project dialog, navigate to tut -install/examples/ejb/.
3. Select the interceptor folder and click Open Project.
4. In the Projects tab, right -click the interceptor project and select Run.
This will compile, deploy, and run the interceptor example, opening a
web browser page to http://localhost:8080/interceptor/.
5. Type a name into the form and select Submit.
The name will be converted to lowerca se by the method interceptor
defined in the HelloInterceptor class.
To Run the interceptor Example Using Ant :
1. Go to the following directory:
tut-install/examples/ejb/interceptor/
2. To compile the source files and package the application, use the
follow ing command:
ant
This command calls the default target, which builds and packages the
application into a WAR file, interceptor.war, located in the dist
directory.
3. To deploy and run the application using Ant, use the following
command:
ant run
This comma nd deploys and runs the interceptor example, opening a
web browser page to http://localhost:8080/interceptor/.
4. Type a name into the form and select Submit :
The name will be converted to lowercase by the method interceptor
defined in the Hello Intercepto r class.
munotes.in

Page 227


Interceptors
221 18.7 SERVICES The Java Naming and Directory Interface™ (JNDI) is an application
programming interface (API) that provides naming and directory
functionality to applications written using the Java™ programming
language. It is defined to be indepen dent of any specific directory service
implementation. Thus a variety of directories -new, emerging, and already
deployed can be accessed in a common way.
18.7.1 Naming Service:
The Java Naming and Directory Interface (JNDI) is an application
programming i nterface (API) for accessing different kinds of naming and
directory services. JNDI is not specific to a particular naming or directory
service, it can be used to access many different kinds of systems including
file systems; distributed objects systems li ke CORBA, Java RMI, and
EJB; and directory services like LDAP, Novell NetWare, and NIS+.
JNDI is similar to JDBC in that they are both Object -Oriented Java APIs
that provide a common abstraction for accessing services from different
vendors. While JDBC can be used to access a variety of relational
databases, JNDI can be used to access a variety of of naming and directory
services. Using one API to access many different brands of a service is
possible because both JDBC and JNDI subscribe to the same architec tural
tenet: Define a common abstraction that most vendors can implement. The
common abstraction is the API. It provides an objectified view of a service
while hiding the details specific to any brand of service. The
implementation is provided by the vendo r, it plugs into the API and
implements code specific to accessing that vendor's product.
JNDI provides two APIs and one SPI. JNDI has a naming API that allows
Java applications to access naming systems like CORBA's Naming
services and a directory API that extends the naming service to provide
access to directory services like LDAP. JNDI also has a SPI (Service -
Provider Interface) which is a programming model that vendors use to
write JNDI plug -ins or implementations for their specific product. Each
vendor' s plug -in is called a service -provider. A service -provider
implements the JNDI APIs so that a Java application can access that
vendor's product. For the most part, JNDI hides the implementation details
of the a service -provider so that Java developer that uses JNDI can use the
same objects and method regardless of the brand of naming or directory
service accessed. This is the real power behind APIs like JDBC and JNDI:
They provide one programming model for accessing many different
products; there is no need to learn a different programming model every
time a different product is used.
18.7.2 Directory Service :
Directory services are an essential part of today’s network -centric
computing infrastructure. Directory -enabled applications now power
almost all the mission critical processes of an enterprise, including munotes.in

Page 228


Enterprise Java
222 resource planning, value chain management, security and firewalls, and
resource provisioning. Directory services also provide the foundation for
deployment of e -business and extranet applications. So w hat exactly is a
Directory Service?
A directory service is the collection of software and processes that store
information about your enterprise, subscribers, or both. An example of a
directory service is the Domain Name System (DNS), which is provided
by DNS servers. A DNS server stores the mappings of computer host
names and other forms of domain name to IP addresses. A DNS client
sends questions to a DNS server about these mappings (e.g. what is the IP
address of test.example.com?). Thus, all of the comp uting resources
(hosts) become clients of the DNS server. The mapping of host names
enables users of the computing resources to locate computers on a
network, using host names rather than complex numerical IP addresses.
Whereas the DNS server stores only t wo types of information: names and
IP addresses, an LDAP directory service can store information on many
other kinds of real -world and conceptual objects. Sun Java System
Directory Server stores all of these types of information in a single,
network -access ible repository. You may for example want to store
physical device information, employee information (name, E -mail
address), contract or account information (name, delivery dates, contract
numbers, etc.), authentication information, manufactured production
information. It is worth noting that although a directory service can be
considered an extension of a
18.8 CHARACTERISTICS OF DIRECTORY SERVICES • Hierarchical naming model :
A hierarchical naming model uses the concept of containment to reduce
ambiguity between names and simplify administration. The name for most
objects in the directory is relative to the name of some other object which
conceptually contains it. For example, the name of an object representing
an employee of a particular company contains the name of the object
representing the company, and the name of the company might contain the
name of the objects representing the country where the company operates,
e.g. cn=John Smith, o=Example Corporation, c=US. Together the names
of all objects in th e directory service form a tree, and each Directory
Server holds a branch of that tree, which in the Sun Java System Directory
Server documentation is also referred to as a suffix.
• Extended search capability :
Directory services provide robust search capa bilities, allowing searches on
individual attributes of entries.
• Distributed information model :
A directory service enables directory data to be distributed across multiple
servers within a network. munotes.in

Page 229


Interceptors
223 • Shared network access :
While databases are defined in terms of APIs, directories are defined in
terms of protocols. Directory access implies network access by definition.
Directories are designed specifically for shared access among applications.
This is achieved through the object -oriented schema model. By contrast,
most databases are designed for use only by particular applications and do
not encourage data sharing.
• Replicated data :
Directories support replication (copies of director y data on more than one
server) which make information systems more acces sible and more
resistant to failure.
• Datastore optimized for reads :
The storage mechanism in a directory service is generally designed to
support a high ratio of reads to writes.
• Extensible schema :
The schema describes the type of data stored in the di rectory. Directory
services generally support the extension of schema, meaning that new data
types can be added to the directory.
18.9 ARCHITECTURE The JNDI architecture consists of an API and a service provider interface
(SPI). Java applications use the J NDI API to access a variety of naming
and directory services. The SPI enables a variety of naming and directory
services to be plugged in transparently, thereby allowing the Java
application using the JNDI API to access their services.


munotes.in

Page 230


Enterprise Java
224 Packaging :
JNDI is included in the Java SE Platform. To use the JNDI, you must have
the JNDI classes and one or more service providers. The JDK includes
service providers for the following naming/directory services:
• Lightweight Directory Access Protocol (LDAP)
• Common Object Request Broker Architecture (CORBA) Common
Object Services (COS) name service
• Java Remote Method Invocation (RMI) Registry
• Domain Name Service (DNS)
Other service providers can be downloaded from the JNDI page or
obtained from other vendors.
18.10 DIFFERENT PACKAGES The JNDI is divided into five packages:
• javax.naming
• javax.naming.directory
• javax.naming.ldap
• javax.naming.event
• javax.naming.spi
Naming Package :
The javax.naming package contains classes and interfaces for accessing
naming services.
Context :
The javax.naming package defines a Context interface, which is the core
interface for looking up, binding/unbinding, renaming objects and creating
and destroying subcontexts.
Lookup :
The most commonly used operation is lookup(). You sup ply lookup() the
name of the object you want to look up, and it returns the object bound to
that name.
Bindings :
listBindings() returns an enumeration of name -to-object bindings. A
binding is a tuple containing the name of the bound object, the name of the
object's class, and the object itself.
munotes.in

Page 231


Interceptors
225 List:
list() is similar to listBindings(), except that it returns an enumeration of
names containing an object's name and the name of the object's class. list()
is useful for applications such as browsers that want to discover
information about the objects bound within a context but that don't need
all of the actual objects. Although listBindings() provides all of the same
information, it is potentially a much more expensive operation.
Name :
Name is an interface that represents a generic name —an ordered sequence
of zero or more components. The Naming Systems use this interface to
define the names that follow its conventions as described in the Naming
and Directory Concepts lesson.
References :
Objects are stored in nam ing and directory services in different ways. A
reference might be a very compact representation of an object.
The JNDI defines the Reference class to represent reference. A reference
contains information on how to construct a copy of the object. The JNDI
will attempt to turn references looked up from the directory into the Java
objects that they represent so that JNDI clients have the illusion that what
is stored in the directory are Java objects.
18.11 RESOURCES AND JNDI NAMING In a distributed applicatio n, components need to access other components
and resources, such as databases. For example, a servlet might invoke
remote methods on an enterprise bean that retrieves information from a
database. In the Java EE platform, the Java Naming and Directory
Interface (JNDI) naming service enables components to locate other
components and resources.
A resource is a program object that provides connections to systems, such
as database servers and messaging systems. (A Java Database
Connectivity resource is sometime s referred to as a data source.) Each
resource object is identified by a unique, people -friendly name, called the
JNDI name. For example, the JNDI name of the JDBC resource for the
Java DB database that is shipped with the GlassFish Server is
jdbc/__defaul t.
An administrator creates resources in a JNDI namespace. In the GlassFish
Server, you can use either the Administration Console or the asadmin
command to create resources. Applications then use annotations to inject
the resources. If an application uses resource injection, the GlassFish
Server invokes the JNDI API, and the application is not required to do so.
However, it is also possible for an application to locate resources by
making direct calls to the JNDI API. munotes.in

Page 232


Enterprise Java
226 A resource object and its JNDI name are bound together by the naming
and directory service. To create a new resource, a new name/object
binding is entered into the JNDI namespace. You inject resources by using
the @Resource annotation in an application.
You can use a deployment descriptor to ov erride the resource mapping
that you specify in an annotation. Using a deployment descriptor allows
you to change an application by repackaging it rather than by both
recompiling the source files and repackaging. However, for most
applications, a deploymen t descriptor is not necessary.
Data source resource definition in Javav EE :
DataSource resources are used to define a set of properties required to
identify and access a database through the JDBC API. These properties
include information such as the URL of the database server, the name of
the database, and the network protocol to use to communicate with the
server. DataSource objects are registered with the Java Naming and
Directory Interface (JNDI) naming service so that applications can use the
JNDI API t o access a DataSource object to make a connection with a
database.
Prior to Java EE 7, DataSource resources were created administratively as
described in Configuring WebLogic JDBC Resources in Administering
JDBC Data Sources for Oracle WebLogic Server. Jav a EE 7 provides the
option to programmatically define DataSource resources for a more
flexible and portable method of database connectivity.
The name element uniquely id entifies a DataSource and is registered with
JNDI. The value specified in the name ele ment begins with a namespace
scope. Java EE 7 includes the following scopes:
• java:comp : Names in this namespace have per -component visibility.
• java:module : Names in this namespace are shared by all components
in a module, for example, the EJB component s defined in an a ejb -
jar.xml file.
• java:app : Names in this namespace are shared by all components and
modules in an application, for example, the application -client, web,
and EJB components in an .ear file.
• java:global : Names in this namespace are sha red by all the
applications in the server.
18.12 SUMMARY Interceptors are used in conjunction with Java EE managed classes to
allow developers to invoke interceptor methods on an associated target
class, in conjunction with method invocations or lifecycle events .
Common uses of interceptors are logging, auditing, and profiling. munotes.in

Page 233


Interceptors
227 Clients use the naming service to locate objects by name . The Java
Naming and Directory Interface (JNDI) is designed by Sun Microsystems
Ltd. to simplify access to the directory infr astructure, which advanced
network applications are being built on, by providing an unified set of
interfaces
18.13 REFERENCES 1. Java EE for beginners by -Sharanam Shah
2. Advanced Java Programming by -Uttan Kumar Roy
3. Java EE 8 by -Elder Moreas
4. www.javatutorial.com
18.14 UNIT END QUESTIONS 1. What is interceptors with different annotations?
2. Explain interceptors lifecycle?
3. Explain the steps for running interceptors application?
4. Explain interceptors with example?
5. What is naming ser vice and directory service ?
6. Explain Characteristics of Directory Service?
7. Explain different packages of java naming directory?

*****
munotes.in

Page 234

228 UNIT V
19
PERSISTENCE, OBJECT/RELATIONAL
MAPPING AND JPA
Unit Structure
19.1 Objectives
19.2 Persistence, Object/Relational Mapping And JPA
19.3 What is Persistence?
19.4 Persistence in Java
19.5 Current Persistence Standards in Java
19.6 Why another Persistence Standards?
19.7 Object/Relational Mapping
19.8 Summary
19.9 Sample Questions
19.10 References
19.1 OBJECTIVES This chapter will introduce Data Persistence it’s means for an application
to persist and retrieve information from a non -volati le storage system.
Persistence is vital to enterprise applications because of the required
access to relational databases.
19.2 PERSISTENCE, OBJECT/RELATIONAL MAPPING AND JPA Data is an important asset to any computer application. All computer
applications require that a person or another computer access their data.
This data is used in different ways.
Data can be:
 Read -only
 Read -write
 Read for update over multiple requests
 Modified through batch updates
 Used in bulk data retrieval
The attention span of a c omputer is only as long as its cord is connected to
a power supply. The precious data is within the confines of electronic munotes.in

Page 235


Persistence, Object/Relational Mapping and JPA
229 memory. If the application does not preserve data when it was powered
off, the application is of little or rather no practical use. H ence, it is
required to make the precious data live longer than the application. This is
where Persistence comes in.
19.3 WHAT IS PERSISTENCE? Most business applications require that data must be persistent. Data can
be labeled as persistent only when it m anages to survive day to day
problems such as system crashes and network failures. Often multiple
users request for data simultaneously. Here, there is a definite possibility
of data getting corrupt, if mid -request, system failure, occurs. Maintaining
the persistence of data in an enterprise wide application is quite a
challenging job.
In enterprise application architecture, data persistence is implemented as:
 Having data stored outside an application’s active memory, known as
persistent data store , typical ly, a relational database or an object
database or a flat file system
 Having a rollback system , where, in case of system failure, the state
of the data is rolled back to its last known valid data state
Persistence is one of the fundamental concepts of appl ication
development . It allows DATA to outlive the execution of an application
that created it. It is one of the most vital pieces of an application without
which all the data is simply lost. Majority of applications use persistent
data. For example, GUI a pplications need to store user preferences across
program invocations, Web applications track user movements and orders
over long periods of time.
Hence, it is imperative to choose an appropriate persistence data store.
Often when choosing the persistence data store the following fundamental
qualifiers are considered:
1. The length of time data must be persisted
2. The volume of data
Application may consider an HTTP session when the life of a piece of
data is limited to the user’s session. However, persis tence over several
sessions or several users requires a larger data store. Large amounts of
data should not be stored in an HTTP session, instead a database should be
considered. The type of database that is chosen also plays an important
influence on the architecture and design.
19.4 PERSISTENCE IN JAVA Most of enterprise systems and applications save data into a relational
database of some kind. This is why persistence has been a major
application development concern for many decades. Persistence in Java munotes.in

Page 236


Enterprise Java
230 usually means storing data in a relational database using SQL. In Java,
persistence is accomplished by storing data in a Relational Database
Management System [RDBMS]. SQL is used to get data in and out of the
relational database. Java Database Connectivit y [JDBC]: The Java API IS
used to connect to the RDBMS and fire SQL statements.
Persistence of Object -Oriented Models :
Today most of the development is carried out in an object -oriented manner
using languages such as Smalltalk, C++ and Java. Object [Domain ]
modelling is a concept always linked with Persistence. In fact, it is often
the domain model that is persisted.
Object Oriented Programming is based on OBJECTS that represent the
business model [the real world]. Objects are easily traversed through
relationship graphs using inheritance, associations. When thinking in
terms of Java as the programming language of choice, the business logic
of an application works with Objects of different class types.
However, when dealing with the data store, it’s importa nt to note that the
tables of a database are not Objects, which becomes an issue. This is
where the concept of Object Persistence comes in. Object Persistence
deals with persistence in object -oriented programs such as Java. It means
determining how objects and their relationships are persisted in a
relational database.
Object persistence is about:
 Mapping object state
 Determining how an object’s state [data stored in member variables of
an object] is stored in database table columns
 Dealing with the fact th at object state types may not align with
relational database types
 Mapping object relationships
 Determining how associations between objects are stored as relational
database keys or in relational database intersection tables
Why Object -Oriented Models?
 Business logic can be implemented in Java as opposed to stored
procedures
 Design patterns and sophisticated object -oriented concepts such as
inheritance and polymorphism can be used
 Provides code reusability and maintainability
In most of the applications, storing and retrieving information usually
involves some kind of interaction with a relational database. munotes.in

Page 237


Persistence, Object/Relational Mapping and JPA
231 Why Relational Database? :
Today, computer applications that involve storing data, involve accessing
a relational database. Relational databases are the persistence store for
most applications. A relational database is a choice because of the
following:
 It is a proven data persistence technology
 Provides flexible and robust approach to data management
 It is the De -facto standard in software development
19.5 CURRENT PERSISTENCE STANDARDS IN JAVA The Java platform was always supported for managing persistence to
relational databases. It
provides programming interfaces that in turn provide gateway to the
relational databases. There already exist the following options that allow
the Java developers to store and retrieve persistent data:
 Serialization
 JDBC
 EJB 2 Entity Beans
 Java Data Objects
Serialization :
Serialization allows transforming an object graph into a series of bytes,
which can then be sent over the network or stored in a file. Serialization
seems to be quite simple, but it has a few limitations:
1. Unsuitable for Large Amount of Data: It must store and retrieve the
entire object graph at once. This makes it unsuitable for dealing with
large amounts of data.
2. Lacks strict data integrity: Changes made to objects cannot be
undone, if an error occurs while updating information. This makes it
unsuitable for applications that require strict data integrity.
3. No Concurrent Access to Information: Multip le threads or
programs cannot read and write the same serialized data concurrently
without conflicting with each other.
4. No Querying Capability: It provides no query capabilities.
JDBC :
JDBC overcomes a lot of limitations that serialization has such as:
1. It can handle large amounts of data munotes.in

Page 238


Enterprise Java
232 2. Ensures data integrity
3. Supports concurrent access to information
4. Provides a sophisticated query language in SQL
Unfortunately, JDBC does not provide ease of use. JDBC was not
designed for storing objects . JDBC allows the Java programs to fully
interact with the database. However, this interaction is heavily reliant on
SQL. It requires a considerable amount of code spec that deals with taking
tabular row and column data and converting it back and forth int o objects.
EJB 2 Entity Beans :
The Enterprise Edition of the lava platform introduced entity Enterprise
JavaBeans [EJBs]
EJB 2.x entities are components that represent persistent information in a
data store.
EJB 2.x entities:
 Provide an object -oriented vie w of persistent data
 Use a strict standard, making them portable across vendors
Unfortunately, EJB 2.x entities:
 Are slow
 Are difficult to code
 Are not serializable
 Require a one -to-one mapping to database tables
 Require expensive application servers to ru n, as they have to reside
within a J2EE application server environment
 Require developers to determine which bean field maps to which table
column
 Do not offer features such as inheritance, polymorphism and complex
relations
Java Data Objects :
Java Data Ob jects [JDO] was initiated to provide another persistence
specification effort due to the failures of the EJB persistence model.
JDO :
 Provides an object -oriented query language, which was not well
accepted by the relational database users munotes.in

Page 239


Persistence, Object/Relational Mapping and JPA
233  Supports non -relational databases. In fact, it was driven by members
of the object -oriented database community and is now being adopted
by object -oriented database products as the primary API
JDO never became an integrated part of the enterprise Java platform. It
had many g ood features in it and was adopted by a small community of
devoted and loyal users who stuck by it and tried to promote it.
Unfortunately, the major commercial vendors did not share the same view
of how a persistence framework should be implemented.
19.6 W HY ANOTHER PERSISTENCE STANDARDS? The answer to this question is that, each of the above -mentioned
persistence solutions have severe limitations.
Object/ Relational Mapping :
The object oriented [domain] model use classes, whereas the relational
databases u se tables. This creates a gap [The Impedance Mismatch] .
Getting the data and associations from objects into relational table
structure and vice versa requires a lot of tedious programming due to the
difference between the two. This difference is called The Impedance
Mismatch .
Developers need something simple to convert from one to the other
automatically. Bridging the gap between the object model and the
relational model is known as Object -Relational Mapping [O -R mapping or
ORM].

The Impedance Mismatch :
This issue arises as the design of relational data and object -oriented
instances share a very different relationship structure within their
respective environments. Relational databases are structured in a tabular
manner and the object -oriented instances a re structured in a hierarchica l
manner. This means that in this object -oriented world, data is represented
as OBJECTS [often Called DOMAIN model]. However, the storage
medium is based on a RELATIONAL paradigm. Hence, there exists an
inevitable mismatch, th e so -called Object/Relational Impedance
Mismatch which creates a vacuum between the Object -Oriented Model
of a well -designed application [the DOMAIN model] and the relational
model in a database schema. This vacuum is surprisingly wide. munotes.in

Page 240


Enterprise Java
234

How to Map One to the Other? :
The most native approach that is usually taken is a simple mapping
between each class the
database table. This approach requires writing a lot of code spec that maps
one to the other. This code spec is often complex, tedious and costly to
deve lop.

The Solution to The Impedance Mismatch :
This impedance mismatch has led to the development of several different
object persistence
technologies attempting to bridge the gap between the relational world and
the object -oriented world. Hence the soluti on is using an Object
Relational Mapping Tool . An Object Relational Mapping Tool provides munotes.in

Page 241


Persistence, Object/Relational Mapping and JPA
235 a simple, API for storing and retrieving Java objects directly to and from
the relational database.
Object/Relational Mapping [ORM] is a technique that allows an
application written in an
object oriented language to deal with the information [it manipulates] as
objects, rather than using database specific concepts such as ROWS,
COLUMNS and TABLES which is facilitated by a software called
Object/Relational Mapper .
An Object/Relational Mapper is a piece of software that is used to
transform: An OBJECT
view of the data INTO A RELATIONAL view Object/Relational
Mapper also offers persistence services [CRUD] such as:
1. CREATE
2. READ
3. UPDATE
4. DELETE
O/R mapping is pe rformed by a persistence framework. This framework
knows how to:
 Query the database to retrieve objects
 Persist those objects back to their representation in the database’s
tables and columns All this is known with the help of Mappings.
Mappings are define d in metadata , typically annotations.
ORM has several benefits. In particular:
 Eliminates writing SQL to load and persist object state, leaving the
developer free to concentrate on the business logic
 Enables creating an appropriate DOMAIN model, after whic h, the
developer only needs to think in terms of OBJECIS, rather than
TABLES, ROWS and COLUMNS
 Reduces dependence on database specific SQL and thus provides
Portability across databases
 Reduces more than 30% of the amount of Java code spec that needs to
be written by adopting an ORM munotes.in

Page 242


Enterprise Java
236

19.7 OBJECT/RELATIONAL MAPPING An ORM provides the following advantages:
1. Better System Architecture:
Most of the times all the application functionality and the database access
code spec is held together. This brings in so me severe disadvantages. It
becomes really difficult to reuse code spec. Hence code repetitions occur
at several different places. Changing anything becomes quite difficult, as
each and every place that holds the repetitive code spec needs to be
located an d changed accordingly. If the application functionality [business
logic] and the database access code spec [persistence mechanism] are
separated, applying changes become very easy. Changes can be made to
one part without influencing the other parts.
2. Red uce Coding Time:
Most of the time the database access code spec is simple inserts, updates
or deletes. These are SQL statements which sometimes are quite tedious to
code. ORM tool helps here, by generating them on the fly and thereby
saves a lot of time.
3. Caching and Transactions:
Most ORM tools such as Hibernate come with features such as Caching
and Transactions. These features, if chosen to hand code are not so easy to
implement. And it definitely does not make sense to develop them when
they already exist. munotes.in

Page 243


Persistence, Object/Relational Mapping and JPA
237 Where Does Java Persistence API Fit In? :
Today, there are several good ORM tools available that perform the
mapping between objects  Relational Database Tables and thereby
solve the Impedance Mismatch:
1. Hibernate
2. OpenJPA
3. TopLink
4. EclipseLink
These Object -Relational Mapping tools/frameworks allow the developers
to focus on the object model instead of dealing with the mismatch between
the object -oriented and relational paradigms. Unfortunately, each of these
tools has its own set of API s. This ties the application code spec to the
proprietary interfaces of a specific vendor [ORM tool]. Since the code
spec is tied to a specific vendor [referred to as Vendor Lock -In], switching
to another tool is not possible without rewriting all the pers istence code
spec.
Java Persistence API :
The Java Enterprise Edition’s [Java EE 5] Enterprise JavaBeans 3 has
introduced a new way of communicating with databases called the lava
Persistence API [JPA], a section of EJB 3.0.
JPA defines a persistence framew ork which provides a way of
automatically mapping normal Java objects to an SQL database. In other
words, it helps load, search and save the data model objects. JPA
combines the best features from most of the available persistence
standards:
 Is extremely e asy to use, entities can be created as simple as creating
serializable classes
 Supports large data sets
 Provides data consistency
 Allows concurrent use of information
 Provides querying capabilities of JDBC
 Allows using advanced object -oriented concepts suc h as inheritance
Java Persistence API As A Specification :
JPA is a specification from Sun, which is released under Java EE 5
specification.
munotes.in

Page 244


Enterprise Java
238 It is not:
 An implementation
 A product
Hence, it cannot be used as it is for persistence. It needs an ORM
implement ation to work with and persist Java Objects. Technically, JPA is
just a set of interfaces [a Specification] and thus requires an
implementation. All specifications require vendors or open source projects
to implement them. Using JPA therefore requires pick ing up an
implementation [ORM tool such as Hibernate, Toplink, OpenJPA or any
other ORM that implements JPA].
JPA defines the interface that an implementation has to implement. The
whole point of having a standard interface is that users can, in principle,
switch between implementations of JPA without changing their code. This
way, JPA helps prevent Vendor Lock -In by relying on a strict
specification such as JDO and EJB 2.x entities. Currently most of the
persistence vendors [ORM tool providers] have releas ed implementations
of JPA. Since, the Java Persistence code spec covers several persistence
frameworks into a single API, an application written using JPA will work
across several implementations [Hibernate Toplink and so on]. This is
very useful, especial ly when, development begins using the free ‘open
source ORM implementations and later on when the need arises, the open
source’ implementation is swapped with a commercial ORM
implementation.
JPA 1.0 as a part of EJB 3 :
After the failure of EIB 2, BIB 3.0 came into existence to make Enterprise
JavaBeans easier and more productive to use. EJB 3.0 introduced a new
model for persistence called The Java Persistence API 1.0. Developers
from the leading vendors of object -relational mapping solutions such as
Hiber nate, Toplink and JDO joined the Java group and helped shape the
new EJB specification. This resulted into a new specification of EJB 3.0
[Java EE 5] with the following distinct pieces:
1. Existing EJB 2.1 APIs and the traditional contracts from the
persp ectives of the container, the bean provider and the client with
new features such as Java EE injection, EJB 3.0 interceptor
Specifications and lifecycle call -back changes
2. A simplified API for developing new session and message -driven
components
3. The Java Persistence API
Even though, Java Persistence API is defined as part of the EJB 3.0
specification, it is not needed to have an EJB container or a Java EE
application server in order to run applications that use persistence.
munotes.in

Page 245


Persistence, Object/Relational Mapping and JPA
239 19.8 SUMMARY Data Persist ence is a means for an application to persist and retrieve
information from a non -volatile storage system. Persistence is vital to
enterprise applications because of the required access to relational
databases.
19.9 PRACTICE QUESTIONS: MCQ:
Q.1) Which one of the following best illustrates the concept of Object
Persistence.
a) Determining how an object’s state[data stored in member variable of
an object ]is stored in database table columns.
b) Provides an object – oriented view of persistent data.
c) Design patterns and sophisticated object oriented concepts such as
inheritance and polymorphism can be used.
d) Provide one to one mapping to database table.
Answer: A
Q.2) Which of the following is not a correct explanation of JDO.
a) JDO is a standard way to ac cess persistent data in databases, using
plain old Java objects (POJO) to represent persistent data.
b) JDO is an object relational mapping tool.
c) Provides object relational query language and support non -relational
databases.
d) JDO was popular and an integrated part of enterprise java platform.
Answer: D
Q.3) What is ORM.
a) Object Relation Map
b) Object Rate Mapping
c) Object Relational Mapping
d) Object Relational Mapper
Answer: C
munotes.in

Page 246


Enterprise Java
240 Q.4) Which method is used to remove a persistent instance from the
datastore.
a) Session.remove()
b) Session.delete()
c) Session.del()
d) Session.rm()
Answer: B
Q.5) Which tool provides a set of persistent annotati ons to define
mapping metadata.
a) JPA
b) JSR
c) XML
d) JRE
Answer: A
Q.6) Which of the following simplifies Object Relational Mapping tool.
a) Data Creation ,Data Isolation, Data Access
b) Data Manipulation, Data Creation, Data Extraction
c) Data Crea tion, Data Manipulation, Data Access
d) Data Isolation, Data Extraction, Data Manipulation
Answer: C
Q.7) The problem which arises because of the difference between model
of programming language and model of database is classified as.
a) modelling mismatch
b) referential mismatch
c) dependence mismatch
d) impedance mismatch
Answer: D
Q.8) An ORM Framework persist your objects according to the mapping
metadata you provide.
a) False
b) True munotes.in

Page 247


Persistence, Object/Relational Mapping and JPA
241 c) May be
d) Can’t say
Answer: B
Q.9) Which technique is used by Hibe rnate to persist collections of
embeddable types.
a) ElementCollection
b) ManyToMany
c) OneToMany
d) CollectionElement
Answer: A
Q.10) What is the JPA equivalent of hibernate.cfg.xml file.
a) configuration.xml
b) persistence.xml
c) jpa.configuration.xm l
d) jpa.persistence.xml
Answer: B
Descriptive:
1. Write a note on Java Persistence API.
2. Explain the architecture of JPA 2.0.
3. What is Persistence?
4. What are the various options that allow the Java developers to store
and retrieve persistent dat a?
5. What is Object/Relational Mapping?
6. List and explain various advantages provided by Object Relational
Mapping.
19.10 REFERENCES Books and References: Sr. No. Title Author/s Publisher Edition Year 1. Java EE 7 For Beginners Sharanam Shah, Vaishali SPD First 2017 munotes.in

Page 248


Enterprise Java
242 Shah 2. Java EE 8 Cookbook: Build reliable applications with the most robust and mature technology for enterprise development Elder Moraes Packt First 2018 3. Advanced Java Programming Uttam Kumar Roy Oxford Press NA 2015



*****
munotes.in

Page 249

243 20
JAVA PERSISTENT API
Unit Structure
20.1 Objectives
20.2 Introduction to Java Persistence API
20.3 Writing JPA Application
20.4 Summary
20.5 Sample Questions
20.6 References
20.1 OBJECTIVES In this chapter we will learn the Java Persistence API ( JPA) specification
of Java. Also learn how it is used to persist data between Java object and
relational database. JPA acts as a bridge between object -oriented domain
models and relational database systems. As JPA is just a specification, it
doesn't perfor m any operation by itself. It requires an implementation. So,
ORM tools like Hibernate, TopLink and iBatis implements JPA
specifications for data persistence.
20.2 INTRODUCTION TO JAVA PERSISTENCE API 20.2.1 Introduction to Java Persistence API :
Convention ally when a programmer is dealing with applications, he/she
probably imagines that an application has some specific functions
[business logic / application logic] and all that it has to do is process and
then finally save data in a database. When thinking in terms of Java as the
programming language of choice for most programmers, the business
logic of an application works with OBJECTS of different CLASS types.
However, when dealing with the storage medium, it’s important to note
that the tables of a databa se are not OBJECT. This becomes a little
difficult to handle.
Today, there are several Object/Relational mapping tools that have
become popular because they help bridge up the gap between the Objects
and the relational database which in turn allows the dev elopers concentrate
on the business logic:
 Hibernate
 TopLink
 EclipseLink
 OpenJPA munotes.in

Page 250


Enterprise Java
244 And many others are available, unfortunately, each of these tools has its
own set of APIs. This ties the application code spec to the proprietary
interfaces of a specific ven dor [ORM tool]. In spite of having so many
Object/Relational mapping tools, there is no single persistence standard
for the Java platform that can be used in both the Java EE and Java SE
environments. This is where Java Persistence API comes in.
JPA helps standardize the persistence API for the Java platform. A lot of
these Object/ Relational tool vendors [such as TopLink and Hibernate, as
well as other leading application server vendors and JDO vendors] have
widely accepted the JSR -220 specification and mo st of them have also
released their implementation of JPA.
20.2.2 The Java Persistence API :
The Java Persistence API is a standard API that allows accessing,
persisting and managing data between Java objects / classes and the
relational database in Java EE 5 platform. JPA was defined as a part of the
EJB 3.0 specification as a replacement to the EJB 2 CMP (Container -
Managed Persistence) Entity Beans specification. It is now considered the
standard industry approach for Object  Relational Mapping in the Jav a
Industry.
With the help of a standard API, JPA provides standard mechanisms to
using Object Relational Mapping tools.
Java Persistence consists of three areas:
 The Java Persistence API
 Object/ Relational mapping metadata
 The Query language
Object -relatio nal mapping with the Java Persistence API is entirely
metadata driven. It can be done by adding annotations to the code spec OR
using externally defined XML 0R using annotations as well as externally
defined XML.
JPA uses Annotations or XML to map Objects to a Relational Database.
These Objects are called Entities. Entities are nothing but POJOs that do
not extend any class nor implement any interface. JPA also allows
querying and retrieving data using its own query language called Java
Persistence Query La nguage. It generates all the necessary SQL calls to
achieve this and thereby, relieves the developers from manual result -set
handling and object conversion.



munotes.in

Page 251


Java Persistent API
245 20.2.3 JPA, ORM, Database and the Application :

JPA is made up of a few classes and interfaces . The application
communicates with the configured IPA provider [in this case EclipseLink]
to access the underlying data. Typically, applications invoke the
appropriate methods of the Java Persistence API. These methods are
passed the persistence objects a nd instructed to operate upon them. The
information about the mapping [metadata] between the instance variables
of classes and the columns of the tables in the database is available either
in XML and/ or POJOs with the help of Annotations.
POJOs are Java c lasses that represent the tables in the database. Data
Access Object [DAO] is the design pattern that can be used [if required] to
deal with database operations. EclipseLink uses the database [using JDBC
API internally] and refers to the metadata to provid e persistence services
[and Persistent Objects] to the application. The application talks to
EclipseLink via the JPA to perform the SELECT, INSERT, UPDATE and
DELETE operations on the database tables. The ORM tool automatically
creates the required SQL que ries and fires them using the JDBC APIs.
20.2.4 Architecture of JPA :
munotes.in

Page 252


Enterprise Java
246 Persistence:
The javax.persistence.Persistence class contains static helper methods to
obtain EntityManagerFactoryinstances in a vendor -neutral fashion.
EntityManagerFactory:
The Enti tyManagerFactory is created with the help of a Persistence Unit
during the application start up. It serves as a factory for spawning
EntityManager objects when required. Typically, it is created once [one
EntityManagerFactory object per database] and for l ater use kept alive for
later use.The javax.persistence.EntityManagerFactory class is a factory for
EntityManagers.
EntityManager:
The EntityManager object [javax.persistence.EntityManager] is
lightweight and inexpensive to create. It provides the main i nterface to
perform actual database operations. All the POJOs i. e. persistent objects
are saved and retrieved with the help of EntityManager object. Typically,
EntityManager objects are created as needed and destroyed when not
required. Each EntityManager manages a set of persistent objects and has
APIs to insert new Objects and delete existing ones. EntityManagers also
act as factories for Query instances and CriteriaQuery instances.
Entity:
Entites are persistent objects that represent datastore records .
Entity Transaction:
A Transaction represents a unit of work with the database. Any kind of
modifications initiated via the EntityManager object are placed within a
transaction. An EntityManager object helps creating an EntityTransaction
object. Transact ion Objects are typically used for a short time and are
closed by either committing or rejecting.
Query:
Persistent objects are retrieved using a Query object. Query objects
[javax.persistence.Query] allows using SQL or Java Persistence Query
Language [JP QL] queries to retrieve the actual data from the database and
create objects.
Criteria :
Criteria API IS a non -string -based API for the dynamic construction of
object -based queries [javax.persistence.criteria]. Just like JPQL static and
dynamic queries, cr iteria query objects are passed to the
EntityManager’screateQuery() method to create Query objects and then
executed using the methods of the Query API. A CriteriaQuery object can
be thought of as a set of nodes corresponding to the semantic constructs of
the query: munotes.in

Page 253


Java Persistent API
247  Domain objects, which correspond to the range variables and other
identification variables of the JPQL FROM clause
 WHERE clause predicates, which comprise one or more conditional
expression objects
 SELECT clauses, which comprise one or more sele ct item objects
 ORDER -BY and GROUP -BY items
 Subqueries
20.2.5 How JPA works? :
An XML is created or annotations are added to POJOS, which inform the
JPA provider [such as Eclipselink] about:
1. The classes needed to Store the data
2. How the classes are r elated to the tables and columns in the database
This way all the necessary information is provided to the JPA provider.
During the runtime, the IPA provider reads the XML and/or annotations
and dynamically builds Java classes to manage the translation bet ween the
database and the Java objects. An EntityManagerFactory is created from
the compiled collection of mapping metadata. The EntityManagerFactory
provides the mechanism for managing persistent classes and the
EntityManagerinterface. The EntityManager c lass provides the interface
between the persistent data store and the application. The EntityManager
interface wraps a JDBC connection, which can be user managed or
controlled by the JPA provider and is only intended to be used by a single
application thre ad, then closed and discarded.
All the database interaction is done via a simple, intuitive API that JPA
provides. This allows performing queries against the objects represented
by the database. This API informs the JPA provider:
 To save the changes whenev er the objects are changed
 To store the objects in the database whenever new objects are created
Based on all the above discussion, the following is what will be
required to build an application that persists data.
An ORM tool:
 To avoid low level JDBC and SQL code
 To leverage object -oriented programming and object model usage
 To provide database and schema independence
 Since it’s free [Most ORMs are free and open source] munotes.in

Page 254


Enterprise Java
248  To use high end performance features such as caching and
sophisticated database and que ry optimizations
JPA:
 To gain portability across application sewers and persistence
providers [ORMs]
 Since it’s a standard and part of EJB 3 and Java EE
 Since it provides a usable and functional specification
 Since it supports both Java EE and Java SE
20.2.6 JPA Specification :
Specification is part of Java EE 6 where IPA has been officially separated
from distinct API.
JPA 2.0 brings in the following enhancements:
1. ORM mapping enhancements such as:
(a) Ability to model collections, maps and lists using
@ElementCollection annotation
(b) Ability to map unidirectional one -to-many relationships as JPA 1.0
only allowed Bidirectional one -to-many relationships
2. EntityManager and the Query APIs now support:
(a) Retrieving the first result
(b) Accessing the u nderlying vendor -specific entity manager/ query
objects
(c) Pessimistic locking
3. JPQL has been enhanced with SQL -like CASE, NULLIF, COALESCE
and like capabilities
4. Criteria API similar to the one that Hibernate provides
5. Standardization of:
(a) Second level caching
(b) Hints for Query configuration and for EntityManager configuration
(c) Metadata to support DDL generation and Java2DB mapping
6. Support for validation

munotes.in

Page 255


Java Persistent API
249 20.3 WRITING JPA APPLICATION JPA Practical using GuestBook
Steps:
1. Create W eb Application with dedicated folder for Library

2. Add Simple java class or Persitent Entity class from Database (code
below GuestBook.java)
3. Add SQL Connector Jar file to Library
4. Create Persistence Unit using jdbc connection to MySQL database
5. Create the JSP files (codes given below)
6. Run the Application.
GuestBook.java
~~~~~~~~~~~~~
package tyit;
import javax.persistence.*;

@Entity
@Table(name="GuestBook")
public class GuestBook {
@Id
@GeneratedValue(strategy = GenerationType.IDE NTITY)
@Column(name="VisitorNo", unique=true, updatable=false)
private Integer visitorNo;
@Column(name="VisitorName")
private String visitorName;
@Column(name="Message")
private String message;
@Column(name="MessageDate") munotes.in

Page 256


Enterprise Java
250 private String messageDate;

public GuestBook() {
}

public Integer getVisitorNo() {
return visitorNo;
}
public void setVisitorNo(Integer visitorNo) {
this.visitorNo = visitorNo;
}

public String getVisitorName() {
return visitorName;
}
public void setVisitorName(String visitorName) {
this.visitorName = visitorName;
}

public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}

public String getMessageDate() {
return messageDate;
}
public void setMessageDate(String messageDate) {
this.messageDate = messageDate;
} munotes.in

Page 257


Java Persistent API
251 }
index.jsp
~~~~~~~~~~
<%@page contentType="text/html" pageE ncoding="UTF -8"%>



Sign the Guest Book


Visitor Name: size="50" />
Message:




GuestBookView.jsp
~~~~~~~~~~~~~~~~~
<%@page import="java.ut il.*,javax.persistence.*,tyit.GuestBook" %>
<%@page contentType="text/html" pageEncoding="UTF -8"%>

<%!
private EntityManagerFactory entityManagerFactory;
private EntityManager entityManager;
private EntityTransaction entityTrans action;
List guestbook;
%>
<%
entityManagerFactory =
Persistence.createEntityManagerFactory("JPAApplicationPU");
entityManager = entityManagerFactory.createEntityManager();
String submit = request.getParameter("btnSubmit"); munotes.in

Page 258


Enterprise Java
252 if(submit != null && ("Submit").equals(submit)) {
try {
String guest = request.getParameter("guest");
String message = request.getParameter("message");
String messageDate = new java.util.Date().toString();

GuestBook gb = new GuestBook();
gb.setVisitorName(guest);
gb.setMessage(message);
gb.setMessageDate(messageDate);
entityTransaction = entityManager.getTransaction();
entityTransaction.begin( );
entityManager.persist(gb);
entityTransaction.commit();
} catch (RuntimeException e) {
if(entityTransaction != null) entityTransaction.rollback();
throw e;
}
response.sendRedirect("G uestBookView.jsp");
}

try {
guestbook = entityManager.createQuery("SELECT * from
GuestBook").getResultList();
} catch (RuntimeException e) { }
entityManager.close();
%>


View the Guest Book Click here to
sign the guestbook.



munotes.in

Page 259


Java Persistent API
253 <%
Iterator iterator = guestbook.iterator();
while (iterator.hasNext()) {
GuestBook obj = (GuestBook) iterator.next();
%>
On <%= obj.getMessageDate() %>,

<%= obj.getVisitorName() %>:
<%= obj.getMessage() %>



<%
}
%>


20.4 SUMMARY The Java Pers istence API (JPA) is a specification of Java. It is used to
persist data between Java object and relational database. JPA acts as a
bridge between object -oriented domain models and relational database
systems.
As JPA is just a specification, it doesn't per form any operation by itself. It
requires an implementation. So, ORM tools like Hibernate, TopLink and
iBatis implements JPA specifications for data persistence.
20.5 SAMPLE QUESTIONS MCQ :
Q.1 What is the full form of JPQL
a) Java Persistence Query Langua ge
b) Java Provider Query Language
c) Java POJO Query Language
d) Java performance query language
Ans: a) Java Persistence Query Language
Q.2 Which tool automatically creates the required SQL queries
a) XML munotes.in

Page 260


Enterprise Java
254 b) JPQL
c) ORM
d) JPA
Ans: c) ORM
Q.3 Which one is the simple java class that represents a row in a database
table.
a) Attribute
b) Primary key
c) foreign key
d) Entity
Ans: d) Entity
Q.4 An object is called persistent if it is stored in the database and can be
accessed anytime. This ty pe of entity property is called as
a) Persistability
b) Persistent Identity
c) Transactionality
d) Granularity.
Ans: a) Persistability
Q.5 Which keyword makes possible to filter results after evry join, leading
to smaller results after each successive join.
a) ON
b) delete.
c) enter
d) remove.
Ans: a) ON
Q.6 Which annotation is used to link two tables through a relation table?
a. @RelationTable
b. @JoinTable
c. @LinkTable
d. @GroupTable munotes.in

Page 261


Java Persistent API
255 Ans: b) @JoinTable
Q.7 Which annotation is used to create Pk -Fk relat ion b/w two tables?
a. @JoinColumn
b. @ForeignKey
c. @JoinedKey
d. @PrimaryKey
Ans: a) @JoinColumn
Q.8 Which statement(S) is/are incorrect
a. Stored procedure may return a value and function must return a
value.
b. Function has only IN parameter.
c. Try and C atch can be used with both stored procedure and
function.
d. Stored procedure has IN and OUT parameter.
Ans: c) Try and Catch can be used with both stored procedure and
function.
Q.9 Which API is used to define queries for entities and their persistent
state by creating query -defining objects
a) Criteria API.
b) Query API
c) Entity API
d) Transaction API
Ans: a) criteria API
Q.10 JPA 2.1 introduced Which method to call databse funtions which are
not directly supported by the standard
a) delete()
b) insert()
c) call()
d) function()
Ans: d) function()
Descriptive: munotes.in

Page 262


Enterprise Java
256 1. Write a note on Java Persistence API.
2. Explain the architecture of JPA 2.0.
3. Using suitable example explain the various components of JPA.
4. Create simple JPA application to store a nd retrieve Book details. <<
similar to above example >>
5. Develop a JPA Application to demonstrate use of ORM associations.
20.6 REFERENCES Books and References: Sr. No. Title Author/s Publisher Edition Year 1. Java EE 7 For Beginners Sharanam Shah, Vaishali Shah SPD First 2017 2. Java EE 8 Cookbook: Build reliable applications with the most robust and mature technology for enterprise development Elder Moraes Packt First 2018 3. Advanced Java Programming Uttam Kumar Roy Oxford Press NA 2015




***** munotes.in

Page 263

257 21
HIBERNATE
Unit Structure
21.1 Objectives
21.2 Introduction to Hibernate
21.3 Writing Hibernate Application
21.4 Summary
21.5 Sample Questions
21.6 References
21.1 OBJECTIVES In this we will explain What is hibernate and how to install Hibernate &
other associated packages to prepare a develop environment for the
Hibernate applications. We will work with MySQL database to
experiment with Hibernate examples, so make sure you already have setup
for MySQL database.
21.2 INTRODUCTION TO HIBERNATE 21.2. 1 What is Hibernate? :
Any project that requires database interaction have started looking at
ORM tools than considering the traditional approach i.e. JDBC. Hibernate
ease the job of programmer in working with traditional database using
concrete SQL queries in Java by using java object mapped with data base
and allow programmer to interact with database just like other java class
or object. The objective of Hibernate is to free the programmer from
tedious database interaction and focus on working with java o bjects and
features of application instead of worrying about how to work with data
from database. Hibernate does this by copying data from database table to
java class and saving state of an object to database table.
Hibernate is a free, open source, high performance persistent ORM and
query tool.
Gavin King, founded the Hibernate Project in 2001 at JBoss Inc. [now part
of RedHat Inc.]
Hibernate provides:
 Mapping of java classes to Database table.
o e.g.: Student.java class → Student table in Oracle
 Mapping of java data type to SQL data type. munotes.in

Page 264


Enterprise Java
258 o e.g.: int → number, String → varchar, java.sql.Date → DateTime,
etc.
 Flexibility in Querying and retrieving data from any database.
 Freedom to switch to any data base without changing the application
logic/presentation logic.
21.2.2 Why Hibernate? :
 Hibernate is a high -performance Object/Relational persistence and
query service, available free under the open source GNU Lesser
General Public License (LGPL).
 Takes ca re of all SQL operations in a java program.
 Make feel like working with Objects rather than SQL in performing
Create, Read, Update and Delete SQL operations.
 Complete portability across database.
 Supports IDE like Netbeans by providing plug -in.
 Cuts down d evelopment time by using Object oriented technology
like inheritance, composition and java collection framework.
 Can have multiple primary key generations through multiple identity
column mapping.
 Hibernate has two cache layers for handling thread safety, non-
blocking concurrent data access, connection pooling etc.
 Allows working with any database like Oracle, MySql, DB2, Sybase,
PostgresSQL, Apache Derby, MS SQL Server, MS Access, etc.
21.2.3 Hibernate, Database and The Application

Application program us es persistent objects that represent data from
database. Configuration is stored in configuration files like munotes.in

Page 265


Hibernate
259 Hibernate.properties and hibernate.cfg.xml to map the objects to
corresponding database and hibernate dilect to choose appropriate SQL
statement fo r database. A mapping file is used to map instance variables of
class to database columns. Hibernate uses JDBC API with JTA to perform
database operations like Create, Insert, Update, Delete, Select etc. to
automatically fire queries bases on operations pe rformed by application
program on java objects.
21.2.4 Components of Hibernate :
The main components of Hibernate are:
1. Connection Management: Hibernate solves the problems which arise
when a relational database is connected by an application written in o bject
oriented programming language style, due to data type differences,
manipula tive differences, transactional differences, structural and integrity
differences. Connection Management provides efficient connection
management and removes the overhead of d atabase interaction from
application program.
2. Transaction Management: Transaction in hibernate is managed by
JTA and JDBC. It allow to fire more than one SQL query at a time.
3. Object Relation Management: It is used to map java objects to
database tabl es. Hibernate stores the persistent objects in session and reads
the state of an object to execute appropriate database query.
21.1.5 Architecture of Hibernate :
Hibernate is a layered architecture. The main components are
Configuration, Session Factory, Session, Transaction, Query and Criteria.
Hibernate uses existing Java APIs, like JDBC for database connectivity,
Java Transaction API(JTA) for transaction and Java Naming and
Directory Interface (JNDI) for easy integration with other enterprise
applications .

munotes.in

Page 266


Enterprise Java
260 Following is a detailed view of the Hibernate Application Architecture
with few important core classes.

Hibernate uses various existing Java APIs, like JDBC, Java Transaction
API(JTA), and Java Naming and Directory Interface (JNDI). JDBC
provides a rudimentary level of abstraction offunctionality common to
relational databases, allowing almost any database with a JDBC driver to
supported by Hibernate. JNDI and JTA allow Hibernate to be integrated
with J2EE application servers.
Configuration: It repre sents properties/configuration of a hibernate
application. It the first object created in a hibernate application and created
once at the time of application execution. This object reads the
configuration file to establish database connection and mapping. This
object helps in creating session factory.
It represents a configuration or properties file required by the Hibernate.
The Configuration object provides two keys components:
1. Database Connection: This is handled through one or more
configuration file s supported by Hibernate. These files are
hibernate.properties and hibernate.cfg.xml.
2. Class Mapping Setup This component creates the connection between
the Java classes and database tables.
Session Factory: It is created using configuration object at t he time of
application startup to serve as a base for creating light weight sessions
conveniently during client’s request. One session factory is created for one
database for multiple database multiple session factory objects are created.
Session Object: Sessions are single threaded, lightweight objects to
communicate with database represented by session class from
org.hinernate package. Persistent object are created, saved and retrieved
using session object during client interaction. It wraps the Connecti on
class from java.sql package and serves as factory for Transaction. The
session objects should not be kept open for a long time because they are munotes.in

Page 267


Hibernate
261 not usually thread safe and they should be created and destroyed them as
needed.
Transaction: Transaction is a single threaded object used by application
to represent group of SQL queries to form a unit of work called
transaction. Transactions in Hibernate are handled by an underlying
transaction manager and transaction (from JDBC or JTA). All changes
during a s ession are placed within transaction. Transactions are either
completed using commit or canceled using rollback. The
org.hibernate.Transaction interface provides methods for transaction
management.
Query: It uses either conventional SQL or Hibernate Query Language
(HQL) to communicate with database. It associates the query parameters,
restricts the results coming from database and executes queries. Persistent
objects are retrieved using query object.
Criteria: Criteria objects are used to create and execut e object oriented
criteria queries to retrieve objects.
21.2.6 How Hibernate Works? :
• All configuration files hibernate.cfg.xml are created to describe about
the java classes and there mapping with database tables.
• At the time of application startup t hese files are compiled to provide
hibernate framework with necessary information.
• This dynamically builds java class objects by mapping them to
appropriate database table.
• A session factory object is created from compiled collections of
mapping docu ments.
• Session Factory spawns a lightweight session to provide interface
between java objects and applications.
• Database communication is performed by this session using hibernate
API used to map the changes from java object to database table and
vice versa.
munotes.in

Page 268


Enterprise Java
262 21.3 WRITING HIBERNATE APPLICATION In this section we will d evelop a Hibernate application to store Feedback
of Website Visitor in MySQL Database. The application to be built is
called Guestbook Feedback Entry using Hibernate. This application
should be capable of accepting and displaying employee details using
database. To achieve this, it should provide a user interface that accepts
Guest’s name, message and date.
From the application development perspective, the following software will
be requ ired on the
development machine:
1. Java Development Kit
2. NetBeans IDE
3. MySQL community Server [The database server]
4. JDBC driver for MySQL
5. Hibernate 4.XXX or Higher (ORM Tool) [Available on
www.hibernate.org/downloads]
create database feedback db;
create table GuestBook(
vno int PRIMARY KEY AUTO_INCREMENT,
vname varchar(50),
msg varchar(100),
mdate varchar(50)
)

Library Files: The Java library [.JAR] i.e. JDBC driver is required. This
will be specific to a relational database to be used. In thi s case MySQL is
used as the database of choice, hence, the database specific JDBC driver
file will be MySQL Connector/J 5.1.10 .
The following is the list of jar files required munotes.in

Page 269


Hibernate
263
hibernate -release -
5.3.0.Final \lib\required
-->antlr.jar
-->hibernate -common -annotations
-->hibernate -core
-->hibernate -jpa-2.0-api
-->javaassist
-->jboss -logging
-->jboss -transaction -api-1.1-spec
hibernate -release -5.3.0.Final \lib\jpa
-->hibernate -entitymanager.jar
download from dom4j.sourceforge.net
-->dom4j -2.1.1.jar

The Applic ation Development Approach :
The application will be built using JSP.
The data entry form that captures the data will be called index.html and
the page that will fetch and display the entries will be called Fetch.jsp .
The captured data will be stored in a t able called GuestBook under the
feedbackdb MySQL database server .
In the Java application, the POJO that will represent the GuestBook
database table will be called mypack.GuestBookBean.java .
The following steps are required to build this application:
1. Create the database schema munotes.in

Page 270


Enterprise Java
264 2. Create the Web application
3. Add the Java libraries to the application
4. Create a POJO to represent the table in the database schema
5. Generate a hibernate configuration file.
6. Annotate the POJO to indicate the mappin g between the JavaBean
properties and the columns in the table
7. Create JSPs with code spec:
(a) To build a Configuration object
(b) To build a SessionFactory object by referencing the
Configuration object.
(c) To obtain an HiberanteSession object from the SessionFactory
(d) To perform the required database operations.
GuestBookBean.java
package mypack;
import javax.persistence.*;
@Entity
@Table(name="guestbook")
public class GuestBookBean implements java.io.Serializable {
@Id
@GeneratedValue
@Column(name="vno")
private Integer visitorNo;
@Column(name="vname")
private String visitorName;
@Column(name="msg")
private String msg;
@Column(name="mdate")
private String msgDate;
public GuestBookBean() { }
public Integer getVisitorNo() { return visitorNo; }
public String getVisitorName() { return visitorName; }
public String getMsg() { return msg; }
public String getMsgDate() { return msgDate; } munotes.in

Page 271


Hibernate
265 public void setVisitorNo(Integer vn) { visitorNo = vn ; }
public void setVisitorName(String vn) { visitorName = vn; }
public void setMsg(String m) { msg = m; }
public void setMsgDate(String md) { msgDate=md; }
}
Source packages new  others select category Hibernate
Hibernate Configuration Wizard





name="hibernate.dialect">org.hibernate.dialect.MySQLDialect>
name="hibernate.connection.driver_class">com.mysql.jdbc.Driverrty>
name="hibernate.connection.url">jdbc:mysql://localhost:3306/feedbackdb
?zeroDateTimeBehavior=convertToNull
munotes.in

Page 272


Enterprise Java
266 root
root




index.html :

Website Feedback Form for google.con



Enter Your Name:

Enter Your Message :



fb.jsp :
<%@page import=" org.hibernate.*, org.hibernate.cfg.*, mypack.*" %>
<%! SessionFactory sf;
org.hibernate.Session hibSession;
%>
<%
sf = new Configuration().configure().buildSessionFactory();
hibSession = sf.openSession();
Transaction tx = null;
GuestBookBean gb = new GuestBookBean();
try{
tx = hibSession.beginTransaction();
String username = request.getParameter("name");
String usermsg = request.getParameter("message");
String nowtime = ""+new java.util.Date();
gb.setVisitorName(username);
gb.setMsg(usermsg);
gb.setMsgDate(nowtime); munotes.in

Page 273


Hibernate
267 hibSession.save(gb);
tx.commit();
out.println("Thank You for your valuable feedback....");
}catch(Exception e){out.println(e);}
hibSession.close();
%>
Output:


21.4 SUMMARY In this Chapter we studied hibernate and steps to install Hi bernate & other
associated packages to prepare a develop environment for the Hibernate
applications. We also worked with MySQL database to
experiment with Hibernate examples, so make sure you already have setup
for MySQL database.
21.5 PRACTICE QUESTIONS MCQ :
1) What is hibernate?
a) CRM
b) Programming Tool
c) ORM
d) SQL tool. munotes.in

Page 274


Enterprise Java
268 2) Hibernate framework simplifies the development of java application
to interact with the database
a) True
b) False
3) Which of the following is true about SessionFactory object in
hibernate?
a) SessionFactory o bject configures Hibernate for the application
using the supplied configuration file.
b) SessionFactory object allows for a Session object to be
instantiated.
c) The SessionFactory is a thread safe object.
d) All options mentioned for this question.
4) Which method is used to update the state of the given instance from
the underlying database?
a) Session.store()
b) Session.keep()
c) Session.update()
d) Session.load()
5) HOL stands for
a) Hibernate Queue Language
b) Hibernate Query Language
c) Hypertext Query Language
d) HighSpeed Query Language
6) Hibernate uses PersisterClassProvider by default.
a) True
b) Fales
7) _______________ object is used to create SessionFactory object in
Hibernate.
a) Session
b) Configuration
c) Transaction
d) TransactionFactory munotes.in

Page 275


Hibernate
269 8) In hibernate, QBC stands for
a) Query By Criteria
b) Query By Call
c) Query By Code
d) Query By Column
9) Which method is easy for Java Programmer to add criterion?
a) SQL
b) HCQL
c) HQL
d) AQL
10) Which of the following simplifies an Object Relational Mapping
Tool?
a) Data creation
b) Data manipulation
c) Data access
d) All options mentioned for this question .
11) _______ is not a core interface of hibernate.
a) Criteria
b) Session
c) SessionManagement
d) Configuration
12) Is SessionFactory a ThreadSafe object
a) Yes
b) No
13) Is Session created per thread in hibernate?
a) Yes
b) No
14) All POJO must implement non -argument constructor in hibernate.
a) True
b) False munotes.in

Page 276


Enterprise Java
270 15) When several entities point to the target entity, that is achieved by
a) @OneToOne
b) @OneToMany
c) @ManyToOne
d) @ManyToMany
16) If entity is not annotated with @Table, what will happen?
a) Throws error because no table name is assigned
b) No error and class name w ill be mapped with table name.
17) A __________ is used to get a physical connection with a database.
a) SessionFactory
b) Session
c) Transaction
d) ConnectionProvider
18) A _________ represents a unit of work with the database and the Java
object.
a) SessionFactory
b) Connectio nProvoder
c) Transaction
d) Session
19) _________ is a factory of JDBC connections.
a) SessionFactory
b) ConnectionProvoder
c) Transaction
d) Session
20) Mapping in hibernate can be given to an ORM tool either in the form
of an ______or in the form of the annotations
a) XHTML
b) JSON
c) HTM L
d) XML munotes.in

Page 277


Hibernate
271 Answers :
1) c
2) a
3) d
4) c
5) b
6) a
7) b
8) a
9) d
10) d
11) c
12) a
13) a
14) a
15) c
16) b
17) b
18) c
19) b
20) d
Descriptive:
1. Explain software development approach of Hibernate?
2. Develop a Hibernate application to store and retrieve employee details
in MySQL Database.
3. Develop a Hibernate application to store Feedback of Website Visitor
in MySQL Database.
4. Develop an application to demonstrate Hibernate One - To -One
Mapping Using Annotation.

munotes.in

Page 278


Enterprise Java
272 21.6 REFERENCES Books and References: Sr. No. Title Author/s Publisher Edition Year 1. Java EE 7 For Beginners Sharanam Shah, Vaishali Shah SPD First 2017 2. Java EE 8 Cookbook: Build reliable applications with the most robust and mature technology for enterprise development Elder Moraes Packt First 2018 3. Advanced Java Programming Uttam Kumar Roy Oxford Press NA 2015



*****
munotes.in