Ch04. JavaEE
Ch04. JavaEE
Chapter
4 Java EE
CHAPTER AUTHORS
Iryani Binte Mohd Nasril
Kaldybayev Ayan
Luc Francis Edouard Boissaye
Wen Zihe
Ch4: Java EE
2
Ch4: Java EE
CONTENTS
1 Introduction to Enterprise Systems ................................................................................................................ 4
1.1 Features of Enterprise System................................................................................................................. 4
1.2 Technologies ................................................................................................................................................... 5
2 Overview of Java EE ............................................................................................................................................... 5
2.1 Understanding Java EE................................................................................................................................ 6
2.2 Java EE6 Specifications ............................................................................................................................... 6
3 Creating an Application ........................................................................................................................................ 7
4 Data Layer .................................................................................................................................................................. 7
4.1 JPA Overview................................................................................................................................................... 7
4.2 Understanding Entities ............................................................................................................................... 8
4.3 Creating Entity Class .................................................................................................................................... 8
4.4 Entity Manager ............................................................................................................................................... 9
5 Logic Layer.............................................................................................................................................................. 10
5.1 EJB Overview................................................................................................................................................ 10
5.2 EJB Container ............................................................................................................................................... 10
5.3 Benefits of EJB ............................................................................................................................................. 11
5.4 Classifications of EJB ................................................................................................................................. 11
5.4.1 Session Beans ..................................................................................................................................... 12
5.4.2 Remote Business Interface ........................................................................................................... 14
5.4.3 Message Driven Beans .................................................................................................................... 15
5.4.4 Differences between the Beans................................................................................................... 16
5.5 Functionalities Provided by the Container ...................................................................................... 16
5.5.1 Security ................................................................................................................................................. 16
5.5.2 Transaction ......................................................................................................................................... 16
6 Creating the Interface......................................................................................................................................... 17
7 Conclusion............................................................................................................................................................... 22
8 Resources ................................................................................................................................................................ 22
9 References............................................................................................................................................................... 23
3
Ch4: Java EE
Enterprise Systems also allows for collaboration, communication and information gathering
- Essentials of Management Information (8th edition)
across the organization. An example of Enterprise Systems is an Enterprise Resource Planning
(ERP) system used in many large organizations.
Enterprise Systems requires a lot of infrastructure. The business logic is the main part of an
Enterprise System. It can be really complex. The main task you have as a developer is to
translate the business processes and workflow into code. If you want to be able to maintain and
split the code you need to create components that are able to work together.
4
Ch4: Java EE
well as the performance in order to track down the source of problems and then pinpoint and
fix the problems in the underlying layers.
Data Integrity
One of the primary design considerations for the Enterprise Systems is data integrity. Data
integrity means that data in the systems should not be lost or corrupted.
Interoperability
Interoperability is the ability of Enterprise System (or any general IT system) to use information
and functionality of another system. One of the examples will then be data exchange between
two systems. Interoperability is a key to building Enterprise Systems with mixed services. It
helps in achieving improved efficiency of the system operations. Hence, Enterprise Systems are
required to be interoperable so that they can collaborate with other systems.
1.2 Technologies
Two of the technologies commonly used for implementing enterprise systems are Java
Enterprise Edition (Java EE) and .NET.
Java EE, currently in version 6, is an extension to Java Standard Edition (Java SE). It provides
additional APIs which are not available in Java SE. The APIs are mainly for the development of
Java enterprise applications.
In addition, .NET is another common technologies that is used to create and Enterprise System.
However, in the remaining sections we will be focusing on Java EE rather than .NET and
illustrate how easy is it to create an ES using Java EE.
2 OVERVIEW OF JAVA EE
Java EE provides you an infrastructure to create and maintain Enterprise Systems. Some of the
services that Java EE provides are mentioned below:
JTA: Java Transaction API provides a standard interface for demarcating transactions. The Java
EE architecture provides a default auto commit to handle transactions commits and rollbacks.
JPA: Java Persistence API is a solution for persistence. Persistence uses an object/relational
mapping approach to bridge the gap between an object-oriented model and a relational
database. JPA can also be used as a query language.
Security Services: Java Authentication and Authorization Services (JAAS) enables services to
authenticate and enforce access controls upon users.
5
Ch4: Java EE
The diagram above depicts the main architecture of Java EE. Java EE itself is a huge topic. For
the next few sub-chapters, we will be touching on the main important components in Java EE,
mainly Entities and Enterprise Java Beans.
Java EE is a set of 28 specifications which provide common interfaces to use Java EE compliant
server.
6
Ch4: Java EE
3 CREATING AN APPLICATION
Throughout the rest of the section, we’ll be using a Library System that has been created as the
example.
Applications are made up of user interface, business logic, and data as shown below. Without
the interactions happening between them, no applications can be successfully built.
4 DATA LAYER
Database is important as it stores business data and act as a central point between applications.
Persistent data is everywhere, and most of the time it uses relational database as the underlying
persistence engine.
In Java, we manipulate objects as instances of classes. An object that can store its state to get
reused later is called persistent.
7
Ch4: Java EE
@Entity(name = “Book”)
public class BookEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long Id;
@column(nullable = false)
private String title;
private Float price;
@column(length = 2000)
private String description;
private String isbn;
private Integer nbOfPage;
private Boolean illustrations;
private int CopyNumber;
…….
}
8
Ch4: Java EE
<<entity>> Book
Book
ID bigint Nullable = false
-id: Long TITLE varchar(255) Nullable = false
-title: String Mapping
-price: Float PRICE double Nullable = false
-description: String DESCRIPTION varchar(255) Nullable = false
-isbn: String
-nbOfPages:Integers ISBN varchar(255) Nullable = false
-illustrations:Boolean NBOFPAGES integer Nullable = false
ILLUSTRATIONS smallint Nullable = false
The Entity Manager with Persistence Context keeps track of the changes done to the managed
entity instance. The method em.flush() is used to update the changes to database, em.close() is
used to close the PersistenceContext and EntityManager, em.find(Entity object) is used to find
the entity instance in database and em.remove(Entity Object) to remove entries in database.
9
Ch4: Java EE
The diagram shown below is the updated version with the data layer change as follows. JPA
allows us to do persistence and relationships easily.
5 LOGIC LAYER
Now that we have looked at the data layer, let’s move on to the logic layer. To create
functionalities for the logic layer, we used Enterprise Java Beans (EJB). EJB will be further
discussed in the next few sections.
beyond those available from the operating system. In Enterprise Java Bean technology, there is
one component called the EJB Container, which is responsible for managing Enterprise Java
Beans. The following list is some of the important service:
Security
Transaction management
Remote accessibility
Resource and life cycle management
Clustering and load-balancing
Concurrent requests support
EJB container also provides us the scalability and availability of Enterprise Beans:
Availability:
The Enterprise Java Bean Technology uses the internet protocol RMI-IIOP to allow interaction of
Enterprise Beans and its container. EJB container is in charge of creating, deleting, maintaining
the lifecycle of Beans and also the connection of Enterprise Beans and Client Object. Therefore
we say that EJB container provides us Availability.
Scalability:
If there is a sudden increase of the number of clients which uses the Beans, EJB container would
increase the number of Enterprise Beans in its Beans pool and decrease the number of Beans
when the number of client accessing to the system decrease. So we achieve the Scalability of our
server with the use of EJB container.
Message-Driven Bean
We will illustrate the two Enterprise Bean in the following sections.
12
Ch4: Java EE
@Stateful
public class ShoppingCartBean implements shoppingCartRemotes{
…….
public void addItem(Product item){
product.addElement(item);
}
…….
}
The Stateless Session Bean instances are indifferent and equivalent for all clients. Thus, the
Stateless Session Bean could be destroyed after method invocation or remained in the pools of
session bean which is maintained by EJB container. The pool of Stateless Session Bean is
maintained because we want to achieve high server performance as there are constant numbers
of client doing the same tasks simultaneously.
@Stateless
public class TheLirarySystemManagerBean implements TheLibrarySystemManagerRemote{
…….
}
The code fragment above is how we define a Stateless Session Bean; the @stateless annotation
indicates the java class is a Stateless Session bean.
13
Ch4: Java EE
@Stateless
public class TheLirarySystemManagerBean implements TheLibrarySystemManagerRemote{
@EJB
LoggingBean logging;
@PersistenceContext
EntityManager em;
@RolesAllowed(“admin”)
public boolean createBook(String isbn, String titleName, String author, String publisher, int
copyNumber) {
this.title = em.find(TitleEntity.class, isbn);
if(this.title == null) {
title = new TitleEntity();
title.create(isbn, titleName, author, publisher);
book = new BookEntity();
book.create(copyNumber, title);
title.addBook(book);
book.setTitle(title);
em.persist(title);
em.persist(book);
}else {
book = new BookEntity();
book.create(copyNumber, title);
title.addBook(book);
book.setTitle(title);
em.persist(book);
}
logging.log(“A book named “+title+” has been added.”);
return true;
}
The code above (which is defined in our Stateless Session Bean) could be used by the client
instance. The following code fragment is used to define an EntityManager that is used to persist
the entity instances to database.
@persistenceContext Entity Manager em ;
The rest of the code is the same as how we code a method in POJO (Plain Old Java Object).
14
Ch4: Java EE
@Remote
public interface TheLirarySystemManagerRemote {
public void createLibMember(String memberId, String name, String password, String
String department, String faculty, String phoneNum);
public boolean createBook(String isbn, String titleName, String author, String publisher,
int copyNumber);
public List<BookState> getBooks();
public List<BookState> getBooks(String memberId);
public boolean deleteBook(long bookId);
Figure 7: TheLibrarySystemManagerRemote.java
15
Ch4: Java EE
5.5.2 Transactions
By default Java EE is protecting your data integrity with a transaction mechanism. Basically, if
there is an error or an exception during the execution of one of your function, the container will
rollback all the modification made. What is really impressive is that it also works when you are
using remote Beans. The best example is a fund transfer system which interacts with two banks;
normally you think of it as a complex transaction system. If there is a problem with one of the
bank, you will have to cancel and rollback the whole transaction in both banks. Normally, huge
and complex codes are needed with the entire ‘if else’ block to check the system. However with
Java EE everything is automatic. You can still customize with some annotation the exact
behaviour of the transaction in order to improve performance or get your exact need.
The diagram shown below is the updated version with the logic later changed.
16
Ch4: Java EE
17
Ch4: Java EE
In the web application’s architecture (as shown in the Figure 9), we can clearly see how JSF fits
into it.
As we mentioned before, JSF provides easy development of web applications based on Java
technologies. Let us list some benefits of using JSF:
It provides standard, reusable components for creating UI for web applications.
It provides many tag libraries for accessing and manipulating the components.
It automatically saves the form data and repopulates the form when it is displayed at
client side.
JSF encapsulates the event handling and component rendering logic
JSF is a specification and vendors can develop the implementations for JSF.
There are many GUIs available these days to simplify the development of web based
application based on JSF framework.
18
Ch4: Java EE
First command takes a name from an input and puts it to the “bookname” property of managed
bean “bookControl”. Afterwards, they are synchronized together.
The last, but not the least part of JSF architecture is “Pages and Components”. When most of
the job is done the last thing that remains is to send the page to the client. For that JSF supports
display technology called Java Server Pages (JSP). JSP is the technology which aims to develop
dynamically generated web pages based on HTML or XML. JSP is the same as PHP, except that it
uses the Java language. All the HTML and Java codes are to put inside .jsp extension file and it
can be run to serve as dynamic web page. Java codes are to put inside “<%” and “%>” tags. In
our following example we will show you how JSP is used in Login Page in Figure 11.
19
Ch4: Java EE
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Library CS4217 - Member Login</title>
</head>
<body> <center>
<h1>The Library System</h1>
<% if (session.getAttribute("memberid") != null) {%>
<p>You have already logged in.</p>
<% } else {%>
<% if (request.getAttribute("loginFailed") != null) {%>
<p>Login Failed. Try again!</p><%}%>
<form action="MemberLogin" method="POST">
<table><tr> <td align="right">ID:</td>
<td align="left"><input type="text" name="id" size="20" /></td></tr>
<tr> <td align="right">Password:</td>
<td align="left"><input type="password" name="password" size="20" /></td>
</tr></table><br />
<input type="submit" value="Submit" />
</form>
<% }%>
</center></body></html>
This particular example of Login Page accepts login and password information on
corresponding fields and gives a result whether logging in was successful or failed.
With an explanation of Java Server Faces and Java Server Pages, we now introduce
programming language called “Servlet”.
Servlet is a small program that runs on a server. It is usually a Java applet that runs within a
Web server environment. Java servlets are becoming increasingly popular as an alternative to
Common Gateway Interface (CGI) programs. The biggest difference between the two is that a
Java applet is persistent. This means that once it is started, it stays in memory and can handle
multiple requests whereas a CGI program disappears once it has fulfilled a request. The
persistence of Java applets makes them faster because there's no wasted time in setting up and
tearing down the process.
20
Ch4: Java EE
init( ) – executes once when the servlet is first loads and will not be called for each
request
service( ) – for each request this method is called in a new thread by server. It is called
to process HTTP requests.
doGet( ), doPost( ), etc – those methods handles GET, POST and other requests done by
a user. These methods get dispatched by service( ) method.
destroy( ) – whenever server wants to delete servlet instance it calls this method.
Now we would like to show you a very simple program called “HelloWWWServlet.java” which
prints “Hello WWW” in the web page with all its standards.
package hall;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
In this code program first sets the content as “text/html” then prints “Hello WWW” as a title in
the web page. This is the way Servlets are used in modern database driven webservers.
21
Ch4: Java EE
So we have discovered what is the JSF technology, what is it used to, and what are the
components of it. We briefly discussed each of the components and its purpose in architecture.
Let us then look at the final application diagram.
7 CONCLUSION
As enterprise systems tend to become more and more complex, system designers must ensure
the scalability of the systems and how they communicate with each other. This task requires
more and more effort both in terms of business functionalities and regarding the technologies
chosen. Using Java EE will help companies to be able to create an Enterprise System easily and
effectively. Since Java EE is a very huge topic, we hope this small chapter will allow you to create
a small Enterprise System. We have covered the major steps which will help you and allows you
to look into the smaller details on your own.
8 RESOURCES
Amit Bahree, D. M. (2007). Pro WCF: Practical Microsoft SOA Implementation [Paperback].
Apress.
Chappell, D. (March, 2010). Introducing Windows Communication Foundation in .NET Framework
4. Retrieved 9 March, 2011, from http://msdn.microsoft.com/library/ee958158.aspx
Corporation, O. (n.d.). The Java EE 5 Tutorial. Retrieved 10 March, 2011, from
http://download.oracle.com/javaee/5/tutorial/doc/bnazq.html
22
Ch4: Java EE
Eichengreen, B. (May/June, 1999). One Economy, Ready or Not: Thomas Friedman's Jaunt
Through Globalization. Retrieved 6 March, 2011, from
http://www.foreignaffairs.com/articles/55017/barry-eichengreen/one-economy-
ready-or-not-thomas-friedman-s-jaunt-through-globaliz
Erl, T. (2007). SOA Principles of Service Design. Prentice Hall.
Goncalves, A. (2009). Beginning Java(TM) EE 6 with GlassFish(TM) 3: From Novice to
Professional. Apress, Inc.
Hewitt, E. (2009). Java SOA Cookbook. O’Reilly Media.
Jane Laudon, K. L. (2007). Essentials of Management Information Systems. Prentice Hall.
Judith Hurwitz, R. B. (2007). Service Oriented Architecture for Dummies. Wiley Publishing, Inc.
Kalin, M. (2009). Java Web Services: Up and Running. O'Reilly Media, Inc.
Klein, S. (2007). Professional WCF Programming: .NET Development with the Windows
Communication Foundation. John Wiley & Sons.
9 REFERENCES
[1] Corporation, Oracle. The Java EE 6Tutorial.
http://docs.oracle.com/javaee/6/tutorial/doc/.
23