0% found this document useful (0 votes)
139 views72 pages

Core Course Vii J2Ee Technologies Objective

msc it course notes

Uploaded by

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

Core Course Vii J2Ee Technologies Objective

msc it course notes

Uploaded by

maha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 72

CORE COURSE VII

J2EE TECHNOLOGIES

Objective:

To provide understanding on developing distributed enterprise applications using


J2EE

UNIT I Client – Server Architecture:


Two Tier Model – 3 Tier Model – n Tier Model – J2EE Architecture - .net
Architecture – MPC Architecture.

UNIT II Interaction Services:

RMI – CORBA – XML – JMS.

UNIT III Presentation Services:

JSP – Javamail – Servlet.

UNIT IV Component Model:

EJB: Session beans: Stateless and Statefull – Entity beans – CMP and BMP –
Message Driven Beans.

UNIT V Struts Framework:

Introduction – Building a simple struts – Model layers –View layer – controller layer
– Validator – Tiles –Declarative Exception Handling –Struts Modules.

Text Books:

1. Jim Keogh “The Complete Reference J2EE “Tata McGraw – Hill Edition 2002. 2.
James Holmes “The Complete References Struts Second Edition “ Tata McGraw Hill
Edition-2007.

Reference Books:

1. Jusin Couch, Daniel H. Steinberg, “J2EE Bible” Wily India (P) Ltd, New Delhi
2002. 2. Paul Tremblett, “Instant Enterprise Java Y-Beans”, Tata McGraw Hill
Publishing Company, New Delhi, 2001.

*****
RMI (Remote Method Invocation)

The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an
object running in another JVM.

The RMI provides remote communication between the applications using two
objects stub and skeleton.

Understanding stub and skeleton

RMI uses stub and skeleton object for communication with the remote object.

A remote object is an object whose method can be invoked from another JVM.
Let's understand the stub and skeleton objects:

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 initiates a connection with remote Virtual Machine (JVM),


2. It writes and transmits (marshals) the parameters to the remote Virtual
Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.

skeleton

The skeleton is an object, acts as a gateway for the server side object. All the
incoming requests are routed through it. When the skeleton receives the incoming
request, it does the following tasks:

1. It reads the parameter for the remote method


2. It invokes the method on the actual remote object, and
3. It writes and transmits (marshals) the result to the caller.
.

Common Object Request Broker Architecture (CORBA)

Definition - What does Common Object Request Broker Architecture


(CORBA) mean?
The Common Object Request Broker Architecture (CORBA) is a specification
developed by the Object Management Group (OMG). CORBA describes a messaging
mechanism by which objects distributed over a network can communicate with
each other irrespective of the platform and language used to develop those objects.
There are two basic types of objects in CORBA. The object that includes some
functionality and may be used by other objects is called a service provider. The
object that requires the services of other objects is called the client. The service
provider object and client object communicate with each other independent of the
programming language used to design them and independent of the operating
system in which they run. Each service provider defines an interface, which
provides a description of the services provided by the client.

CORBA enables separate pieces of software written in different languages and


running on different computers to work with each other like a single application or
set of services. More specifically, CORBA is a mechanism in software for
normalizing the method-call semantics between application objects residing either
in the same address space (application) or remote address space (same host, or
remote host on a network).
CORBA applications are composed of objects that combine data and functions that
represent something in the real world. Each object has multiple instances, and each
instance is associated with a particular client request. For example, a bank teller
object has multiple instances, each of which is specific to an individual customer.
Each object indicates all the services it provides, the input essential for each service
and the output of a service, if any, in the form of a file in a language known as the
Interface Definition Language (IDL). The client object that is seeking to access a
specific operation on the object uses the IDL file to see the available services and
marshal the arguments appropriately.
The CORBA specification dictates that there will be an object request broker (ORB)
through which an application interacts with other objects. In practice, the
application simply initializes the ORB, and accesses an internal object adapter,
which maintains things like reference counting, object (and reference) instantiation
policies, and object lifetime policies. The object adapter is used to register instances
of the generated code classes. Generated code classes are the result of compiling
the user IDL code, which translates the high-level interface definition into an OS-
and language-specific class base to be applied by the user application. This step is
necessary in order to enforce CORBA semantics and provide a clean user process
for interfacing with the CORBA infrastructure.

The CORBA Architecture

At its core, the CORBA architecture for distributed objects shares many features
with the architecture used by Java RMI. A description of a remote object is used to
generate a client stub interface and a server skeleton interface for the object. A
client application invokes methods on a remote object using the client stub. The
method request is transmitted through the underlying infrastructure to the remote
host, where the server skeleton for the object is asked to invoke the method on the
object itself. Any data resulting from the method call (return values, exceptions) is
transmitted back to the client by the communication infrastructure.

But that’s where the similarities between CORBA and RMI end. CORBA was
designed from the start to be a language-independent distributed object standard,
so it is much more extensive and detailed in its specification than RMI is (or needs
to be). For the most part, these extra details are required in CORBA because it
needs to support languages that have different built-in features. Some languages,
like C++, directly support objects, while others, like C, don’t. The CORBA standard
needs to include a detailed specification of an object model so that nonobject-
oriented languages can take advantage of CORBA. Java includes built-in support
for communicating object interfaces and examining them abstractly (using Java
bytecodes and the Java Reflection API). Many other languages don’t. So the CORBA
specification includes details about a Dynamic Invocation Interface and a Dynamic
Skeleton Interface, which can be implemented in languages that don’t have their
own facilities for these operations. In languages that do have these capabilities, like
Java, there needs to be a mapping between the built-in features and the features as
defined by the CORBA specification.
The rest of this section provides an overview of the major components that make up
the CORBA architecture: the Interface Definition Language, which is how CORBA
interfaces are defined; the Object Request Broker (ORB) and Object Adaptor, which
are responsible for handling all interactions between remote objects and the
applications that use them; the Naming Service, which is a standard service in
CORBA that lets remote clients find remote objects on the network; and the inter-
ORB communication protocol, which handles the low-level communication between
processes in a CORBA context.

Interface Definition Language

The Interface Definition Language provides the primary way of describing data types
in CORBA. IDL is independent of any particular programming language. Mappings,
or bindings, from IDL to specific programming languages are defined and
standardized as part of the CORBA specification. At the time of this writing,
standard bindings for C, C++, Smalltalk, Ada, COBOL, Lisp, Python and Java have
been approved by the OMG. Chapter 14 contains a complete description of IDL
syntax.

The central CORBA functions, services, and facilities, such as the ORB and the
Naming Service, are also specified in IDL. This means that a particular language
binding also specifies the bindings for the core CORBA functions to that language.
Sun’s Java IDL API follows the Java IDL mapping defined by the OMG standards.
This allows you to run your CORBA-based Java code in any compliant Java
implementation of the CORBA standard, provided you stick to standard elements of
the Java binding. Note, however, that Sun’s implementation includes some
nonstandard elements; they are highlighted in this chapter where appropriate.

The Object Request Broker and the Object Adaptor

The core of the CORBA architecture is the Object Request Broker, as shown
in Figure 4-1. Each machine involved in a CORBA application must have an ORB
running in order for processes on that machine to interact with CORBA objects
running in remote processes. Object clients and servers make requests through
their ORBs; the ORB is responsible for making the requests happen or indicating
why they can’t. The client ORB provides a stub for a remote object. Requests made
on the stub are transferred from the client’s ORB to the ORB servicing the
implementation of the target object. The request is passed on to the implementation
through an object adaptor and the object’s skeleton interface.

Figure 4-1. Basic CORBA architecture

The skeleton interface is specific to the type of object that is exported remotely
through CORBA. Among other things, it provides a wrapper interface that the ORB
and object adaptor can use to invoke methods on behalf of the client or as part of
the lifecycle management of the object. The object adaptor provides a general facility
that “plugs” a server object into a particular CORBA runtime environment. Older
versions of the CORBA specification and Java IDL supported a Basic Object Adaptor
(BOA) interface, while newer versions (CORBA 2.3 and later, JDK 1.4 and later)
support a Portable Object Adaptor interface (we’ll discuss the difference later in the
chapter). All server objects can use the object adaptor to interact with the core
functionality of the ORB, and the ORB in turn can use the object adaptor to pass
along client requests and lifecycle notifications to the server object. Typically, an
IDL compiler is used to generate the skeleton interface for a particular IDL
interface; this generated skeleton interface will include calls to the object adaptor
that are supported by the CORBA environment in use.

The Naming Service

The CORBA Naming Service (sometimes abbreviated to COSNaming, from “CORBA


Object Services, Naming”) provides a directory naming structure for remote objects.
The CORBA Naming Service is one of the naming and directory services supported
by JNDI, so the concepts used in its API are similar to the general model
of Contexts and DirContexts used in JNDI.

The naming tree always starts with a root node, and subnodes of the object tree can
be created by an application. Actual objects are stored by name at the leaves of the
tree. Figure 4-2 depicts an example set of objects[12] registered within a Naming
Service directory. The fully qualified name of an object in the directory is the
ordered list of all of its parent nodes, starting from the root node and including the
leaf name of the object itself. So, the full name of the object labeled “Fred” is “Living
thing,” “Animal,” “Man,” “Fred,” in that order.

Figure 4-2. A naming directory

Each branch in the directory tree is called a naming context, and leaf objects
have bindings to specific names. Each node in the naming directory is represented
by an org.omg.CosNaming.NamingContext object. EachNamingContext can be
asked to find an object within its branch of the tree by asking for the object by
name, relative to that particular naming context. You can get a reference to the root
context of the naming directory from an ORB using the resolve_initial_references(
) method. Once you have a reference to the root of the naming directory, you can
perform lookups of CORBA objects, as well as register your own CORBA objects
with the Naming Service. We’ll see more concrete details of utilizing the CORBA
Naming Service later in this chapter in Putting It in the Public Eye.

Inter-ORB Communication

Version 2.0 (and later) of the CORBA standard includes specifications for inter-ORB
communication protocols that can transmit object requests between various ORBs
running on the network. The protocols are independent of the particular ORB
implementations running at either end of the communication link. An ORB
implemented in Java can talk to another ORB implemented in C, as long as they’re
both compliant with the CORBA standard and use the same CORBA
communication protocol. The inter-ORB protocol is responsible for delivering
messages between two cooperating ORBs. These messages might be method
requests, return types, error messages, etc. The inter-ORB protocol also deals with
differences between the two ORB implementations, like machine-level byte ordering
and alignment. As a CORBA application developer, you shouldn’t have to deal
directly with the low-level communication protocol between ORBs. If you want two
ORBs to talk to each other, you need to ensure that they are compatible in terms of
CORBA compliance levels (do they support similar levels of the CORBA
specification?) and that they both speak a common, standard inter-ORB protocol.

The Internet Inter-ORB Protocol (IIOP) is an inter-ORB protocol based on TCP/IP.


TCP/IP is by far the most commonly used network protocol on the Internet, so IIOP
is the most commonly used CORBA communication protocol. There are other
standard CORBA protocols defined for other network environments, however. The
DCE Common Inter-ORB Protocol (DCE-CIOP), for example, allows ORBs to
communicate on top of DCE-RPC.

o Xml (eXtensible Markup Language) is a mark up language.


o XML is designed to store and transport data.
o Xml was released in late 90’s. it was created to provide an easy to use and
store self describing data.
o XML became a W3C Recommendation on February 10, 1998.
o XML is not a replacement for HTML.
o XML is designed to be self-descriptive.
o XML is designed to carry data, not to display data.
o XML tags are not predefined. You must define your own tags.
o XML is platform independent and language independent.

o What is mark-up language


o A mark up language is a modern system for highlight or underline a
document.
o Students often underline or highlight a passage to revise easily, same in the
sense of modern mark up language highlighting or underlining is replaced by
tags.

Why xml

Platform Independent and Language Independent: The main benefit of xml is


that you can use it to take data from a program like Microsoft SQL, convert it into
XML then share that XML with other programs and platforms. You can
communicate between two platforms which are generally very difficult.

The main thing which makes XML truly powerful is its international acceptance.
Many corporation use XML interfaces for databases, programming, office
application mobile phones and more. It is due to its platform independent feature.

Features and Advantages of XML

XML is widely used in the era of web development. It is also used to simplify data
storage and data sharing.

The main features or advantages of XML are given below.

1) XML separates data from HTML

If you need to display dynamic data in your HTML document, it will take a lot of
work to edit the HTML each time the data changes.

With XML, data can be stored in separate XML files. This way you can focus on
using HTML/CSS for display and layout, and be sure that changes in the
underlying data will not require any changes to the HTML.

With a few lines of JavaScript code, you can read an external XML file and update
the data content of your web page.

2) XML simplifies data sharing

In the real world, computer systems and databases contain data in incompatible
formats.

XML data is stored in plain text format. This provides a software- and hardware-
independent way of storing data.

This makes it much easier to create data that can be shared by different
applications.

3) XML simplifies data transport

One of the most time-consuming challenges for developers is to exchange data


between incompatible systems over the Internet.
Exchanging data as XML greatly reduces this complexity, since the data can be read
by different incompatible applications.

4) XML simplifies Platform change

Upgrading to new systems (hardware or software platforms), is always time


consuming. Large amounts of data must be converted and incompatible data is
often lost.

XML data is stored in text format. This makes it easier to expand or upgrade to new
operating systems, new applications, or new browsers, without losing data.

5) XML increases data availability

Different applications can access your data, not only in HTML pages, but also from
XML data sources.

With XML, your data can be available to all kinds of "reading machines" (Handheld
computers, voice machines, news feeds, etc), and make it more available for blind
people, or people with other disabilities.

6) XML can be used to create new internet languages

A lot of new Internet languages are created with XML.

Here are some examples:

o XHTML
o WSDL for describing available web services
o WAP and WML as markup languages for handheld devices
o RSS languages for news feeds
o RDF and OWL for describing resources and ontology
o SMIL for describing multimedia for the web

XML Example

XML documents create a hierarchical structure looks like a tree so it is known as


XML Tree that starts at "the root" and branches to "the leaves".

Example of XML Document

XML documents uses a self-describing and simple syntax:

1. <?xml version="1.0" encoding="ISO-8859-1"?>


2. <note>
3. <to>Tove</to>
4. <from>Jani</from>
5. <heading>Reminder</heading>
6. <body>Don't forget me this weekend!</body>
7. </note>

The first line is the XML declaration. It defines the XML version (1.0) and the
encoding used (ISO-8859-1 = Latin-1/West European character set).

The next line describes the root element of the document (like saying: "this
document is a note"):

1. <note>

The next 4 lines describe 4 child elements of the root (to, from, heading, and body).

1. <to>Tove</to>
2. <from>Jani</from>
3. <heading>Reminder</heading>
4. <body>Don't forget me this weekend!</body>

JMS Tutorial – What is JMS

RAMBABU POSA 7 COMMENTS

Nowadays, most of the enterprise applications are using messaging concept for
asynchronous communication between heterogeneous applications using JMS or
AMQP. I’m going to deliver a series of posts to discuss these concepts in detail with
real-time examples in my coming posts.

Table of Contents [hide]


 1 JMS
 2 What is Message?
 3 What is Messaging?
 4 What is JMS?
 5 JMS Advantages
 6 JMS Components
 7 Most popular JMS Providers
 8 History of JMS API
 9 Conclusion

JMS

 JMS is the acronym for Java Messaging System.


 JMS is part of Java EE.
 JMS API is the implementation to handle the producer-consumer problem.
 JMS API allows us to create, send, receive, and read messages.
 Some o the benefits of using JMS are – loosely coupled application, reliability,
and asynchronous communication.
What is Message?

The message is a piece of information. It can be a text, XML document, JSON data
or an Entity (Java Object) etc. The message is very useful data to communicate
between different systems.

What is Messaging?

Messaging means exchanging information between different components in the


same system or different systems. It can happen in either a synchronous manner or
an asynchronous manner.

What is JMS?

JMS stands for Java Message Service. JMS API is a Java API which contains a
common set of interfaces to implement enterprise based messaging systems. JMS
API is used to implement Messaging systems in Java-based applications only, it
does not support other languages.

JMS API is used to create, send, receive and read messages or exchange messages
between different systems. Once we develop a Java Messaging System with JMS
API, then we can deploy the same application in any JMS Provider software.

What is JSP?

Java Server Pages (JSP) is a technology which is used to develop web pages by
inserting Java code into the HTML pages by making special JSP tags. The JSP tags
which allow java code to be included into it are <% ----java code----%>.

It can consist of either HTML or XML (combination of both is also possible) with JSP
actions and commands.

It can be used as HTML page, which can be used in forms and registration pages
with the dynamic content into it.

Dynamic content includes some fields like dropdown, checkboxes, etc. whose value
will be fetched from the database.

This can also be used to access JavaBeans objects.


We can share information across pages using request and response objects.

JSP can be used for separation of the view layer with the business logic in the web
application.

JMS Architecture

An Enterprise Application may have ‘n’ number of components and they are
exchanging messages by using one of the Messaging System as shown below.
JMS Messaging System

Some Enterprise applications may have ‘n’ number systems and they exist in
different locations. They use different platforms. If they want to exchange
information in a loosely coupled manner, then we should use JMS Messaging
system.
JMS in Distributed Systems

JMS Advantages

 Loosely Coupled: We can develop loosely coupled applications very easily.


That means JMS API is standard or specification that should be implemented
by all JMS Providers so that we can change existing JMS Provider to new JMS
Provider with little changes (that means only configurations) or without
changing our JMS Application code.
 Asynchronous: We can develop asynchronous messaging applications very
easily. That means JMS Sender can send messages and continue on its own
work. It does not wait for the completion of message consumption by JMS
Receiver.
 Robust and Reliable: JMS ensures that a message is delivered one and only
once to the destination system. So we can develop reliable applications very
easily.
 Interoperability: JMS API allows Interoperability between other Java Platform
languages like Scala and Groovy.

JMS Components

A typical JMS system contains the following components:


1. JMS Client: Java program used to send (or produce or publish) or receive (or
consume or subscribe) messages.
 JMS Sender: JMS Client which is used to send messages to the
destination system. JMS sender is also known as JMS Producer or JMS
Publisher.
 JMS Receiver: JMS Client which is used to receive messages from
Source system. JMS Receiver is also known as JMS Consumer or JMS
Subscriber.
2. JMS Provider: JMS API is a set of common interfaces, which does not contain
any implementation. JMS Provider is a third-party system who is responsible
to implement the JMS API to provide messaging features to the clients.

JMS Provider is also known as MOM (Message Oriented Middleware) software


or Message Broker or JMS Server or Messaging Server. JMS Provider also
provides some UI components to administrate and control this MOM software.

3. JMS Administered Objects: JMS Objects which are preconfigured by an


administrator for the use of JMS clients. They are ConnectionFactory and
Destination Objects.
 ConnectionFactory: ConnectionFactory object is used to create a
connection between Java Application and JMS Provider. It is used by
Application to communicate with JMS Provider.
 Destination: Destinations are also JMS Objects used by a JMS Client to
specify the destination of messages it is sending and the source of
messages it receives. There are two types of Destinations: Queue and
Topic.
4. JMS Message: an object that contains the data being transferred between JMS
clients.

Most popular JMS Providers

JMS PROVIDER
S.NO. ORGANIZATION
SOFTWARE

1. WebSphere MQ IBM

2. Weblogic Messaging Oracle Corporation


3. Active MQ Apache Foundation

Rabbit Technologies(acquired by Spring


4. Rabbit MQ
Source)

5. HornetQ JBoss

6. Sonic MQ Progress Software

7. TIBCO EMS TIBCO

8. Open MQ Oracle Corporation

9. SonicMQ Aurea Software

Two-Tier Architecture:
The two-tier is based on Client Server architecture. The two-tier architecture is like
client server application. The direct communication takes place between client and
server. There is no intermediate between client and server. Because of tight
coupling a 2 tiered application will run faster.
Two-Tier Architecture
The above figure shows the architecture of two-tier. Here the direct communication
between client and server, there is no intermediate between client and server.

Let’s take a look of real life example of Railway Reservation two-tier architecture:

Let’s consider that first Person is making Railway Reservation for Mumbai to Delhi
by Mumbai Express at Counter No. 1 and at same time second Person is also try to
make Railway reservation of Mumbai to Delhi from Counter No. 2

If staff from Counter No. 1 is searching for availability into system & at the same
staff from Counter No. 2 is also looking for availability of ticket for same day then in
this case there is might be good change of confusion and chaos occurs. There might
be chance of lock the Railway reservation that reserves the first.

But reservations can be making anywhere from the India, then how it is handled?

So here if there is difference of micro seconds for making reservation by staff from
Counter No. 1 & 2 then second request is added into queue. So in this case the
Staff is entering data to Client Application and reservation request is sent to the
database. The database sends back the information/data to the client.

In this application the Staff user is an end user who is using Railway reservation
application software. He gives inputs to the application software and it sends
requests to Server. So here both Database and Server are incorporated with each
other, so this technology is called as “Client-Server Technology“.
The Two-tier architecture is divided into two parts:

1) Client Application (Client Tier)


2) Database (Data Tier)
On client application side the code is written for saving the data in the SQL server
database. Client sends the request to server and it process the request & send back
with data. The main problem of two tier architecture is the server cannot respond
multiple request same time, as a result it cause a data integrity issue.

Advantages:

Easy to maintain and modification is bit easy


Communication is faster
Disadvantages:

In two tier architecture application performance will be degrade upon increasing the
users.
Cost-ineffective
Three-Tier Architecture:
Three-tier architecture typically comprise a presentation tier, a business or data
access tier, and a data tier. Three layers in the three tier architecture are as follows:

1) Client layer
2) Business layer
3) Data layer

1) Client layer:

It is also called as Presentation layer which contains UI part of our application. This
layer is used for the design purpose where data is presented to the user or input is
taken from the user. For example designing registration form which contains text
box, label, button etc.

2) Business layer:

In this layer all business logic written like validation of data, calculations, data
insertion etc. This acts as a interface between Client layer and Data Access Layer.
This layer is also called the intermediary layer helps to make communication faster
between client and data layer.
3) Data layer:

In this layer actual database is comes in the picture. Data Access Layer contains
methods to connect with database and to perform insert, update, delete, get data
from database based on our input data.

Three-tier Architecture
Three-tier Architecture
Advantages

High performance, lightweight persistent objects


Scalability – Each tier can scale horizontally
Performance – Because the Presentation tier can cache requests, network utilization
is minimized, and the load is reduced on the Application and Data tiers.
High degree of flexibility in deployment platform and configuration
Better Re-use
Improve Data Integrity
Improved Security – Client is not direct access to database.
Easy to maintain and modification is bit easy, won’t affect other modules
In three tier architecture application performance is good.
Disadvantages

Increase Complexity/Effort

Definition of N-Tier Architecture


N-tier architecture is also called multi-tier architecture because the software is
engineered to have the processing, data management, and presentation functions
physically and logically separated. That means that these different functions are
hosted on several machines or clusters, ensuring that services are provided without
resources being shared and, as such, these services are delivered at top capacity.
The “N” in the name n-tier architecture refers to any number from 1.

Not only does your software gain from being able to get services at the best possible
rate, but it’s also easier to manage. This is because when you work on one section,
the changes you make will not affect the other functions. And if there is a problem,
you can easily pinpoint where it originates.
A More In-Depth Look at N-Tier Architecture
N-tier architecture would involve dividing an application into three different tiers.
These would be the

1. logic tier,
2. the presentation tier, and
3. the data tier.

The separate physical location of these tiers is what differentiates n-tier


architecture from the model-view-controller framework that only separates
presentation, logic, and data tiers in concept. N-tier architecture also differs from
MVC framework in that the former has a middle layer or a logic tier, which
facilitates all communications between the different tiers. When you use the MVC
framework, the interaction that happens is triangular; instead of going through the
logic tier, it is the control layer that accesses the model and view layers, while the
model layer accesses the view layer. Additionally, the control layer makes a model
using the requirements and then pushes that model into the view layer.
This is not to say that you can only use either the MVC framework or the n-tier
architecture. There are a lot of software that brings together these two
frameworks. For instance, you can use the n-tier architecture as the overall
architecture, or use the MVC framework in the presentation tier.

What Are the Benefits of N-Tier Architecture?


There are several benefits to using n-tier architecture for your software. These are
scalability, ease of management, flexibility, and security.

 Secure: You can secure each of the three tiers separately using different
methods.
 Easy to manage: You can manage each tier separately, adding or modifying
each tier without affecting the other tiers.
 Scalable: If you need to add more resources, you can do it per tier, without
affecting the other tiers.
 Flexible: Apart from isolated scalability, you can also expand each tier in any
manner that your requirements dictate.

In short, with n-tier architecture, you can adopt new technologies and add more
components without having to rewrite the entire application or redesigning your
whole software, thus making it easier to scale or maintain. Meanwhile, in terms of
security, you can store sensitive or confidential information in the logic tier, keeping
it away from the presentation tier, thus making it more secure.

Other benefits include:

 More efficient development. N-tier architecture is very friendly for


development, as different teams may work on each tier. This way, you can be
sure the design and presentation professionals work on the presentation tier
and the database experts work on the data tier.
 Easy to add new features. If you want to introduce a new feature, you can
add it to the appropriate tier without affecting the other tiers.
 Easy to reuse. Because the application is divided into independent tiers, you
can easily reuse each tier for other software projects. For instance, if you
want to use the same program, but for a different data set, you can just
replicate the logic and presentation tiers and then create a new data tier.

J2EE (Java 2 Enterprise Edition) is an environment for developing and deploying


enterprise applications. The J2EE platform consists of J2EE components, services,
Application Programming Interfaces (APIs) and protocols that provide the
functionality for developing multi-tiered and distributed Web based applications.

Before reading further it is recommended to read about multi-tier architecture here.


J2EE is four-tier architecture. These consist of Client Tier (Presentation tier or
Application tier), Web tier, Enterprise JavaBeans Tier (or Application server tier),
and the Enterprise Information Systems Tier or the Data tier.

Two or more tiers can physically reside on the same Java Virtual Machine although
each tier provides a specific type of functionality to an application. Some of the APIs
of J2EE components can be used on more than one tier (i.e. XML API), while other
APIs (i.e., EJB API) or associated with a particular tier. Following diagram is
representing the multi-tier architecture of J2EE.

CLIENT TIER : Client tier consists of programs that interact with the user. It
prompts the user for input and then convert the user’s response into requests that
are forwarded to software on a component that processes the request and returns
results to the client program. J2EE clients can be classified as follows

Web client is A software (usually browser) that accesses resources located on the
web tier.

Ejb client can access one or more enterprise java beans that are located on the EJB
tier rather than resources on the web tier.
EIS clients are the interface between users and resources located on the EIS tier.

Multi-tier clients can access components located on tiers other than the tier where
the multi-tier client resides.

WEB TIER : Web tier accepts requests from other software that was sent using
POST, GET, and PUT operations, which are part of HTTP transmissions. The two
major components of web tier are Servlets and Java Server Pages. A servlet is a java
class that resides on the web tier and is called by a request from a browser client
that operates on the client tier. A servlet is associated with a URL that is mapped by
the servlet container. It typically generates an HTML output stream that is returned
to the web server. The web server in turn transmits the data to the client. JSP is
different than a servlet depending on the container that is used. JSP uses custom
tags to access the bean.

ENTERPRISE JAVA BEANS TIER OR APPLICATION TIER : Enterprise java bean is a


class that contains business logic and callable from a servlet or Jsp. EJB tier
contains the enterprise java beans server that stores and manages enterprise java
beans. This tier automatically handles concurrency issues that assure multiple
clients have simultaneous access to the same object and also manages instances of
components. EJB server and EJB container is responsible for low level system
services that are essential for implementing business logic.

ENTERPRISE INFORMATION SYSTEMS TIER OR DATA TIER : This tier provides


flexibility to developers of J2EE applications since it include variety of resources
and support connectivity to resources. It defines all the elements that are needed to
communicate between J2EE application and non-J2EE software.
What is .NET Framework? Complete Architecture Tutorial

What is Microsoft .Net Framework?


The .Net framework is a software development platform developed by Microsoft. The
framework was meant to create applications, which would run on the Windows
Platform. The first version of the .Net framework was released in the year 2002.

The version was called .Net framework 1.0. The .Net framework has come a long
way since then, and the current version is 4.7.1.
The .Net framework can be used to create both - Form-based and Web-based
applications. Web services can also be developed using the .Net framework.

The framework also supports various programming languages such as Visual Basic
and C#. So developers can choose and select the language to develop the required
application. In this chapter, you will learn some basics of the .Net framework.

In this tutorial, you will learn-

.Net Framework Architecture


.NET Components
.Net Framework Design Principle
.Net Framework Architecture
The basic architecture of the .Net framework is as shown below.

What is .NET Framework

.net framework architecture diagram


.NET Components
The architecture of the .Net framework is based on the following key components;

Architecture of .NET Framework


1. Common Language Runtime
The "Common Language Infrastructure" or CLI is a platform on which the .Net
programs are executed.

The CLI has the following key features:

Exception Handling - Exceptions are errors which occur when the application is
executed.
Examples of exceptions are:

If an application tries to open a file on the local machine, but the file is not present.
If the application tries to fetch some records from a database, but the connection to
the database is not valid.
Garbage Collection - Garbage collection is the process of removing unwanted
resources when they are no longer required.
Examples of garbage collection are

A File handle which is no longer required. If the application has finished all
operations on a file, then the file handle may no longer be required.
The database connection is no longer required. If the application has finished all
operations on a database, then the database connection may no longer be required.
Working with Various programming languages –
As noted in an earlier section, a developer can develop an application in a variety of
.Net programming languages.

Language - The first level is the programming language itself, the most common
ones are VB.Net and C#.
Compiler – There is a compiler which will be separate for each programming
language. So underlying the VB.Net language, there will be a separate VB.Net
compiler. Similarly, for C#, you will have another compiler.
Common Language Interpreter – This is the final layer in .Net which would be used
to run a .net program developed in any programming language. So the subsequent
compiler will send the program to the CLI layer to run the .Net application.
What is .NET Framework

2. Class Library
The .NET Framework includes a set of standard class libraries. A class library is a
collection of methods and functions that can be used for the core purpose.

For example, there is a class library with methods to handle all file-level operations.
So there is a method which can be used to read the text from a file. Similarly, there
is a method to write text to a file.

Most of the methods are split into either the System.* or Microsoft.* namespaces.
(The asterisk * just means a reference to all of the methods that fall under the
System or Microsoft namespace)
A namespace is a logical separation of methods. We will learn these namespaces
more in detail in the subsequent chapters.

3. Languages
The types of applications that can be built in the .Net framework is classified
broadly into the following categories.

WinForms – This is used for developing Forms-based applications, which would run
on an end user machine. Notepad is an example of a client-based application.
ASP.Net – This is used for developing web-based applications, which are made to
run on any browser such as Internet Explorer, Chrome or Firefox.
The Web application would be processed on a server, which would have Internet
Information Services Installed.
Internet Information Services or IIS is a Microsoft component which is used to
execute an Asp.Net application.
The result of the execution is then sent to the client machines, and the output is
shown in the browser.
ADO.Net – This technology is used to develop applications to interact with
Databases such as Oracle or Microsoft SQL Server.
Microsoft always ensures that .Net frameworks are in compliance with all the
supported Windows operating systems.

.Net Framework Design Principle


The following design principles of the .Net framework is what makes it very relevant
to create .Net based applications.

Interoperability - The .Net framework provides a lot of backward support. Suppose if


you had an application built on an older version of the .Net framework, say 2.0. And
if you tried to run the same application on a machine which had the higher version
of the .Net framework, say 3.5. The application would still work. This is because
with every release, Microsoft ensures that older framework versions gel well with the
latest version.
Portability- Applications built on the .Net framework can be made to work on any
Windows platform. And now in recent times, Microsoft is also envisioning to make
Microsoft products work on other platforms, such as iOS and Linux.
Security - The .NET Framework has a good security mechanism. The inbuilt
security mechanism helps in both validation and verification of applications. Every
application can explicitly define their security mechanism. Each security
mechanism is used to grant the user access to the code or to the running program.
Memory management - The Common Language runtime does all the work or
memory management. The .Net framework has all the capability to see those
resources, which are not used by a running program. It would then release those
resources accordingly. This is done via a program called the "Garbage Collector"
which runs as part of the .Net framework.
The garbage collector runs at regular intervals and keeps on checking which system
resources are not utilized, and frees them accordingly.

Simplified deployment - The .Net framework also have tools, which can be used to
package applications built on the .Net framework. These packages can then be
distributed to client machines. The packages would then automatically install the
application.
UNIT III

Jsp- java mail-servlet

Introduction to JSP

Introduction

It stands for Java Server Pages.

It is a server side technology.

It is used for creating web application.

It is used to create dynamic web content.

In this JSP tags are used to insert JAVA code into HTML pages.

It is an advanced version of Servlet Technology.

It is a Web based technology helps us to create dynamic and platform independent


web pages.

In this, Java code can be inserted in HTML/ XML pages or both.

JSP is first converted into servlet by JSP container before processing the client’s
request.

JSP pages are more advantageous than Servlet:

They are easy to maintain.

No recompilation or redeployment is required.


JSP has access to entire API of JAVA .

JSP are extended version of Servlet.

Features of JSP

Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.

Reduction in the length of Code :- In JSP we use action tags, custom tags etc.

Connection to Database is easier :-It is easier to connect website to database and


allows to read or write data easily to the database.

Make Interactive websites :- In this we can create dynamic web pages which helps
user to interact in real time environment.

Portable, Powerful, flexible and easy to maintain :- as these are browser and server
independent.

No Redeployment and No Re-Compilation :- It is dynamic, secure and platform


independent so no need to re-compilation.

Extension to Servlet :- as it has all features of servlets, implicit objects and custom
tags

JSP syntax

Syntax available in JSP are following

Declaration Tag :-It is used to declare variables.

Syntax:-

<%! Dec var %>

Example:-

<%! int var=10; %>

Java Scriplets :- It allows us to add any number of JAVA code, variables and
expressions.

Syntax:-

<% java code %>

JSP Expression :- It evaluates and convert the expression to a string.


Syntax:-

<%= expression %>

Example:-

<% num1 = num1+num2 %>

JAVA Comments :- It contains the text that is added for information which has to
be ignored.

Syntax:-

<% -- JSP Comments %>

Process of Execution

Steps for Execution of JSP are following:-

Create html page from where request will be sent to server eg try.html.

To handle to request of user next is to create .jsp file Eg. new.jsp

Create project folder structure.

Create XML file eg my.xml.

Create WAR file.

Start Tomcat

Run Application

Example of Hello World

We will make one .html file and .jsp file


demo.jsp

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Hello World - JSP tutorial</title>

</head>

<body>

<%= "Hello World!" %>

</body>

</html>

Advantages of using JSP

It does not require advanced knowledge of JAVA

It is capable of handling exceptions

Easy to use and learn

It can tags which are easy to use and understand

Implicit objects are there which reduces the length of code

It is suitable for both JAVA and non JAVA programmer

Disadvantages of using JSP

Difficult to debug for errors.

First time access leads to wastage of time

It’soutput is HTML which lacks features.

JSP Scriptlet tag (Scripting elements)


1. Scripting elements
2. JSP scriptlet tag
3. Simple Example of JSP scriptlet tag
4. Example of JSP scriptlet tag that prints the user name
In JSP, java code can be written inside the jsp page using the scriptlet tag. Let's see what are the
scripting elements first.

JSP Scripting elements


The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:

o scriptlet tag
o expression tag
o declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

1. <% java source code %>

Example of JSP scriptlet tag


In this example, we are displaying a welcome message.

1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>

Example of JSP scriptlet tag that prints the user name


In this example, we have created two files index.html and welcome.jsp. The index.html file gets
the username from the user and the welcome.jsp file prints the username with the welcome
message.

File: index.html

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp

1. <html>
2. <body>
3. <%
4. String name=request.getParameter("uname");
5. out.print("welcome "+name);
6. %>
7. </form>
8. </body>
9. </html>

JSP expression tag


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. It is mainly used to print the values of variable or
method.

Syntax of JSP expression tag


1. <%= statement %>

Example of JSP expression tag


In this example of jsp expression tag, we are simply displaying a welcome message.

1. <html>
2. <body>
3. <%= "welcome to jsp" %>
4. </body>
5. </html>

Note: Do not end your statement with semicolon in case of expression tag.

Example of JSP expression tag that prints current time


To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the instance
of Calendar class by the getInstance() method.

index.jsp

1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>
Example of JSP expression tag that prints the user name
In this example, we are printing the username using the expression tag. The index.html file gets
the username and sends the request to the welcome.jsp file, which displays the username.

File: index.jsp

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>

File: welcome.jsp

1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>

JSP Declaration Tag


1. JSP declaration tag
2. Difference between JSP scriptlet tag and JSP declaration tag
3. Example of JSP declaration tag that declares field
4. Example of JSP declaration tag that declares method

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.

Syntax of JSP declaration tag

The syntax of the declaration tag is as follows:

1. <%! field or method declaration %>


Difference between JSP Scriptlet tag and Declaration tag
Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables not The jsp declaration tag can declare variable
methods. methods.

The declaration of scriptlet tag is placed inside the The declaration of jsp declaration tag is pla
_jspService() method. _jspService() method.

Example of JSP declaration tag that declares field


In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.

index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the cube of
given number and calling this method from the jsp expression tag. But we can also use jsp
scriptlet tag to call the declared method.

index.jsp
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>

JSP Implicit Objects


1. JSP Implicit Objects
2. out implicit object
3. Example of out implicit object

There are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.

The available implicit objects are out, request, config, session, application etc.

A list of the 9 implicit objects is given below:

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable

JSP Declaration Tags

Declaration tags in JSP function as identification containers for the functions,


methods and variables in JSP pages. Because these tags identify rather than
generate output, you will most often find declaration tags working in combination
with expression or scriptlet tags. Syntax options include the simple "<%! jsp
declaration %>" and the XML alternative "jsp:declaration…."
JSP Expression Tags

Expression tags signal JSP to convert a Java statement – also called an expression –
into a string and display the output. Syntax options include the simple "<%= Java
statement %>" and the XML alternative "jsp:expression…."

VIDEO OF THE DAY

JSP Directive Tags

Directives – or message tags – are instructional tags that contain two parts: type
and attribute. Type can be "page," which gives page-specific processing directions,
"Include," which provides specific file names or "Tag Library," which identifies the
tag library you want to use on the current page. Syntax options include the simple
"<%@ dir-type dir-attr %> and the XML alternative "."

JSP Scriptlet Tags

Scriptlet tags allow you to embed any valid Java source code in JSP server pages.
The code within the tags executes in consecutive order on the server side and is
available for client access through a Web browser. Syntax options include the
simple "<% Java code %> and the XML alternative "jsp:scriptlet Java code."

JSP Flow Control Tags

Flow control tags function the same as – and are an alternative to – scriptlets.
Unlike scriptlets, however, flow control tags allow you to control the order in which
statements run. The conditional tags "if" and "choose" and the iterator tags
"forEach" and "forTokens" are all examples of JSP flow control tags. The syntax
framework for each includesJava code. For example, when you use an "if"
statement, the correct syntax isJava codewhere test= is the type and "$test
parameters" identifies tag attributes.

JSP Action Tags

Action tags can tell JSP to transfer control between pages, set or get properties,
facilitate browser independent support for Java applets and make it possible to use
server-side JavaBeans. Of the many available action tags, the most common are the
include directive, the forward tag, which transfers control to a dynamic or static
URL and the useBean tag, which allows a JSP to create or receive an instance of a
reusable software component that works with Java called a JavaBean. The only
syntax option for an action tag is the XML version: "jsp:useBean Java body."

JSP Comment Tags

Comment tags are for "information only" and do not appear on JSP pages. Use them
for clarification or documentation and view them by right clicking on a Web page
and accessing the "view source" option. The only syntax option for a comment tag is
the simple version: <%/ comments go here />.

Servlets | Servlet Tutorial

Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language. However, there were many disadvantages to this technology. We have discussed these
disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.

What is a Servlet?
Servlet can be described in many ways, depending on the context.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web page.

CGI (Common Gateway Interface)

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
request, it starts a new process.

CGI vs., Servlet

Disadvantages of CGI

There are many problems in CGI technology:

If the number of clients increases, it takes more time for sending the response.

For each request, it starts a process, and the web server is limited to start
processes.

It uses platform dependent language e.g. C, C++, perl.

Advantages of Servlet

Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads
for handling the multiple requests to the Servlet. Threads have many benefits over
the Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low. The advantages of Servlet are as
follows:

Better performance: because it creates a thread for each request, not process.

Portability: because it uses Java language.

Robust: JVM manages Servlets, so we don't need to worry about the memory leak,
garbage collection, etc.

Secure: because it uses java language.

Servlet Interface
1. Servlet Interface
2. Methods of Servlet interface

Servlet interface provides commonbehaviorto all the servlets.Servlet interface defines


methods that all servlets must implement.

Servlet interface needs to be implemented for creating any servlet (either directly or indirectly).
It provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and
to destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface


There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods
of servlet. These are invoked by the web container.

Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the
web container only once.

public void service(ServletRequest provides response for the incoming


request,ServletResponse response) request. It is invoked at each request
by the web container.
public void destroy() is invoked only once and indicates that
servlet is being destroyed.

public ServletConfig getServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about servlet such


as writer, copyright, version etc.

Life Cycle of a Servlet (Servlet Life Cycle)

Life Cycle of a Servlet

Servlet class is loaded

Servlet instance is created

init method is invoked

service method is invoked

destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:

Servlet class is loaded.

Servlet instance is created.

init method is invoked.

service method is invoked.

destroy method is invoked.

Life cycle of a servlet

As displayed in the above diagram, there are three states of a servlet: new, ready
and end. The servlet is in new state if servlet instance is created. After invoking the
init() method, Servlet comes in the ready state. In the ready state, servlet performs
all the tasks. When the web container invokes the destroy() method, it shifts to the
end state.

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class.
The servlet instance is created only once in the servlet life cycle.

3) init method is invoked

The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life cycle method
of the javax.servlet.Servlet interface. Syntax of the init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked

The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described
above then calls the service method. If servlet is initialized, it calls the service
method. Notice that servlet is initialized only once. The syntax of the service method
of the Servlet interface is given below:

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException

5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance
from the service. It gives the servlet an opportunity to clean up any resource for
example memory, thread etc. The syntax of the destroy method of the Servlet
interface is given below:

public void destroy()

The JavaMail API provides a platform-independent and protocol-independent


framework to build mail and messaging applications. The JavaMail API provides
a set of abstract classes defining objects that comprise a mail system. It is an
optional package (standard extension) for reading, composing, and sending
electronic messages.

JavaMail provides elements that are used to construct an interface to a


messaging system, including system components and interfaces. While this
specification does not define any specific implementation, JavaMail does include
several classes that implement RFC822 and MIME Internet messaging
standards. These classes are delivered as part of the JavaMail class package.

Following are some of the protocols supported in JavaMail API:

 SMTP: Acronym for Simple Mail Transfer Protocol. It provides a mechanism to


deliver email.

 POP: Acronym for Post Office Protocol. POP is the mechanism most people on the
Internet use to get their mail. It defines support for a single mailbox for each user.
RFC 1939 defines this protocol.

 IMAP: Acronym for Internet Message Access Protocol. It is an advanced protocol


for receiving messages. It provides support for multiple mailbox for each user, in
addition to, mailbox can be shared by multiple users. It is defined in RFC 2060.

 MIME: Acronym for Multipurpose Internet Mail Extensions. . It is not a mail


transfer protocol. Instead, it defines the content of what is transferred: the format of
the messages, attachments, and so on. There are many different documents that
take effect here: RFC 822, RFC 2045, RFC 2046, and RFC 2047. As a user of the
JavaMail API, you usually don't need to worry about these formats. However, these
formats do exist and are used by your programs.

 NNTP and Others:There are many protocols that are provided by third-party
providers. Some of them are Network News Transfer Protocol (NNTP), Secure
Multipurpose Internet Mail Extensions (S/MIME) etc.

Details of these will be covered in the subsequent chapters.


Architecture
As said above the java application uses JavaMail API to compose, send and
receive emails.The following figure illustrates the architecture of JavaMail:

The abstract mechanism of JavaMail API is similar to other J2EE APIs, such as
JDBC, JNDI, and JMS. As seen the architecture diagram above, JavaMail API is
divided into two main parts:

 An application-independent part: An application-programming interface (API) is used


by the application components to send and receive mail messages, independent of
the underlying provider or protocol used.

 A service-dependent part: A service provider interface (SPI) speaks the protocol-


specific languages, such as SMTP, POP, IMAP, and Network News Transfer Protocol
(NNTP). It is used to plug in a provider of an e-mail service to the J2EE platform.
To send an e-mail using your Java Application is simple enough but to start with
you should have JavaMail API and Java Activation Framework
(JAF)installed on your machine.
You will need the JavaBeans Activation Framework (JAF) extension that provides
the javax.activation package only when you're not using Java SE 6 or newer.

 You can download latest version of JavaMail (Version 1.5.0) from Java's standard
website.

 You can download latest version of JAF (Version 1.1.1) from Java's standard website.

Download and unzip these files, in the newly created top level directories you
will find a number of jar files for both the applications. You need to
add mail.jar and activation.jar files in your CLASSPATH.

SMTP server
To send emails, you must have SMTP server that is responsible to send mails.
You can use one of the following techniques to get the SMTP server:

 Install and use any SMTP server such as Postfix server (for Ubuntu), Apache James
server (Java Apache Mail Enterprise Server)etc. (or)

 Use the SMTP server provided by the host provider for eg: free SMTP provide
by JangoSMTP site is relay.jangosmtp.net (or)

 Use the SMTP Server provided by companies e.g. gmail, yahoo, etc.
The examples in the subsequent chapters, we've used the free JangoSMTP server to send
email. You can create an account by visiting this site and configure your email adress.

UNIT IV Component Model:

EJB: Session beans: Stateless and Statefull – Entity beans – CMP and BMP –
Message Driven Beans.

Stateless Session Beans

A session bean represents work performed by a singleclient. That work can be performed within a single method

invocation, or it may span multiple method invocations. If the work does span more than one method, the object must

retain the user’s object state across the method calls, and a stateful session bean would therefore be required.

Generally, stateless beans are intended to perform individual operations automatically and don’t maintain state across

method invocations. They’re also amorphous, in that any client can use any instance of a stateless bean at any time at
the container’s discretion. They are the lightest weight and easiest to manage of the various EJB component

configurations.

Stateful Session Beans

Stateful session beans maintain state both within and between transactions. Each stateful session bean is therefore

associated with a specific client. Containers are able to save and retrieve a bean’s state automatically while managing

instance pools (as opposed to bean pools) of stateful session beans.

Stateful session beans maintain data consistency by updating their fields each time a transaction is committed. To

keep informed of changes in transaction status, a stateful session bean implements the SessionSynchronization

interface. The container calls methods of this interface while it initiates and completes transactions involving the

bean.

Session beans, whether stateful or stateless, are not designed to be persistent. The data maintained by stateful session

beans is intended to be transitional. It is used solely for a particular session with a particular client. A stateful session

bean instance typically can’t survive system failures and other destructive events. While a session bean has a

container-provided identity (called its handle), that identity passes when the client removes the session bean at the

end of a session. If a client needs to revive a stateful session bean that has disappeared, it must provide its own means

to reconstruct the bean’s state.

Stateful vs. Stateless Session Beans

A stateful session bean will maintain a conversational state with a client. The state of the session is maintained for the

duration of the conversation between the client and the stateful session bean. When the client removes the stateful

session bean, its session ends and the state is destroyed. The transient nature of the state of the stateful session bean

should not be problematic for either the client or the bean, because once the conversation between the client and the

stateful session bean ends, neither the client nor the stateful session bean should have any use for the state.

A stateless session bean will not maintain conversational states for specific clients longer than the period of an

individual method invocation. Instance variables used by a method of a stateless bean may have a state, but only for

the duration of the method invocation. After a method has finished running either successfully or unsuccessfully, the

states of all its instance variables are dropped. The transient nature of this state gives the stateless session bean

beneficial attributes, such as the following:

 Bean pooling Any stateless session bean method instance that is not currently invoked is equally available

to be called by an EJB container or application server to service the request of a client. This allows the EJB

container to pool stateless bean instances and increase performance.


 Scalability Because stateless session beans are able to service multiple clients, they tend to be more scalable

when applications have a large number of clients. When compared to stateful session beans, stateless session

beans usually require less instantiation.

 Performance An EJB container will never move a stateless session bean from RAM out to a secondary

storage, which it may do with a stateful session bean; therefore, stateless session beans may offer greater

performance than stateful session beans.

Since no explicit mapping exists between multiple clients and stateless bean instances, the EJB container is free to

service any client’s request with any available instance. Even though the client calls

the create() and remove()methods of the stateless session bean, making it appear that the client is controlling the

lifecycle of an EJB, it is actually the EJB container that is handling the create() and remove() methods without

necessarily instantiating or destroying an EJB instance.

Entity beans

The need of entity beans.


Entity beans are objects that represents a persistence storage mechanism. The objects can
be a customer, product, account etc. Each entity bean has underlying table in a relational
database and each row in the table represents the instance of the bean.

Need of entity beans:

1. When it is needed by multiple clients.

2. When any action from the database side.

3. When a transaction is to be performed from the client.

4. When the enforcement of accuracy and integrity is needed.

Types of Entity beans and their uses.


There are two types of entity beans.:

1) Container Managed Persistence (CMP)


2) Bean Managed Persistence (BMP)

CMP can be used when:

- No code for database code is needed(by placing the specific accessibility is provided by
XML file).
- The code reusability is needed.

- The speed of development by creation of the database access code by the developers.

BMP can be used when:

- Synchronizing the state of the database directly by the container.

- To provide the flexibility for the bean developer to perform the persistence operations.

- The needs of the query exceeds the capabilities of EJB QL.

- The persistent storage is a non database system or is a legacy database system that does
not supports for CMP.

steps involved in developing Entity beans.


1. Select which bean is to be used – BMP or CMP entity bean

2. Create the required entity bean.

3. Author the source code for the entity bean, which involves developing the following:

a. The component interface(s)


b. The home interface(s)
c. The bean class
d. Any helper classes required by the entity bean

4. Develop the deployment descriptors for the beans.

5. Create the database tables. (If your database tables already exist, you can omit this step)

6. Establish the Object Relation mapping.

7. Compile and archive all the EJB components into a JAR file.

8. Archive the complete application into an EAR file.

9. Make the deployment of the application onto the J2EE engine.

10. Start the application.

steps involved in deployment of CMP and BMP entity beans.


The purpose of deployment of entity bean is to make them available for the client
applications.

Requirements before deploying:


1. Author and compile the various entity beans that are to be deployed. This includes bean
class, remote interfaces, home interfaces, and the primary key class, if required.

2. Get the mapping done for the entity beans for the appropriate database tables and save
the mapping information that is a deployable XML file.

3. Assemble the entity beans into a .jar or .ear file

Steps involved in deployment of entity beans:

There are three steps in deploying the entity beans.

1. Configuration :

- Specifying the number of properties for the bean.


- The usage of persistence mechanism and the needed information to do so.

2. Code generation :

- The information from the configuration phase is used by the different tools to generate the
classes for the required beans.
- This process may include helper classes related to transactions, persistence, and security.
- The implementations of EJBHome and EJBObject, and the stubs and skeletons required for
RMI-IIOP.

3. Installation :

- The EJB server is started and make the beans available to the clients applications.

lifecycle of the entity beans.


The time when the entity bean starts instantiating and till it takes the time for garbage
collection is the life cycle of an entity bean.

The life cycle has three states, namely

1. Does not exist state


2. Pooled state
3. Ready state

1. Does not Exist State :

- The life of a bean’s instance starts with a set of files. These files include remote interface,
interface, deployment descriptor, primary key and the needed files at the time of
deployment.

- In this state, no instances of the bean exists.


2. Pooled State :

- At the time of starting the EJB server,with the help of the method Class.newInstance() , all
the instances are created and placed in a pool. The default values of the persistent fields are
set. The bean class should never contain the constructor. Therefore the default no-argument
must be available in the container.

- Before placing the instances in the pool, an instance EntityContext is assigned by the
container which assigns and implements the setEntityContext() method by the bean class,
followed by entering into the instance pool.

- Now the bean instance is available for the client requests and become active soon after
receiving the requests. The bean container provides different levels of access at every stage
of the bean’s life cycle.

3. The Ready State:

- Once the bean reaches this state, it can accept the requests from the client. The state of a
beans instance reaches to ready state once the container assigns it to an EJB object.

- This assignment occurs in two different circumstances:

1. When the new entity bean is being created.


2. When the container is activating an entity bean.

4. End of the Life Cycle :

- The life of a bean’s instance comes to an end when the container decides to remove it from
the pool and allows it to be garbage collected.

- This may happen when the container decides to reduce the number of instances from the
pool in order to conserve the resources. So that the highest performance can be achieved.

CMP (Container-Managed Persistence) :

- All the logic for synchronizing the bean's state with the database is handled automatically by the container.

- The bean developer doesn't need to write any data access logic.

- The EJB server is supposed to take care of all the persistence needs automatically.
- Vendor tools are used to map the entity fields to the database and absolutely no database access code is writ
bean class.

BMP (Bean-Managed Persistence) :

- Enterprise bean manages synchronizing its state with the database as directed by the container.

- BMP gives the bean developer the flexibility to perform persistence operations that are too complicated for the
container or to use a data source that is not supported by the container.

- The bean uses a database API to read and write its fields to the database, but the container tells it when to do
synchronization operation and manages the transactions for the bean automatically.

What Is a Message-Driven Bean?

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.

What Makes Message-Driven Beans Different from Session Beans?


The most visible difference between message-driven beans and session beans is that clients do not access message-driven
beans through interfaces. Interfaces are described in the section Accessing Enterprise Beans. Unlike a session bean, a
message-driven bean has only a bean class.

In several respects, a message-driven bean resembles a stateless session bean.

 A message-driven bean’s instances retain no data or conversational state for a specific client.
 All instances of a message-driven bean are equivalent, allowing the EJB container to assign a message to any
message-driven bean instance. The container can pool these instances to allow streams of messages to be processed
concurrently.
 A single message-driven bean can process messages from multiple clients.

The instance variables of the message-driven bean instance can contain some state across the handling of client
messages, such as a JMS API connection, an open database connection, or an object reference to an enterprise bean
object.

Client components do not locate message-driven beans and invoke methods directly on them. Instead, a client accesses a
message-driven bean through, for example, JMS by sending messages to the message destination for which the message-
driven bean class is the MessageListener. You assign a message-driven bean’s destination during deployment by
using GlassFish Server resources.

Message-driven beans have the following characteristics.

 They execute upon receipt of a single client message.


 They are invoked asynchronously.
 They are relatively short-lived.
 They do not represent directly shared data in the database, but they can access and update this data.
 They can be transaction-aware.
 They are stateless.
When a message arrives, the container calls the message-driven bean’s onMessage method to process the message.
The onMessage method normally casts the message to one of the five JMS message types and handles it in accordance
with the application’s business logic. The onMessage method can call helper methods or can invoke a session bean to
process the information in the message or to store it in a database.

A message can be delivered to a message-driven bean within a transaction context, so all operations within
the onMessage method are part of a single transaction. If message processing is rolled back, the message will be
redelivered. For more information, see Chapter 25, A Message-Driven Bean Example and Chapter 44, Transactions.

When to Use Message-Driven Beans


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.

UNIT V Struts Framework:

Introduction – Building a simple struts – Model layers –View layer – controller layer
– Validator – Tiles –Declarative Exception Handling –Struts Modules.

Struts
The struts framework is used to develop MVC-based web application.

Apache Struts 2 is an elegant, extensible framework for creating enterprise-ready


Java web applications. This framework is designed to streamline the full
development cycle from building, to deploying and maintaining applications over
time. Apache Struts 2 was originally known as Web Work 2. This tutorial will teach
you, how to use Apache Struts for creating enterprise-ready Java web applications in
simple and easy steps.

Model View Controller or MVC as it is popularly called, is a software design pattern


for developing web applications. A Model View Controller pattern is made up of the
following three parts −

Model − The lowest level of the pattern which is responsible for maintaining data.

View − This is responsible for displaying all or a portion of the data to the user.
Controller − Software Code that controls the interactions between the Model and
View.

MVC is popular as it isolates the application logic from the user interface layer and
supports separation of concerns. Here the Controller receives all requests for the
application and then works with the Model to prepare any data needed by the View.
The View then uses the data prepared by the Controller to generate a final
presentable response. The MVC abstraction can be graphically represented as
follows.

Struts2 is a popular and mature web application framework based on the MVC
design pattern. Struts2 is not just a new version of Struts 1, but it is a complete
rewrite of the Struts architecture.

The Webwork framework initially started with Struts framework as the basis and
its goal was to offer an enhanced and improved framework built on Struts to
make web development easier for the developers.

After a while, the Webwork framework and the Struts community joined hands
to create the famous Struts2 framework.

Struts 2 Framework Features


Here are some of the great features that may force you to consider Struts2 −

 POJO Forms and POJO Actions − Struts2 has done away with the Action Forms
that were an integral part of the Struts framework. With Struts2, you can use any
POJO to receive the form input. Similarly, you can now see any POJO as an Action
class.

 Tag Support − Struts2 has improved the form tags and the new tags which allow
the developers to write less code.

 AJAX Support − Struts2 has recognized the take over by Web2.0 technologies, and
has integrated AJAX support into the product by creating AJAX tags, this function is
very similar to the standard Struts2 tags.

 Easy Integration − Integration with other frameworks like Spring, Tiles and
SiteMesh is now easier with a variety of integration available with Struts2.

 Template Support − Support for generating views using templates.


 Plugin Support − The core Struts2 behavior can be enhanced and augmented by
the use of plugins. A number of plugins are available for Struts2.

 Profiling − Struts2 offers integrated profiling to debug and profile the application. In
addition to this, Struts also offers integrated debugging with the help of built in
debugging tools.

 Easy to Modify Tags − Tag markups in Struts2 can be tweaked using Freemarker
templates. This does not require JSP or java knowledge. Basic HTML, XML and CSS
knowledge is enough to modify the tags.

 Promote Less configuration − Struts2 promotes less configuration with the help of
using default values for various settings. You don't have to configure something
unless it deviates from the default settings set by Struts2.

 View Technologies − Struts2 has a great support for multiple view options (JSP,
Freemarker, Velocity and XSLT)

Listed above are the Top 10 features of Struts 2 which makes it as an


Enterprise ready framework.

Struts 2 Disadvantages
Though Struts 2 comes with a list of great features, there are some limitations
of the current version - Struts 2 which needs further improvement. Listed are
some of the main points −

 Bigger Learning Curve − To use MVC with Struts, you have to be comfortable with
the standard JSP, Servlet APIs and a large & elaborate framework.

 Poor Documentation − Compared to the standard servlet and JSP APIs, Struts has
fewer online resources, and many first-time users find the online Apache
documentation confusing and poorly organized.

 Less Transparent − With Struts applications, there is a lot more going on behind
the scenes than with normal Java-based Web applications which makes it difficult to
understand the framework.

Final note, a good framework should provide generic behavior that many
different types of applications can make use of it.

Struts 2 is one of the best web frameworks and being highly used for the
development of Rich Internet Applications (RIA).
Struts MVC

The Model

The model is responsible for managing the data of the application. It responds to
the request from the view and it also responds to instructions from the controller to
update itself.

The View

It means presentation of data in a particular format, triggered by a controller's


decision to present the data. They are script-based templating systems like JSP,
ASP, PHP and very easy to integrate with AJAX technology.

The Controller

The controller is responsible for responding to the user input and perform
interactions on the data model objects. The controller receives the input, it validates
the input and then performs the business operation that modifies the state of the
data model.

Struts2 is a MVC based framework. In the coming chapters, let us see how we can
use the MVC methodology within Struts2.

Struts2 is a popular and mature web application framework based on the MVC
design pattern. Struts2 is not just a new version of Struts 1, but it is a complete
rewrite of the Struts architecture.

The Webwork framework initially started with Struts framework as the basis and
its goal was to offer an enhanced and improved framework built on Struts to
make web development easier for the developers.

After a while, the Webwork framework and the Struts community joined hands
to create the famous Struts2 framework.

Struts 2 Framework Features


Here are some of the great features that may force you to consider Struts2 −

 POJO Forms and POJO Actions − Struts2 has done away with the Action Forms
that were an integral part of the Struts framework. With Struts2, you can use any
POJO to receive the form input. Similarly, you can now see any POJO as an Action
class.

 Tag Support − Struts2 has improved the form tags and the new tags which allow
the developers to write less code.

 AJAX Support − Struts2 has recognized the take over by Web2.0 technologies, and
has integrated AJAX support into the product by creating AJAX tags, this function is
very similar to the standard Struts2 tags.

 Easy Integration − Integration with other frameworks like Spring, Tiles and
SiteMesh is now easier with a variety of integration available with Struts2.

 Template Support − Support for generating views using templates.

 Plugin Support − The core Struts2 behavior can be enhanced and augmented by
the use of plugins. A number of plugins are available for Struts2.

 Profiling − Struts2 offers integrated profiling to debug and profile the application. In
addition to this, Struts also offers integrated debugging with the help of built in
debugging tools.

 Easy to Modify Tags − Tag markups in Struts2 can be tweaked using Freemarker
templates. This does not require JSP or java knowledge. Basic HTML, XML and CSS
knowledge is enough to modify the tags.

 Promote Less configuration − Struts2 promotes less configuration with the help of
using default values for various settings. You don't have to configure something
unless it deviates from the default settings set by Struts2.

 View Technologies − Struts2 has a great support for multiple view options (JSP,
Freemarker, Velocity and XSLT)

Listed above are the Top 10 features of Struts 2 which makes it as an


Enterprise ready framework.

Struts 2 Disadvantages
Though Struts 2 comes with a list of great features, there are some limitations
of the current version - Struts 2 which needs further improvement. Listed are
some of the main points −

 Bigger Learning Curve − To use MVC with Struts, you have to be comfortable with
the standard JSP, Servlet APIs and a large & elaborate framework.
 Poor Documentation − Compared to the standard servlet and JSP APIs, Struts has
fewer online resources, and many first-time users find the online Apache
documentation confusing and poorly organized.

 Less Transparent − With Struts applications, there is a lot more going on behind
the scenes than with normal Java-based Web applications which makes it difficult to
understand the framework.

Final note, a good framework should provide generic behavior that many
different types of applications can make use of it.

Struts 2 is one of the best web frameworks and being highly used for the
development of Rich Internet Applications (RIA).

om a high level, Struts2 is a pull-MVC (or MVC2) framework. The Model-


ViewController pattern in Struts2 is implemented with the following five core
components −

 Actions

 Interceptors

 Value Stack / OGNL

 Results / Result types

 View technologies

Struts 2 is slightly different from a traditional MVC framework, where the action
takes the role of the model rather than the controller, although there is some
overlap.
The above diagram depicts the Model, View and Controller to the Struts2 high
level architecture. The controller is implemented with a Struts2 dispatch servlet
filter as well as interceptors, this model is implemented with actions, and the
view is a combination of result types and results. The value stack and OGNL
provides common thread, linking and enabling integration between the other
components.

Apart from the above components, there will be a lot of information that relates
to configuration. Configuration for the web application, as well as configuration
for actions, interceptors, results, etc.

This is the architectural overview of the Struts 2 MVC pattern. We will go


through each component in more detail in the subsequent chapters.

Request Life Cycle


Based on the above diagram, you can understand the work flow through user's
request life cycle in Struts 2 as follows −

 User sends a request to the server for requesting for some resource (i.e. pages).

 The Filter Dispatcher looks at the request and then determines the appropriate
Action.

 Configured interceptor functionalities applies such as validation, file upload etc.


 Selected action is performed based on the requested operation.

 Again, configured interceptors are applied to do any post-processing if required.

 Finally, the result is prepared by the view and returns the result to the user.

Exceptions in Struts based J2EE applications:


Usually there are two ways in which you can catch the exceptions.
1. Declarative Exception Handling
2. Programmatic Exception Handling

Programmatic Exception Handling


In this approach the exceptions are caught using normal java language try/catch block.In this
approach the flow of control is also maintained by the programs. The main drawback of the
approach is the developer has to write the code for the flow of the application.

In this way, we need to put code in try-catch block. If the exception is caught in the try block, the
control flows into catch block, where we add the errors into the messages and put it in the
session. Then the control is forwarded manually to the error-page where the warning message is
displayed. The drawback of this method, is the developer is fully responsible for the various flow
of applications where the chance of misleading is high.

 Struts Tutorial
 Struts Basics
 Struts Action & FormBeans
 Struts Modules
 Struts Validation Framework
 Struts Tiles Tutorial
 Exception/Error Handling In Struts

Declarative Exception Handling


Declarative Exception Handling is the way of handling Exceptions with the help of xml files. In this
way of handling exception there is no need to write exception-handling code in the application. In this
approach the exceptions are defined in the struts-config file and in case of the exception occurs the
control is automatically passed to the appropriate error page. The biggest benefit of Declarative
Exception Handling is if there is requirement to change the exception handling mechanism, changes
can be made to the xml file, without recompilation of java code.

The declarative exceptions can be placed as action-specific or global. In action specific, we define
these exceptions and path inside the action tag. Otherwise, the exceptions are defined inside the
global-exception tag. This would mean that, if this exception arises in any action class, it would
automatically forwarded to the specified path known as error-page. The error-page then shows the
exact warning message.

Benefit of Declarative Exception Handling


Prior to version 1.1, exception handling in Struts applications works same way as it does in most
other applications. Inside your code, you have to write several try-catch blocks to handle each of the
exceptions that could be thrown.If developer uses the old exception handling mechanism there would
be code duplication. For example if 10 to 20 struts Action class implement a business logic that
throws same exception, then there will be a lot of exception handling code duplicated in all these
Action classes. If there is need to change exception handling logic , then same code changes should
be made in all the Action classes. But in case of Declarative exception handling, code changes can
be easily done in one place and it will be visible to all Action class.

How to configure Declarative Exception handling in Struts


Exception handler definition should be mentioned in the struts-config.xml.There are two types of
exception handler definition global and local action specific exception handler definition. Global
exception handlers are available to the whole application where as local action handlers are specific
to that particular action.

Action specific exception handling


Below code should be included in the struts-config.xml for action specific exceptions.
Entry in struts-config.xml for action specific Declarative Exception handling:
?

1 <action path = "/login" type= "com.jwt.struts.LoginAction"


2 parameter="name" input="/login.jsp" >

3 <exception key="error.invalid.Password"

type="RuntimeException" path="/index.jsp" />


4
</action>
5

In the above code exceptions will be handled during the login action.
Entry in ApplicationResources.properties
?

1 error.invalidPassword = Invalid password entered. Please try agin.

Handling Exception globally


In this way exceptions should be defined inside the global-exception tag in the struts-config.xml. This
would mean that, if this exception arises in any action class, it would automatically forwarded to the
specified path known as error-page. The error-page then shows the exact warning message.Below
code should be included in the struts-config.xml for global exceptions.
?

1 <global-exceptions>

2 <exception

3 type=”com.javawebtutor.NoResultFoundException”

4 key=”error.NoResultFound.Exception”

5 path=”/noresultpage.jsp”/>

</global-exceptions>
6

Tiles is used to create reusable presentation components. With Tiles, we first


define a base layout with different sections after that we define which jsp page
should fill in the corresponding regions in an exteranl configuration file. The
same layout can be reused any number of times by specifying different jsp
pages.
To use Tiles in the Struts application, we need to add the following <plug-in>
definition to the struts-config.xml file.

<plug-in className="org.apache.struts.tiles.TilesPlugin" >


<set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml" />
<set-property property="moduleAware" value="true" />
</plug-in>

There are two ways in which you can specify the Tiles definition and their
attributes. One is using JSP Tile Definition and the other way is using XML Tile
Definition.
All JSP pages that uses Tiles should have the following taglib extension.

<%@taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>

Lets first design the base layout page using tiles. The base layout page is a
normal jsp page, which defines different sections. A region is defined using
the <tiles:insert> tag. The attribute value hold the name of the region.

The layout shown above can be created using the following code.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><tiles:getAsString name="title" ignore="true" /></title>
</head>
<body>
<table border="1" cellpadding="2" cellspacing="2" align="center">
<tr>
<td height="20%" colspan="2">
<tiles:insert attribute="header" ignore="true" />
</td>
</tr>
<tr>
<td width="20%" height="250">
<tiles:insert attribute="menu" />
</td>
<td>
<tiles:insert attribute="body" />
</td>
</tr>
<tr>
<td height="20%" colspan="2">
<tiles:insert attribute="footer" />
</td>
</tr>
</table>
</body>
</html>

If the ignore attribute is set to true, then that region is optional. Even if the
attribute is not specified the code will work fine.
To create our home page we need to insert title, header, menu, body and footer
jsp pages. The following code is used to create our home page.

<%@taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>


<tiles:insert page="/baseLayout.jsp" flush="true">
<tiles:put name="title" value="Tiles Example" />
<tiles:put name="header" value="/header.jsp" />
<tiles:put name="menu" value="/menu.jsp" />
<tiles:put name="body" value="/body.jsp" />
<tiles:put name="footer" value="/footer.jsp" />
</tiles:insert>

The name attribute of the put tag specifies the region in the baseLayout in
which the corresponding page specified by the value attribute should be
displayed. In our example the header region is occupied by the header.jsp page,
the menu part is occupied by the menu.jsp page, the body part by the body.jsp
page and the footer by the footer.jsp page. The only section that will be
changing when the user request a different page is the body part.
On executing the application the following home page is displayed. The table
border is set to 1 inorder to give a clear seperation between the regions.

On clicking the links in the left menu, only the body part of the page should
change. So instead of forwarding each link to a jsp page, we forward it to a Tile
definition.
tiles-defs.xml file contains all the Tile definitions. A Tile definition can be
added in the following way.

<definition name="baseLayout" path="/baseLayout.jsp">


<put name="title" value="Tiles Example" />
<put name="header" value="/header.jsp" />
<put name="menu" value="/menu.jsp" />
<put name="body" value="/body.jsp" />
<put name="footer" value="/footer.jsp" />
</definition>
The name of the Tile definition is "baseLayout" and it contains one jsp page for
each region. Since the title region is specified using getAsString tag, we provide
a String variable instead of a jsp page. When an action is forwarded to the Tile
definition baseLayout, then the baseLayout.jsp page will be displayed with
corresponding jsp pages in the Tile definition
The powerful and useful feature of the Tile definition is the ability to extend an
other Tile definition. In our example only the tilte and the body regions are
going to change for each link in the left menu. So it is a good practice to create
an new Tile definition which extends the baseLayout, with different values for
title and body regions.

<definition name="friends" extends="baseLayout">


<put name="title" value="Friends" />
<put name="body" value="/friends.jsp" />
</definition>

<definition name="office" extends="baseLayout">


<put name="title" value="The Office" />
<put name="body" value="/office.jsp" />
</definition>

The menu.jsp contains the following code.

<html>
<body>
<a href="Link.do?method=friends" >Friends</a><br>
<a href="Link.do?method=office" >The Office</a>
</body>
</html>

On clicking each link a corresponding method in the LinkAction class is invoked.


The LinkAction class extends the DispatchAction and it contains the following
methods.

public class LinkAction extends DispatchAction {

public ActionForward friends(ActionMapping mapping, ActionForm form, HttpServletR


equest request, HttpServletResponse response) throws Exception {
return mapping.findForward("friends");
}

public ActionForward office(ActionMapping mapping, ActionForm form, HttpServletRe


quest request, HttpServletResponse response) throws Exception {
return mapping.findForward("office");
}
}

Add the following action forward entries in the struts-config.xml file.

<action-mappings>
<action path="/Link" parameter="method" type="com.vaannila.LinkAction">
<forward name="friends" path="friends"/>
<forward name="office" path="office"/>
</action>
</action-mappings>

The path attribute hold the value of the Tile definition to forward. When the
path value is "friends" the baseLayout.jsp page is displayed with the tilte as
Friends and friends.jsp as the body.
When the path value is "office" the baseLayout.jsp page is displayed with the
tilte as The Office and office.jsp as the body.

Struts Modules:
When you develop a web based application using struts,many developers like to put all Struts related
stuff (action, form) into a single Struts configuration file for the entire application .For small application
its not a problem.But if you are developing big application day by day your configuration file will
become complicated.

Generally a large application will be divided into various modules.These modules will be developed
by various teams and finally when you are integrating each module, you may feel it as complex task.
Apache has analysed all these problems and introduced Struts Modules which allows you to
develop modularized struts application.Struts modules concept allows you to write Struts
Configuration file for each module.

1. Single Module Example :


By having multiple struts configuration files it will be easy to maintain and debug. Here we work with a
single module, so you can split the configuration file according to your convenience. During the
startup the ActionServlet will read all the configuration files and create a database of configuration
objects,which it will later refer while processing the request.
Let's see how we can achieve this.

index.jsp
?

1 <html>

2 <body>

3 <h1>This is index page using struts module concept</h1>

4 </body>

</html>
5

info.jsp
?

1 <html>

2 <body>

3 <h1>This is info page using struts module concept</h1>

4 </body>

</html>
5

Now create Struts configuration files for the application.Here we are going to create two configuration
files.We can create any number of configuration files.
struts-config1.xml
?

1 <?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE struts-config PUBLIC
2
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
3
"<a class="vglnk" href="http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd"
4 rel="nofollow"><span>http</span><span>://</span><span>jakarta</span><span>.</span><span>a
</span><span>config</span><span>_</span><span>1</span><span>_</span><span>3</span><span>.
5
<struts-config>
6
<action-mappings>
7
<action
8 path="/Page1"
9 type="org.apache.struts.actions.ForwardAction"

10parameter="/index.jsp"/>
</action-mappings>
11
</struts-config>
12

struts-config2.xml
?

1 <?xml version="1.0" encoding="UTF-8"?>

2 <!DOCTYPE struts-config PUBLIC

3 "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"


"<a class="vglnk" href="http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd"
4 rel="nofollow"><span>http</span><span>://</span><span>jakarta</span><span>.</span><span>a
</span><span>config</span><span>_</span><span>1</span><span>_</span><span>3</span><span>.
5
<struts-config>
6
<action-mappings>
7
<action
8
path="/Page2"
9
type="org.apache.struts.actions.ForwardAction"
10parameter="/info.jsp"/>

11</action-mappings>

12</struts-config>

Now we need to map both the configuration files in web.xml separated by comma.

web.xml
?
1
<!DOCTYPE web-app PUBLIC
2
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
3
"<a class="vglnk" href="http://java.sun.com/dtd/web-app_2_3.dtd"
4 rel="nofollow"><span>http</span><span>://</span><span>java</span><span>.</span><span>sun<
</span><span>app</span><span>_</span><span>2</span><span>_</span><span>3</span><span>.</s
5
<web-app>
6 <display-name>Maven Struts Examples</display-name>

7 <servlet>

8 <servlet-name>action</servlet-name>

9 <servlet-class>
org.apache.struts.action.ActionServlet
10
</servlet-class>
11
<init-param>
12
<param-name>config</param-name>
13
<param-value>
14
/WEB-INF/struts-config-1.xml, /WEB-INF/struts-config-2.xml
15</param-value>

16</init-param>

17<load-on-startup>1</load-on-startup>

18</servlet>

19<servlet-mapping>
<servlet-name>action</servlet-name>
20
<url-pattern>*.do</url-pattern>
21
</servlet-mapping>
22
</web-app>
23

If you are working with multiple modules in your project, then you have to create one configuration file
for each modules. Let's say the project has two modules Employee and Reports.Here Employee and
Department are two different modules

Overview of Validation Framework


 When you are implementing Struts based application you need to implement some code to
validate the input(incoming) data.We can validate the input data by overriding validate() method
in FormBean class.We need to implement the validation logic inside the validate() method.

 Lot of fields that we validate require same logic to validate them.you need to write same code
repeatedly in every validate() method hence code is unnecessarily duplicated.

 To avoid this problem and to simplify the validation handling, Apache has introduced validation
framework.Validation framework is not a part of struts frame work ,it should be integrated into the
struts explicitly.

 The Validator framework allows us to move all the validation logic completely outside
of the ActionForm and declaratively configure it for an application through external
XML files.

 No validation logic is necessary in the ActionForm, which makes your application


easier to develop and maintain because all validation we are managing through
external xml files.Without validation framework you need to write validation logic in
ActionForm class.If you need to modify or enhance the validation that occurs for an
ActionForm, then the source code must be recompiled and your server must be
restarted.This will create a maintenance problem.
 Validation framework comes with set of useful routines to handle form validation
automatically and it can handle both server side as well as client side form validation.
If certain validation is not present, you can create your own validation logic and plug it
into validation framework as a re-usable component.

 The Validator Framework in Struts consist of two XML configuration files. The first one
is the validator-rules.xml file which contains the default Struts pluggable validator
definitions.If you want to create new validation, You can add new validation rules by
adding an entry in this file.
The second one is the validation.xml file which contain details regarding the
validation rules that are applied to the different Form Beans. These two configuration
file should be place inside the /WEB-INF folder of the application.

You might also like