Transcript t13
Introduction to J2EE
CS 236700: Software Design
Winter 2004-2005/T13
Based on: Advanced Web Applications Development, cs236606
© Eliezer Dekel, Sara Porat, Michael Factor, Gal Shachor: IBM Labs in Haifa
© Tal Cohen: The Computer Science Department, the Technion
1
Preface
A huge scope
Complex terminology
Our goals:
An overview of J2EE, J2EE services
Understanding the EJB framework
Deployment is a significant issue
Will not be discussed
2
Introduction (1/4): Enterprise Application
Enterprise Application
Running the information and activity of big organizations
Government agencies, Banks, Retailers
Must support various demands
High-availability
Scalability
Backwards compatibility
Multiple clients from remote sites
Consistent data
Security
Usually, designed around a client-server architecture
A stand-alone design cannot support remote access
A peer-to-peer design has security flaws and is more difficult to
program
• A “leader” usually simplifies any distributed algorithm
3
Introduction (2/4): A Three-tier application
Typical design of an Enterprise application:
First Tier
Client
Second Tier
Server
Third Tier
Database
This is a Three-tier application
Quite similar the Model-View-Controller pattern
The key difference: the brains of the system is located inside the 2nd tier
Usually called: Business Logic
Many times the client is just web-browser
4
Introduction (3/4): Application Server
The Business Logic layer (2nd tier)
Is usually the most complicated tier to design
The other two tiers are complex, but their design is almost
mechanical
Typically called: Application Server
It servers as a platform which invokes different applications
The platform provides core services to these applications
Concurrency,
Networking,
Transactions
Naming
Security
HTTP Connectivity
etc.
5
Introduction (4/4): The Motivation
Let a developer focus on the
domain-specific programming. The
general concerns are handles by
the underlying platform
This goal has motivated the development of many
Application Server products
J2EE is a standard (by sun) for an application server
Has several implementations: JBoss, Web-Sphere, WebLogic
Note that an application server addresses the same
needs as an operating system
6
J2EE in Action: Banking System
First Tier
Browser
HTTP
Second Tier
Third Tier
Account
Deposit
Servlet
RMI
RMI
Accounts EJB
Employees EJB
JDBC
Database
JDBC
J2EE Server
The applications: Account EJB, Employees EJB, Account Deposit Servlet
The J2EE server provide many useful services (as mentioned before)
The applications need to invoke these services…
…But not to implement them
7
The J2EE internal architecture
Three basic types of applications
JSP – Java Server Page
Servlets
EJB – Enterprise Java Beans
Containers: Each manages a certain type of application
EJB Container
Servlet Container (handles JSPs as well)
Fundamental technologies used by J2EE:
Reflection, Dynamic Compilation, Serialization, RMI
8
JSP (1/2)
Purpose: A simplified way to generate dynamic web
content
What is it?
An HTML page with embedded tags and Java Code
At runtime the JSP page is translated into an HTML page
The process:
A JSP page is dynamically converted into a Java code that is
compiled by the J2EE server
When a user request arrives, it is passed to an instance of this
class, which creates the desired textual output (HTML)
9
JSP (2/2)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN">
<HTML>
<HEAD>
<%@ page language="java" contentType="text/html;
charset=US-ASCII" pageEncoding="US-ASCII" %>
<TITLE>What’s the time</TITLE></HEAD>
<BODY><h2>
<P> Welcome to what-is-the-time.com<br><br>
<% String s = new java.util.Date().toString();
out.print("Current time=" + s); %>
</P></BODY></HTML>
Special variables:
d1/time.jsp
out – A JspWriter object
session – An HttpSession object of current user session.
request – An HttpServletRequest object associated with
current user request
response – An HttpServletResponse object
10
Servlets (1/2)
Purpose: A standard way for a Java program to handle
HTTP requests
What is it?
A Servlet is a Java class that extends HttpServlet
When the client sends a request to the server, it is forwarded to
an instance of the appropriate servlet class
11
Servlets (2/2)
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
doGet(req, resp);
}
public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><body><h2>");
out.println("Your Name is " + req.getParameter("name"));
out.println("</body></html>");
}
}
d1/MyServlet.html
12
EJBs
Purpose: Provide the means for encapsulation and
reuse of business logic and/or persistent data
What is it?
The EJB mechanism is a realization of the component model
A reusable software unit (like a class), which is dynamically
manipulated by the J2EE server
Why is it needed?
Many times the same business logic is used by several distinct
elements in the J2EE. For instance:
In a banking system, both the withdraw-servlet and the
deposit-servlet need to use the “set-balance” functionality
We are speaking of a distributed environment with persistent
data
=> it is not possible to invoke the setBalance() method on
an instance of the Account class
13
Types of EJBs
Session bean: Represents a single client
Relatively short lived
Does not represent shared data in a database
Does not generally survive EJB server crashes
Entity bean: Represent shared, persistent data
(The data is usually stored in a database)
Can be long lived
Survives EJB server crashes
14
The EJB mechanism (1/3)
Interaction: EJB container and an existing EJBs
Pooling: Reuse of idle EJBs
Sharing: Let two clients use a single EJB instance
Usually used with a stateless session EJB
Passivation/Activation: Save to file/reload from file
An idle EJB may become passive due to memory considerations
Etc.
EJBs are (of course) implemented as instances of classes
Option 1:
The J2EE standard will define a dedicated class, which implements
these methods
Each EJB class will have to extend this dedicated class
The flaw: In a single inheritance language, this approach rules-out the
possibility of inheritance between EJBs
Option 2:
Let the server “paste” the required methods into the EJB class
(See next slide)
15
The EJB mechanism (2/3)
API Interfaces
Remote
extends
Bean Developer
EJBObject
getEJBHome()
getHandle()
getPrimaryKey()
isIdentical(EJBOBject)
remove()
extends
Generated
“Remote interface”
Cart
addBook(String)
removeBook(String)
implements
“Bean class”
CartBean
setSessionContext(..)
ejbCreate(String)
ejbActivate()
ejbPassivate()
ejbRemove()
addBook(String)
removeBook(String)
delegates
“EJBObject implementation”
implementation”
“EJBObject
CartImpl
CalculatorImpl
addBook(String)
add(int,int)
removeBook(String)
sub(int,int)
getEJBHome()
getEJBHome()
getHandle()
getHandle()
getPrimaryKey()
getPrimaryKey()
isIdentical(EJBObject)
isIdentical(EJBObject)
remove()
remove()
16
The EJB mechanism (3/3)
Outline of steps
Programmer writes an interface for the business logic
Programmer writes a class which implements this interface
But it does not have to declare “implements X”
The EJB container creates a class which implements the interface
This class forwards the calls to the actual class
Additional code is inserted into this class
17
The EJB initialization mechanism (1/2)
Creation of a new EJB
Client code can’t just use new MyEjbClass() to create an EJB
Why?
1. The name of the actual implementation is not known
2. Many times the EJB container just recycles an existing instance
=> Outline of steps:
The programmer defines “initialization-methods” in his bean class
Named: ejbCreate(…)
The programmer defines the interface (called: Home Interface) for a
factory class
Parameters to methods must match the ejbCreate() methods
The EJB container creates a class which implements the Home
Interface
This class forwards the calls to the appropriate ejbCreate()
method
Additional code is inserted into this class
18
The EJB initialization mechanism (2/2)
API Interfaces
Remote
extends
Bean Developer
Generated
EJBHome
getEJBMetaData()
getHomeHandle()
remove(Handle)
remove(Object)
extends
“Bean class”
CartBean
setSessionContext(..)
ejbCreate(String)
ejbActivate()
ejbPassivate()
ejbRemove()
addBook(String)
removeBook(String)
“Home interface”
CartHome
create(String)
implements
delegates
“EJBHome implementation”
CartHomeImpl
create(String)
getEJBMetaData()
getHomeHandle()
remove(Handle)
remove(Object)
19
A Stateful Session EJB (1/4)
We’d like to model a “Shopping-cart” in an on-line book
store
The cart is represented by a stateful session bean
20
A Stateful Session EJB (2/4)
public interface Cart extends EJBObject
{
public void addBook(String title)
throws RemoteException;
public void removeBook(String title)
throws RemoteException;
public Vector getContents()
throws RemoteException;
}
Our business logic:
Add/remove book to cart
Observe the contents of the cart
21
A Stateful Session EJB (3/4)
import
import
import
import
java.io.Serializable;
java.rmi.RemoteException;
javax.ejb.CreateException;
javax.ejb.EJBHome;
public interface CartHome extends EJBHome
{
Cart create(String name) throws RemoteException;
Cart create(String name, String id)
throws RemoteException;
}
22
A Stateful Session EJB (4/4)
public class CartBean implements SessionBean
{
private String name_;
private String id_;
private Vector books_;
public void ejbCreate(String name) { ejbCreate(name, "0"); }
public void ejbCreate(String name, String id) {
name_ = name;
id_ = id;
books_ = new Vector();
}
public Vector getContents() { return books_; }
public void addBook(String title) { books_.addElement(title); }
public void removeBook(String title) {
books_.removeElement(title);
}
public CartBean() {}
public
public
public
public
void
void
void
void
ejbRemove() {}
ejbActivate() {}
ejbPassivate() {}
setSessionContext(SessionContext sc) {}
}
23
A simple EJB client
import
import
import
import
java.util.*;
javax.naming.Context;
javax.naming.InitialContext;
javax.rmi.PortableRemoteObject;
public class CartClient {
public static void main(String[] args) throws Throwable
{
Context initial = new InitialContext();
Object objref =
initial.lookup("java:comp/env/ejb/SimpleCart");
CartHome home = (CartHome)
PortableRemoteObject.narrow(objref, CartHome.class);
Cart shoppingCart = home.create(“Graham Chapman", "123");
shoppingCart.addBook("Last of the Mohicans");
}
}
Uses JNDI classes to locate the home interface
See: Object objref = initial.lookup("...");
24