0% found this document useful (0 votes)
19 views22 pages

Unit 1

Uploaded by

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

Unit 1

Uploaded by

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

UNIT 1 INTRODUCTION TO J2EE

ARCHITECTURE AND DESIGN


PATTERN
Structure
1.0 Introduction
1.1 Objectives
1.2 Web Server and Web Container
1.3 Introduction to J2EE
1.4 Design Patterns
1.4.1 MVC
1.4.2 Repository Design Pattern
1.4.3 Singleton
1.4.4 Factory
1.5 Building Java Application JAR and WAR and deployment in Tomcat
1.6 Summary
1.7 Solutions/Answer to Check Your Progress
1.8 References/Further Reading

1.0 INTRODUCTION

You are well aware of the java programming language, which is an object oriented
programming language. Java technology provides the specific environment in which
Java programming language applications run. The J2EE platform provides runtime
environment for developing and running large-scale, multi-tiered online/web and
internet applications. This unit will give you an introduction of J2EE and its
architecture. Also in this unit you will be introduced to some well-known design
patterns. Design patterns give readymade explanations/solutions or templates to
commonly occurring problems in the programming language. Design patterns are the
best solutions that are tested and verified prototypes that can speed up your
development process. There are many design patterns but it is not possible to cover all
patterns in this course. This unit covers MVC, Repository, Singleton, Factory design
patterns and some important terms, including Web server and Web Container. This
unit will also provide you with the skill and process to package Java Application
project to JAR/WAR and deploy your application in Tomcat.

The next Unit 2 and 3 of this block will give you detailed discussions on Servlet
programming and session management in web applications. Unit 4 of this block will
provide you with a basic understanding of Java Server Pages ( JSP) components that
make an entire JSP page, Java Bean, Custom tag, and many other concepts used in
JSP. After studying this block, you will be able to use design patterns and build your
java application using data retrieval and data storage in Servlets/JSP programming
and their deployment in Tomcat.

1.1 OBJECTIVES

After going through this unit, you should be able to:

• differentiate between web server and web container,


• know about design patterns and different types of design patterns,

1
Introduction to J2EE
Architecture and Design
• explain where and why singleton pattern is used,
Pattern
• explain factory method design pattern and how to implement it,
• know the difference between jar and war files and packaging of java
application to JAR/WAR file, and
• deploy java application as war file.

1.2 WEB SERVER AND WEB CONTAINER

You are well aware about web applications and you have opened many web
applications on the internet. Assume that you have filled a form on this and received a
response from them. This communication between you and web application are
fulfilled using HTTP request and HTTP response with HTTP Protocol and method
(You can study much more about these in the next Unit of this Block). When you
write your programme in a programming language such as Servlet and JSP (this will
be covered in detail in Unit 2, 3 and Unit 4 of this Block), you will be using some
other terms like Web Server and Web Container in addition to HTTP request and
response. This section describes you about the Web Server and Web Container.
Web Server is a server software that handles HTTP requests and responses to deliver
web pages or web content to clients (i.e. web browser) using HTTP protocol. Web
browser communicates with web server using the Hypertext Transfer Protocol
(HTTP). Hypertext Transfer Protocol (HTTP) is specially meant to communicate
between Client and Server using Web (or Internet). To successfully execute web
application, the number of server side technologies (such as JSP, Servlets and PHP)
and their libraries are installed on the web server. Without these libraries, a web server
cannot execute those server technologies based applications. In other words, we may
say that the web server creates an execution infrastructure for the server technologies.
An example of web server is Apache HTTP Server.
Web Container is a web server component that handles Servlets, Java Server Pages
(JSP) files, and other Web-tier components. Web container is also called a Servlet
Container or Servlet Engine. It is the responsibility of the Web container to map a
URL to a particular servlet. Also, Web container ensures that the mapped URL
requester has the correct access rights. It means that it provides the run time
environment to web applications. The most common web containers are Glassfish,
Eclipse, JBOSS, Apache Tomcat, WebSphere and Web Logic.
For deployment and running the JSPs/Servlets we need a compatible web server with
a servlet container.
You can know more about the Java 2 Enterprise Edition (J2EE) and its uses in java
programming in the next section.

1.3 INTRODUCTION TO J2EE

In the previous section, you have learned about the two most important terms web
server and web container which are required for Java programming. Through this
section you know about the Java 2 Enterprise Edition (J2EE).
You are well aware about core java or Java Standard Edition (Java SE). Java SE
provides all core functionalities of java programming language. Java technology is
used as a programming language as well as a platform. A Java platform provides a
specific environment in which Java applications run. The Java Enterprise Edition
platform resides on top of the Java Standard Edition platform.
2
The J2EE platform is a set of services, application programming interfaces (APIs) and Web Application
Development using J2EE
protocols. J2EE is used to develop and deploy multi-tier web-based enterprise
applications using a series of protocols and application programming interfaces
(APIs). J2EE contains several APIs such as Java Servlets, Java Server Pages (JSP),
Enterprise Java Beans (EJB), Java Database Connectivity (JDBC), Java Message
Service (JMS), Java Naming and Directory Interface (JNDI) and so on.
The J2EE application model divides applications into three basic parts like
components, containers and connectors. The application developers works on the
components part, whereas system vendors are responsible for implementing
containers and connectors. Containers act as a mediator between clients and
components by providing services like transaction support and resource pooling.
Connectors provide bidirectional communication between J2EE components and
enterprise systems. Below in figure 1, you can depict the functioning of J2EE model:

Presentation Layer Business Layer Databas


e Layer

Client Web Business Persistence


L Logic Layer Layer

Web Java EE Container


Browser Web Container EJB Container JPA Persistence
Engine
Enterprise
Servlet Bean Relationa
Java
App.
l
Enterprise Database
Client JSP Page Entity
Bean
Client machine
App. Client
Controller

Figure 1: J2EE Architecture

A J2EE application contains four components or tiers: Presentation, Application,


Business, and Resource adapter components. The presentation component is the client
side component that is visible to the client and runs on the client’s server. The
Application component is web side layer that runs on the J2EE server. The business
component is the business layer which includes server-side business logic such as
JavaBeans, and it is also run on the J2EE server. The resource adaptor component
comprises an enterprise information system.
When you develop J2EE application, you may find J2EE clients such as a web client,
an application client, wireless clients or Java Web Start-enabled clients. For running
J2EE application, you need a J2EE container which is a server platform, Java
component can be run on this container using APIs provided through the Web
container and EJB container. The EJB container is a server platform used for
controlling the execution of Enterprise Bean. Also, the EJB container job is to provide
local and remote access to enterprise beans.
For creating complex applications, you can use J2EE frameworks like Struts, Spring
and Hibernate, which will you read in block-2 of this course.

3
Introduction to J2EE
Architecture and Design ☞ Check Your Progress 1
Pattern
1. What is a web server, and how does it differ from a web container? Also,
name any four web containers.

2. What is J2EE? What are the components of J2EE applications? What


technologies are included in the J2EE platform?

3. Define the term module in J2EE. What are the four specific modules used in
J2EE applications?

1.4 DESIGN PATTERNS

The previous section has given you an introductory lesson on the Java 2 Enterprise
Edition (J2EE). This section gives a detailed description of the Design Patterns and
their types and uses in Java.
Design patterns are the best solutions that are tested, verified developed prototypes
that can speed up your development process. When you may face problems during
software development, the design patterns gives you explanations for those problems.
Experienced developers have developed these explanations to provide the finest
solutions to the problems. It is also beneficial for un-experienced software developers
to learn software design in a simpler manner. The concept of design pattern has been
initiated by four authors collectively known as GOF (Gang of Four), and they have
published a book (Design Patterns - Elements of Reusable Object-Oriented Software)
on this concept. Design Patterns provides a general reusable solution to commonly
occurring problems. It is not a complete design that can be directly mapped into your

4
code and solve your purpose. It is just like a template or explanation for how to solve Web Application
Development using J2EE
your problems. It offers a common platform for all software developers.
There are 23 classic design patterns and they are categorized into three groups:
Creational, Structural and Behavioral. The Creational design patterns deal with the
creation of an object. Structural design patterns deal with the class structure, and the
behavioral design patterns define the interaction between objects.
Creational design patterns
The Creational design patterns provide a way to deal with the creation of an object
and define 5 design patterns such as Abstract Factory, Builder, Factory, Prototype and
Singleton pattern from which two like Singleton and Factory design pattern are to be
discussed below. The Abstract Factory design pattern allows to create families of
related objects. This pattern permits us to create a Factory for factory classes. The
Builder design pattern provides a valuable solution to many object creation problems
in object-oriented programming. The objective of this pattern is to separate the
creation of a complex object from its representation. The Prototype design pattern
allows us to produce new objects by cloning an existing object using
a clone() method. This pattern is useful when a particular resource is costly to create
or when the abstract factory pattern is not preferred.
Structural design patterns
The Structural design patterns are related to the creation of class and object structure.
These patterns define seven design patterns: Adapter, Bridge, Composite, Decorator,
Façade, flyweight, and Proxy. The Adapter design pattern provides a way to work as
a link between two unrelated interfaces. The object that links these incompatible or
unrelated interfaces is called an Adapter. So, the adapter design pattern permits the
interface of an existing class to be used as another interface. The adapter pattern is
generally used to make available the existing classes for others without changing their
source code. The objective of the Bridge design pattern is to decouple an
abstraction from its im plem entation so that the tw o can perform
independently. The bridge uses object oriented program m ing principles
such as encapsulation,aggregation and inheritance to separate duties into
different classes.This pattern is usefulw hen the class and its functionality
vary a lot.The Composite design pattern defines a pool of objects that are to be
treated as a single object. The Decorator design pattern is used to change the
functionality of an object at runtime. The Façade design pattern is used to generating
wrapper interfaces on top of existing interfaces, and it hides the complications of the
system and arranges a simpler interface to the client application. The Flyweight
design pattern moderates the cost of generating and controlling a large number of
related objects. The Proxy design pattern is used as a procurator or placeholder for
another object to regulate the access and reduce cost as well as reduce complexity.
Behavioral design patterns
The third design patterns category is Behavioral, which defines 11 design patterns:
Chain of responsibility, Command, Interpreter, Iterator, Mediator, Memento,
Observer, State, Strategy, Template Method, and Visitor. They are specifically
concerned with the interaction between objects. As the name recommends, the chain
of responsibility design pattern builds a chain of receiver objects for a request. This
pattern is used where the request sender is disassociated from its receiver based on the
type of request. The Command design pattern is used to create objects containing
information about an action, such as method name, owner of the method, and
Parameter values necessary to be produced later. As the name suggests, the
Interpreter design pattern provides an interpreter to deal with language grammar and
it is used to interpret sentences in a language. The Iterator design pattern provides a
way to access the collection object without revealing its underlying representation.

5
Introduction to J2EE
Architecture and Design
This pattern is frequently used in Java and .Net programming languages. Mediator
Pattern design pattern provides a communication medium or a mediator class that handles all
the communications between different classes. The capability of Memento design
pattern is used to restore an object to its earlier state. The Observer design pattern is
beneficial when an object is changed; then, you can get notified about the state of the
object through this pattern. The State design pattern permits an object to modify its
behaviour when its inner state is modified. The Strategy pattern or policy design
pattern allows selecting an algorithm during runtime. The Template Method design
pattern provides a way to create a superclass template method and permit its child
classes to provide concrete behaviour. The Visitor design pattern gives a way to
separate an operation from the object structure on which it operates. The basic
purpose of this pattern is to define a new operation without modifying the original
classes.
Besides these design patterns some more design patterns are also available. The MVC,
Repository, Singleton and Factory design patterns are discussed below:
1.4.1 MVC Design Pattern
Model View Controller (MVC) design pattern is an architectural pattern for web
applications. It can be used across many frameworks with many programming
languages such as Java, PHP, Python, Ruby, etc. This design pattern is extensively
used to design enterprise web applications and mobile applications. The MVC design
pattern comprises three layers such as data, presentation and control information. This
pattern requires each of these layers to act independently.
The MVC design pattern described three layers such as Model, View and Controller.
In MVC pattern, M (Model) denotes only the pure application data and does not
contain any logic for representing data to a user, whereas V (View) is responsible for
presenting data to the user. The C (Controller) comes between the view and the model
layer and it is responsible for accepting a request from the user, performs interactions
on the data model objects, and sends it back to the view layer.
The UML diagram of MVC design pattern is depicted in figure 2. The following
example demonstrates to you how MVC design pattern will work. The example
contains total of four java files, from which three java files for MVC layers and one
java file containing the main() method. For defining the MVC pattern, the first java
file is created as ‘UniversityModel’, which acts as a model, ‘univView’ as a view that
can display university details and ‘UnivController’ file is responsible for storing the
data in univ object and updateView() method updates the data in a ‘univView’ class
method. The ‘MVCExample’ file will use ‘UnivController’ file to illustrate the MVC
pattern.

Figure 2: UML class diagram of MVC design pattern is

6
Web Application
Development using J2EE
All files of MVC pattern example containing java source code are listed below.
1. You can create a UniversityModel.java file using the following code:
// UniversityModel.java
public class UniversityModel
{
private String name;
private String loc;

public String getName()


{return name; }

public void setName(String name)


{this.name = name; }

public String getLoc()


{return loc; }

public void setLoc(String loc)


{this.loc = loc; }
}

2. You can create a univView.java file using the following code:


// univView.java
public class univView
{
public void display(String univName, String univLoc)
{
System.out.println("University Details: ");
System.out.println("Name: " + univName);
System.out.println("Location: " + univLoc);
}
}

3. You can create a UnivController.java file using the following code:

// UnivController.java
public class UnivController
{
private UniversityModel model;
private univView view;

public UnivController(UniversityModel model, univView view)


{
this.model = model;
this.view = view;
}
public void setUnivName(String name)
{
model.setName(name);
}
public String getUnivName()
{
return model.getName();
7
Introoduction to J2E
EE
Archhitecture and Design
D
}
Patteern public void
v setUnivL
Loc(String locc)
{
mod del.setLoc(locc);
}
public String
S getLoc()
{
retuurn model.getLoc();
}
public void
v updateViiew()
{
vieww.display(moodel.getName(), model.getL
Loc());
}
}

4. Now, create
c a MVC
CExample.javaa file using thhe following code
c
//MVCExam mple.java
public class MVCExampple
{
public static void maain(String[] arrgs)
{
UniveersityModel m model = retriivedata();

//Creaate a view : too write studennt details on console


univV
View view = new n univView w();
UnivCController conntroller = new w UnivControoller(model, view);
v
controoller.updateVView();
}
private static UniverssityModel reetrivedata()
{
UniveersityModel uuniv = new UnniversityModdel();
univ.ssetName("IGN NOU");
univ.ssetLoc("Maiddan Garhi");
returnn univ;
}
}

5. Now, compile
c all thhe files using javac commaand and run MVCExample
M e file with
java as shown in figgure-3:

Figuree 2: Output Screeen for MVC paattern Examplee


8
Web Applicaation
1.4.22 Repository Design
n Pattern Developmen
nt using J2EE

In pllain words, repository meeans somethinng is deposited in storagee. The repository


mean ning is same as in terms of design patteern, it is relatted to the dataa. The repository
desiggn pattern is used in data--centric appliications. The Repository pattern
p is used to
isolaate the busineess logic layeer and the daata source layyers in your application. The
repossitory layer comes
c betweeen the domaiin and data m mapping layeers. As shownn in
figurre 4, the repository residess in the mid of
o the client bbusiness logicc and data souurce
layerr. At the data source layer, a database caan be kept/useed.

Figure 4: Block diagram


d for Repository
R Dessign Pattern
Supppose client buusiness logic wishes a qu uery from datta source then n it first goees to
repossitory layer thereafter
t rep
pository will send the queery to the daatabase, and tthen
t data to the business enntity. Similarlly, when client business loogic
repossitory maps the
base, data willl not directly go to the dataabase but willl go
wantts to save dataa in the datab
throu
ugh the reposiitory layer.
Whille using repository pattern
n, your appliccation’s businness logic layyer need not hhave

F
Figure 5: UML
L diagram forr Course Repoository

any knowledge
k on data persistence, it meaans the reposiitory layer prrovides a wayy to
hide the internall implementaation of how w data persisstence happens. This waay it
empo owers you to replace your data source without
w changging your bussiness logic. T
This
patteern is useful when
w you havve several en
ntities, and coomplex queriees are appliedd on
thosee entities.
This pattern is onne of the mostt popular Javva persistencee patterns. This pattern is uused
with JPA and other framework ks. A JPA (Jaava Persistencce API) is a java specificaation
and defined
d in javvax.persistennce package. JPA is used to access and d manage perrsist
data between Javva object andd relational database.
d JPA
A can act ass a link betw ween
objecct-oriented domain
d modeels and relaational databaase systems.. Various O ORM
(Object Relationaal Mapping) tools
t such as Hibernate, Sppring are used by the JPA A for
implementing dataa persistence..
Assuume that youu want to deevelop a couurse repository for a uniiversity databbase
appliication. For thhis, you needd persistent daata storage foor courses whhere you may add
and remove
r coursses and searchh for them. Fo or using repoository designn pattern, you can
creatte an interfacee that definess read and wrrite operations for a speciffic entity and this
9
Introoduction to J2E
EE
Archhitecture and Design
D
interface is implementedd by data stoore related classes. The UML
U diagram
m for such
Patteern repository iss as follows:
In the UML L diagram, youu have seen thhat there are ffour methods in ‘CourseReepository’
interface thaat you can usse to find a coourse by codee and name; save and deleete course
entity. You can create a course repossitory interfacce like the foollowing codee and then
write a classs for implem menting ‘Cou urseRepositorry’ interface. If you are using
u any
framework such as Sprinng Data JPA and Apache DeltaSpike Data D then youu can only
define the repository interfaces, and a these frrameworks canc generate standard
repository immplementatioons for you. Also,
A you cann write your own
o implemeentation as
per the requuirements of tthe implemenntation compllexity of yourr problem. Foor running
this pattern, you need database
d connnectivity withh J2EE framework. The repository
r
design patteern is strongeer to you whhen you will read J2EE frrameworks inn the next
Block-2 of this
t course.
public interrface CourseeRepository
{
Course getCourseByC
g Code(String code);
c
Course getCourseByN
g Name(String name);
n
Course saveCourse(C Course c);
void deleeteCourse(Coourse c);
}

1.4.3 Sin
ngleton Dessign Pattern
The singletoon pattern is a simplest sofftware design pattern amonngst the 23 weell-known
"Gang of Four"
F design patterns andd it comes uunder the creeational desiggn pattern
category, which
w deals wiith the creatioon of an object. As the namme suggests, Singleton
design patteern is used to create only one instance oof a class, andd all other classses of the
application can use thiss instance. Th his type of pattern
p is moostly used inn database
connection and multi-thhreaded appliications. Singgleton patterrn is used inn logging,
caching, thrread pools, configuration settings etc. You can usee Singleton pattern p in
other designn patterns likke Abstract Factory,
F Buillder, Facade, Prototype etc.,
e while
developing your own sollutions to a sppecific problem m.
The UML class diagram of Singleton pattern is as uunder:

Figuree 3: UML classs diagram of S


Singleton patttern

An implem mentation of this patternn must ensurre that only one instancce of the
singleton cllass will exisst and that innstance provides global acccess to otheers. While
implementin ng singletonn pattern, coonstructors oof the class must be deeclared as
private, andd method is defined
d as puublic static that returns thee instance of the class.
The instancce is typicallly stored as a private staatic variable. The static variable
v is
initialized at
a some point before the sttatic method iis first calledd.
Java core libbraries providde many classses which aree written usinng singleton pattern.
p A
few of them
m are listed below:

• Javaa.lang.Runtim
me with getRu
untime() methhod

10
Web Applicaation
• Java.awt.T
Toolkit with getDefaultTo
g oolkit()
Developmen
nt using J2EE
• Java.awt.D
Desktop with
h getDesktop()

A sample implem
mentation of Singleton
S design pattern inn Java is as fo
ollows:
publlic final classs Singleton
{
//A
A singleton cllass should haave public visibility
//sttatic instancee of class globbally accessibble
priivate static finnal Singletonn instance = new
n Singletonn();
priivate Singleto on()
{
/*
/ private connstructor, so that
t class can
nnot be instanntiated from outside
o this cclass
*/
}
pub blic static Sinngleton getIn
nstance()
{
/*declaration
/ of the methood as public static, so that instance can be used by
other
o classes */
return
r instancce;
}
}

The following exaample illustraates to you ho


ow the Singleeton design paattern works. For
this example,
e UM
ML class diagrram is as show wn in figure 77:

This Singleton Deesign Pattern example conntains two claasses. One is ‘SingletonClaass’,
whicch behaves ass Singleton cllass. This class have privaate constructo
or and providdes a
staticc method too get its staatic instance to other cllasses. The second classs is
‘SinggletonExamplle’, which use
u an instaance of the ‘SingletonCllass’ class. The
implementation off this example is underneaath.

11
Introoduction to J2E
EE
Archhitecture and Design
D
• First, yo
ou can createe a Singleton Class as the name of ‘SinngletonClass’ using the
Patteern followinng source codde:

// SingletonC Class.java
public class SingletonClaass
{
//create ann object of SinngletonClass
privvate static SinngletonClass instance
i = new
w SingletonC
Class();
privvate SingletonnClass(){}
pubblic static SinggletonClass getInstance()
g
{
retuurn instance;
}
pubblic void displlay()
{
System.out.println("Hello Stuudents in SOC CIS, IGNOU"");
}
}

• Create another
a class called ‘SinglletonExamplee’ to get the only instancee from the
singletoon class. The ccode of this class
c is listed below:
b
// SinglletonExamplee.java
public class SingletoonExample
{
pubblic static voidd main(String
g[] args)
{
//G
Get the instannce created byy Singleton cllass
SiingletonClasss instance = SingletonClas
S s.getInstance();
in
nstance.displaay(); //disp play data
}
}

• Now
w compile thee both classess and run the ‘SingleExam
mple’. The outtput of the
thiss example is ddisplayed in following figgure-8:

Figu
ure 4: Output Screen for Singleton examp
ple

1.4.4 Facctory Desiggn Pattern


In the prevvious sectionn, the Singleeton design pattern has been explaiined. The
Singleton deesign pattern belongs to thhe Creationall pattern categgory. As you know, the

12
creattional pattern is related to the creation of
o the object. In this sectio
on, you will leearn Web Applicaation
Developmen
nt using J2EE
one more
m design pattern
p namedd Factory, whhich also com
mes in the sam me category.
A Faactory Design n Pattern or Factory
F Methhod Pattern iss one of the most
m used design
patteern in java. Itt is a creationnal design paattern which deals with thhe creation of an
objecct. As per thee GOF, this pattern
p defines an interfacee or abstract class
c for creaating
an ob bject, but subbclasses are responsible forf creating tthe instance of o the class. The
advaantage of Facctory Pattern is that it alloows the sub-cclasses to chhoose the typee of
objeccts to create. In other words, this patterrn is used to create an objject where obbject
creattion logic is hidden
h to thee client and refers
r to the newly createed object usinng a
comm mon interfacee. This designn pattern is alsso known as ‘‘Virtual Consstructor’.
To immplement thee Factory Dessign Pattern, first,
f you defiine a factory method
m insidee an
interface or abstrract class and bclass use thhe above facttory method and
d let the sub
decidde which objeect to create.
Facttory Design Pattern
P impleementation

The following exxample demo


onstrates to you
y how to w
work Factoryy Design Patttern.
Assuume that IGN
NOU wants to send annouuncement dettails of new courses to users
u

Fig
gure 5: UML diagram for Factory
F Design
n Pattern

throuugh Facebookk, Email and SMS.


S Let’s immplement thiss example with the help off the
Factoory design paattern. For implementing
i g this, first, yyou can design a UML class
c
diagrram, and thhen you cann transform this class diagram in nto source ccode
implementation. UML
U class diagram for thiis example ussing the Facto
ory design patttern
is sho
own in figuree 9.
For implementinng the abov ve class diag gram, you can create an interfacee as
Anno ouncement annd three conncrete classess such as Faacebook.java,, Email.java and
SMS S.java. These three classees can impleement ‘Annouuncement’ innterface. Besides
thesee, you can also
a create two
t more cllasses. Youu can create a factory class
c
‘AnnnouncementFaactory.java’ to get ann Announceement objecct. Creation of
‘AnnnouncementIGGNOU.java’ class is to useu factory cclass and gett an object ofo a
concrete class.

13
Introduction to J2EE
Architecture and Design
Now you can follow the steps for the creation and running the example of Factory
Pattern design pattern:
• First, you can create Announcement interface.

public interface Announcement


{
void sendMSG();
}

• Now, you can create all three classes implementing the same interface as per the
following codes:

//Facebook.java
public class Facebook implements Announcement
{
public void sendMSG()
{
System.out.println("Sending announcement through Facebook");
}
}

//Email.java
public class Email implements Announcement
{
public void sendMSG()
{
System.out.println("Sending announcement as an e-mail");
}
}

//SMS.java
public class SMS implements Announcement
{
public void sendMSG()
{
System.out.println("Sending announcement as an SMS");
}
}

• Now, you can create a Factory Class ‘AnnouncementFactory.java’ as code listed


below:

// AnnouncementFactory.java
public class AnnouncementFactory
{
public Announcement createAnnouncement(String media)
{
if (media == null || media.isEmpty())
return null;
if ("Facebook".equals(media))
{
return new Facebook();
}
else if ("EMAIL".equals(media))
{
14
return new Email();
E Web Applicaation
Developmen
nt using J2EE
}
else
e if ("SMS".equals(meddia))
{
return new SMS();
}
return
r null;
}
}

• You
Y can creeate ‘Announ
ncementIGNO
OU.java’. Ussing this file, you can use
‘Announceme
‘ entFactory’ class to createe and get an oobject of conncrete class. Here
H
you
y are passinng some inforrmation as “F
Facebook”.
// Announcem mentIGNOU.jjava
public class Announcemen
A ntIGNOU
{
public static void main((String[] args))
{
Announ ncementFacto ory anFactoryy = new AnnoouncementFacctory()
Announ ncement annoouncement =
anFactoory.createAnnnouncement(""Facebook");
announcement.sendM MSG();
}
}
• Now, you caan compile alll the java filees and run ‘A
AnnouncemenntIGNOU’ as per
the following
g figure 10. This
T figure is also
a shown ouutput at the coommand prom
mpt.

Figure 6:
6 Compiling and
a output scrreen for Factoory pattern exxample

Up to now, you have


h learned about the dessign patterns,, including MVC,
M Reposittory,
Singleton and Facctory, and hoow to implemment these pattterns. In the next section,, we
will learn
l about th
he building an
nd deploymennt of java/J2E
EE applicationns

15
Introduction to J2EE
Architecture and Design ☞ Check Your Progress 2
Pattern
1. What do you mean by Design Patterns? Can you name some of the design
patterns used in JDK core libraries?

2. What is Singleton pattern? Name one singleton class in Java. How can you
create Singleton class in java? Can we create a clone of a singleton object? If
yes, then how to prevent cloning of a singleton object?

3. Explain the benefits of Factory pattern.

1.5 BUILDING JAVA APPLICATION JAR AND


WAR AND DEPLOYMENT IN TOMCAT

This section will help you to understand about building java applications to JAR and
WAR files and deployment in Tomcat. The following sections described to you how
to create WAR file, how to deploy WAR file and how to extract WAR file. You will
find more about the installation process of Apache’s Tomcat and running and
deployment of your Servlets and JSP programs in section 2.7 of Unit 2 of this Block-
1. Before an understanding of this description, you will know about the JAR and
WAR packaging in Java.
JAR Packaging
The JAR (Java Archive) is a package file format. The file extension of JAR files
is .jar and may contain libraries, resources, and metadata files. Basically, it is a zipped
file containing the compressed versions of .class files, compiled Java libraries and
applications. You can create a JAR file using the jar command like the following. You

16
can also
a create JA AR files usingg IDEs. You can
c learn morre about jar files in ‘Refereence Web Applicaation
Developmen
nt using J2EE
Sectiion’ of this Unit.
U

jar cf nam
me-jar-file inp
put-file(s)

Where c option iss used to creaate a JAR file, f option speecifies the outtputs which ggo to
a filee. You can deefine any fileename for a JAR
J file. Usinng the input--file(s) argumment,
you can
c specify a space-separaated list of onne or more filles that you wishes
w to incllude
in yo
our JAR file.

WA
AR Packagiing
WAR
R (Web Archive) is used too package weeb applicationns. You can deeploy on any
Servlet/JSP contaainer. It may contain
c JSP, Servlet, XML L, images, HTTML pages, CSS
C
files and other reesources.WAR R package co ombines all the
t files into a single uniit. It
takess a smaller amount
a of timme while traansferring file from cliennt to server. The
extennsion of WAR R files is .warr needs a servver to executee a WAR file..
The following
f secctions describbe to you how
w to create, depploy and extrract WAR filee.

Creeate WAR file


f
You can create war file using jar j tool of JD
DK or IDEs. YYou can use -c option of jaar to
creatte the war fille. For creatiing war file, you can go inside the prroject applicaation
direcctory (outside the WEB-IN NF folder), theen write comm
mand like the following:
jar -cvf prrojectname.w
war *

Where -c option is used to crreate file, -v to generate the verbose output and -f - to
speciify the archiv T * (asterissk) symbol indicates that all
ve file name. The a the files off this
direcctory (includinng sub directoory).
The following
f figuure-11 is dispplayed creatio
on process of WAR file:

Figure 7: Command
C proompt showing creation proccess of WAR file
f

ploy the WA
Dep AR file
You can deploy war
w file by placing the waar file in a sppecific folderr of the serveer. If

Figu
ure 7: UML cllass diagram for
f Singleton Design
D Pattern
n Example

17
Introoduction to J2E
EE
Archhitecture and Design
D
you are usiing the tomcat server andd want to deeploy this file manually, go to the
Patteern ‘webapps’ directory
d of aapache tomcaat and paste tthe war file. The
T server will
w extract
the war file internally. Now, you are able
a to access the web project through a browser.
• Supposse, you are ddeploying projject.war file. First go to tomcat
t webappps folder
and passte it.
• Go to tomcat->bin
t f
folder and starrt tomcat by cclicking startuup.bat file
• Now, you
y can accesss your appliication from tthe browser. Open the broowser and
write inn the address bar as localho
ost:port/projeectname eg. lo
ocalhost:80800/project
Extract war
w file man
nually
If you wish to extract thee war file man
nually, then you
y need to useu -x switch of jar tool
of JDK. Thee following coommand is ussed to extractt the war file.

jar -xvf
- projectnaame.war

The following figure-12 shows you ex


xtraction proccess of WAR file:

Figure 12: S
Screen showin
ng extraction process
p of WA
AR file

The figure-13 shows youu the file struucture after extraction


e of WAR file. Now,
N you
have learned about how to create, deeploy and exttract WAR fiiles. The nextt unit will
w to create serrvlet and deplloy in Tomcaat.
tell you how

Figure 13:: File structurre after extraction process of


o WAR file

18
Web Application
☞ Check Your Progress 3 Development using J2EE

1. What is the difference between JAR and WAR files?

2. Describe the process of creation, deployment and extraction of WAR files.

1.6 SUMMARY

This unit focussed on the J2EE, Architecture and Design Patterns. You have learned
about the J2EE and its architecture. By the services of Java 2 Enterprise Edition, you
can develop large scale, component based, distributed, multi-tier applications. J2EE
provides many APIs that can be used to build applications. This unit also covered 23
well-known design patterns which are categorized into three groups such as
Creational, Structural and Behavioral. The design pattern has given you prior
developed descriptions or template as solutions to commonly occurring problems in
programming language. Design patterns are the best solutions that are tested, verified
prototypes that can speed up your software development process. You have learned
about the MVC, Singleton, Factory and Repository design patterns with examples.
The MVC pattern described three layers such as Model, View and Controller. These
three layers have separate functions like Model represent data, View presents data to
user and Controller accepts the request from the user performs interactions on the data
model objects and send it back to the view layer. The repository design pattern is used
in data-centric applications. The repository design pattern provides a way to hide the
internal implementation of how data persistence happens, and it empowers you to
replace your data source without changing your business logic.
The singleton pattern deals with the creation of an object and is used to create only
one instance of a class and all other classes of the application can use this instance. A
Factory Design Pattern or Factory Method Pattern deals with creating an object and
defines an interface or abstract class for creating an object, but subclasses are
responsible for creating the instance of the class. At the end of this unit, you have
learned about how java application can be built as a war file and their deployment in
tomcat.

19
Introduction to J2EE
Architecture and Design
Pattern 1.7 SOLUTIONS/ANSWERS TO CHECK YOUR
PROGRESS
Check your Progress 1
1) Web Server is server software that handles HTTP requests and responses to
deliver web pages or web content to clients (i.e. web browser) using HTTP
protocol. Web server creates an execution infrastructure for the server
technologies. An example of web server is Apache HTTP Server. A compatible
web server with a servlet container is always necessary for deployment and
running the JSPs/Servlets.
Web Container is the web server component that handles Servlets, Java Server
Pages (JSP) files, and other Web-tier components. Web container is also called as
Servlet Container or Servlet Engine. It is the responsibility of Web container to
map a URL to a particular servlet and ensure that the URL requester has the
correct access rights. It means that it provides the run time environment to web
applications.
The most common web containers are Glassfish, Eclipse, JBOSS, Apache
Tomcat, Websphere and Web Logic.

2) J2EE is used to develop and deploy multi-tier web-based enterprise applications


using a series of protocols and application programming interfaces (APIs). J2EE
contains many APIs such Java Servlets, Java Server Pages (JSP), Enterprise
JavaBeans (EJB), Java Database Connectivity (JDBC), Java Message Service
(JMS), Java Naming and Directory Interface (JNDI) and so on. The J2EE
platform consist of set of services, application programming interfaces (APIs),
and protocols.
A J2EE application comprises four components or tiers such as Presentation,
Application, Business and Resource adapter components. The presentation
component is the client side component which is visible to the client and runs on
the client’s server. The Application component is a web side layer that runs on
the J2EE server. The business component is the business layer which includes
server-side business logic such as JavaBeans, and it also runs on the J2EE server.
The resource adaptor component includes enterprise information system.
J2EE contains several API technologies such Java Servlets, Java Server Pages
(JSP), Enterprise Java Beans (EJB), Java Database Connectivity (JDBC), Java
Message Service (JMS), Java Transaction API (JTA), Java Naming and
Directory Interface (JNDI), JDBC data access API and so on. The J2EE platform
is a set of services, application programming interfaces (APIs) and protocols.
3) A module in J2EE is a group of one or more components of the same container
type and one component deployment descriptor of the same type. There are four
different modules used in J2EE: application client module, web, EJB, and
resource adapter module. The Application Client module is bundled as a JAR file
which contains class files and client deployment descriptor (web.xml) file. The
WEB module is bundled as a JAR file that comprises class files (servlets), web
deployment descriptor file, JSP pages, images, and HTML files. The Enterprise
Java Beans (EJB) module is wrapped as a JAR file, collections of class files (ejb)
and EJB deployment descriptor. The fourth module is Resource Adapter which is
packaged as a JAR file consisting of classes, a resource adapter deployment
descriptor, Java interfaces and native libraries.

20
Web Application
Check your Progress 2 Development using J2EE
1) Design patterns are the best solutions that are tested, verified developed
prototypes that can speed up your development process. When you may face
problems during software development, the design patterns give you
explanations for those problems. Experienced developers have developed
these explanations to offer the finest solutions to the problems. It is also
beneficial for inexperienced software developers to learn software design in a
simpler manner.
The name of the design patterns used in JDK core libraries are Decorator
pattern (BufferedInputStream can decorate other streams such as
FilterInputStream), Singleton pattern (which is used by Runtime, Calendar
classes), Factory pattern (used by Wrapper class like Integer.valueOf) and
Observer pattern (used by event handling frameworks like swing).
2) The singleton pattern is a simplest software design pattern amongst the 23
well-known "Gang of Four" design patterns. It comes under the creational
design pattern category which deals with the creation of an object. Singleton
design pattern is used to create only one instance of a class and all other
classes of the application can use this instance. This type of pattern is mostly
used in database connection and multi-threaded applications.
The name of singleton class in JDK is java.lang.Runtime. The implementation
of Singleton design pattern is as under:

public final class Singleton


{
//A singleton class should have public visibility
//static instance of class globally accessible
private static final Singleton instance = new Singleton();
private Singleton()
{
/* private constructor, so that class cannot be instantiated from outside
this class */
}
public static Singleton getInstance()
{
/*declaration of method as public static, so that instance can be used
by other classes */
return instance;
}
}

You can create a clone of a singleton object. Java provide clone() method of
Object class for cloning. This method is protected method. In java, by default,
every class extends Object class, the object of any class, including Singleton
class can call clone() method. If you want to create a clone of a singleton
object, then class must be implemented by java.lang.Cloneable interface.
You can use throw exception within the body of clone() method to prevent
cloning of a singleton object.
3) A Factory Design Pattern or Factory Method Pattern is mostly used design
pattern in java. It is a creational design pattern which deals with the creation
of an object. As per the GOF, this pattern defines an interface or abstract class
for creating an object, but subclasses are responsible for creating the class's
instance. In other words, this pattern is used to create objects where object
creation logic is hidden to the client and refers to newly created objects using
21
Introduction to J2EE
Architecture and Design
a common interface. This design pattern is also known as ‘Virtual
Pattern Constructor’. The advantage of Factory Pattern is that it allows the sub-
classes to choose the type of objects they create.

Check Your Progress 3


1) The JAR (Java Archive) is a package file format. The file extension of JAR
files is .jar and may contain libraries, resources and metadata files. Basically,
it is a zipped file containing the compressed versions of .class files, compiled
Java libraries and applications. WAR (Web Archive) is used to package web
applications. You can deploy any Servlet/JSP container. It may contain JSP,
Servlet, XML, images, HTML pages, CSS files and other resources. It
combines all the files into a single unit and takes a smaller amount of time
while transferring file from client to server. The extension of WAR files is
.war and needs a server to execute a WAR file.
2) You can create war file using jar tool of JDK. You can use -c switch of jar to
create the war file. For creating war file, you can go inside the project
application directory (outside the WEB-INF folder) then write command as
jar -cvf projectname.war * on the command prompt. For the deployment of
WAR file, you can place war file in specific folder of server. If you are using
the tomcat server and want to deploy the war file manually, go to the
‘webapps’ directory of apache tomcat and paste the war file. The server will
extract the war file internally. Now, you are able to access the web project
through the browser. If you wish to extract the war file manually then you
need to use -x switch of jar tool of JDK.

1.8 REFERENCES/FURTHER READING

• Kathy Sierra, Bryan Basham, anddd Bert Bates ,“Head First Servlets and
JSP”, O'Reilly Media, Inc., 2008.
• Budi Kurniawan , “Java for the Web with Servlets, JSP, and EJB: A
Developer's Guide to J2EE Solutions: A Developer's Guide to Scalable
Solutions” ,Techmedia , 2002.
• https://www.oracle.com/java/technologies/appmodel.html
• https://docs.oracle.com/javase/8/docs/technotes/guides/javaws/
• https://docs.oracle.com/cd/B10018_07/migrate.902/a95110/overview.htm
• Design Patterns: Elements of Reusable Object-Oriented Software – Erich
Gamma, Richard Helm, Ralph Johnson, and John Vlissides.
• https://docs.oracle.com/javase/tutorial/deployment/jar/build.html
• https://introcs.cs.princeton.edu/java/85application/jar/jar.html

22

You might also like