1 introduction to j2ee cs 236700: software design winter 2004-2005/t13 based on: advanced web...

24
1 Introduction to Introduction to J2EE 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

Upload: aubrey-stokes

Post on 30-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

1

Introduction to J2EEIntroduction 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

Page 2: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

2

PrefacePreface

A huge scope

Complex terminology

Our goals:An overview of J2EE, J2EE servicesUnderstanding the EJB framework

Deployment is a significant issueWill not be discussed

Page 3: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

3

Introduction (1/4): Enterprise ApplicationIntroduction (1/4): Enterprise Application

Enterprise ApplicationRunning the information and activity of big organizations

Government agencies, Banks, RetailersMust support various demands

High-availabilityScalabilityBackwards compatibilityMultiple clients from remote sitesConsistent dataSecurity

Usually, designed around a client-server architecture A stand-alone design cannot support remote accessA peer-to-peer design has security flaws and is more difficult to

program • A “leader” usually simplifies any distributed algorithm

Page 4: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

4

Introduction (2/4): A Three-tier applicationIntroduction (2/4): A Three-tier application

Typical design of an Enterprise application:

Client DatabaseServer

First Tier Second Tier Third Tier

This is a Three-tier applicationQuite similar the Model-View-Controller patternThe key difference: the brains of the system is located inside the 2nd tier

Usually called: Business LogicMany times the client is just web-browser

Page 5: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

5

Introduction (3/4): Application ServerIntroduction (3/4): Application Server

The Business Logic layer (2nd tier) Is usually the most complicated tier to designThe 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.

Page 6: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

6

Introduction (4/4): The MotivationIntroduction (4/4): The Motivation

Let a developer focus on the domain-specific programming. The general concerns are handles by

the underlying platform

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 productsJ2EE is a standard (by sun) for an application serverHas several implementations: JBoss, Web-Sphere, WebLogic

Note that an application server addresses the same needs as an operating system

Page 7: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

7

J2EE in Action: Banking SystemJ2EE in Action: Banking System

Browser

Account Deposit Servlet

Accounts EJBDatabase

J2EE Server

HTTP

RMI

JDBC

First Tier Second Tier Third Tier

Employees EJB

RMI

JDBC

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

Page 8: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

8

The J2EE internal architectureThe 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

Page 9: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

9

JSP (1/2)JSP (1/2)

Purpose: A simplified way to generate dynamic web content

What is it?An HTML page with embedded tags and Java CodeAt 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 serverWhen a user request arrives, it is passed to an instance of this

class, which creates the desired textual output (HTML)

Page 10: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

10

Special variables:out – A JspWriter objectsession – An HttpSession object of current user session.request – An HttpServletRequest object associated with

current user requestresponse – An HttpServletResponse object

JSP (2/2)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>

<!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>

d1/time.jsp

Page 11: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

11

Servlets (1/2)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 HttpServletWhen the client sends a request to the server, it is forwarded to

an instance of the appropriate servlet class

Page 12: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

12

Servlets (2/2)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>"); }}

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

Page 13: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

13

EJBsEJBsPurpose: 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 modelA 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” functionalityWe 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

Page 14: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

14

Types of EJBsTypes 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

Page 15: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

15

The EJB mechanism (1/3)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)

Page 16: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

16

The EJB mechanism (2/3)The EJB mechanism (2/3)

“EJBObject implementation”CalculatorImpl add(int,int) sub(int,int) getEJBHome() getHandle() getPrimaryKey() isIdentical(EJBObject) remove()

EJBObject getEJBHome() getHandle() getPrimaryKey() isIdentical(EJBOBject) remove()

Remote

“Remote interface”Cart addBook(String) removeBook(String)

extends

implements

API InterfacesBean DeveloperGenerated

extends

delegates

“EJBObject implementation”CartImpl addBook(String) removeBook(String) getEJBHome() getHandle() getPrimaryKey() isIdentical(EJBObject) remove()

“Bean class”CartBean setSessionContext(..) ejbCreate(String) ejbActivate() ejbPassivate() ejbRemove() addBook(String) removeBook(String)

Page 17: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

17

The EJB mechanism (3/3)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

Page 18: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

18

The EJB initialization mechanism (1/2)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

Page 19: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

19

The EJB initialization mechanism (2/2)The EJB initialization mechanism (2/2)

EJBHome getEJBMetaData() getHomeHandle() remove(Handle) remove(Object)

“Bean class”CartBean setSessionContext(..) ejbCreate(String) ejbActivate() ejbPassivate() ejbRemove() addBook(String) removeBook(String)

Remote

“Home interface”CartHome create(String)

“EJBHome implementation”CartHomeImpl create(String) getEJBMetaData() getHomeHandle() remove(Handle) remove(Object)

extends

extends

implements

delegates

API Interfaces

Bean Developer

Generated

Page 20: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

20

A Stateful Session EJB (1/4)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

Page 21: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

21

A Stateful Session EJB (2/4)A Stateful Session EJB (2/4)

Our business logic: Add/remove book to cart Observe the contents of the cart

public interface Cart extends EJBObject { public void addBook(String title) throws RemoteException;

public void removeBook(String title) throws RemoteException;

public Vector getContents() throws RemoteException;}

public interface Cart extends EJBObject { public void addBook(String title) throws RemoteException;

public void removeBook(String title) throws RemoteException;

public Vector getContents() throws RemoteException;}

Page 22: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

22

A Stateful Session EJB (3/4)A Stateful Session EJB (3/4)

import java.io.Serializable;import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.ejb.EJBHome;

public interface CartHome extends EJBHome { Cart create(String name) throws RemoteException;

Cart create(String name, String id) throws RemoteException; }

import java.io.Serializable;import java.rmi.RemoteException;import javax.ejb.CreateException;import javax.ejb.EJBHome;

public interface CartHome extends EJBHome { Cart create(String name) throws RemoteException;

Cart create(String name, String id) throws RemoteException; }

Page 23: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

23

A Stateful Session EJB (4/4)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 void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {}}

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 void ejbRemove() {} public void ejbActivate() {} public void ejbPassivate() {} public void setSessionContext(SessionContext sc) {}}

Page 24: 1 Introduction to J2EE CS 236700: Software Design Winter 2004-2005/T13 Based on: Advanced Web Applications Development, cs236606 © Eliezer Dekel, Sara

24

A simple EJB clientA simple EJB client

import java.util.*;import javax.naming.Context;import javax.naming.InitialContext;import 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"); }}

import java.util.*;import javax.naming.Context;import javax.naming.InitialContext;import 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("...");