j2ee - j ava 2 enterprise edition - uni potsdam

99
J2EE - Java 2 Enterprise Edition Version 1.4 Peter Tröger Hasso-Plattner-Institute, University of Potsdam 1

Upload: others

Post on 03-Feb-2022

2 views

Category:

Documents


0 download

TRANSCRIPT

J2EE - Java 2 Enterprise Edition

Version 1.4

Peter TrögerHasso-Plattner-Institute, University of Potsdam

1

Agenda• Partially based on Sun’s J2EE 1.4 Tutorial

• Available on java.sun.com (1500 pages)

• Multiple examples for Sun Application Server

• Other sources: Sang Shin, Introduction to J2EE; Spielman and Kunnumpurath, Pro J2EE 1.4

• Today: J2EE Overview, Web Tier

• Next Session: J2EE Business Tier

• Session after next: Future of J2EE (EJB 3, Spring)2

Enterprise Application Frameworks

• Presentation logic, business logic, data model and access logic, system services

• Single-Tier: Mainframe-based, dumb terminals, centralized model, monolithic application

• Two-Tier: Fat client talking to back-end database, standardized data access

• Three-Tier: Thin client for presentation, middle-tier server for system services, database tier, business logic and data model changeable

Three-Tier Model• RPC-based: Tight coupling of client and middle-tier (think

of implementation change)

• Object-based: business logic and data model encapsulated in objects (CORBA, RMI)

• Trend: web server - based three tier model

27

27

Three-Tier (Remote Object based)

? Business logic and data model captured in objects– Business logic and data model are now described

in “abstraction” (interface language)

? Object models used: CORBA, RMI, DCOM– Interface language in CORBA is IDL

– Interface language in RMI is Java interface

Database

SQL request

SQL responseObject response

Object request

Now the next evolution is remote object-based three tier model. The key difference of this model from the three tier RPC model is that now the business logic and data model are captured in objects, which means they can be expressed in the abstract terms.

For example, the most popular remote object model is CORBA and RMI. In the case of CORBA, the business logic is abstractly expressed in IDL (Interface Definition Language) while in the case of RMI, it is in the form of Java interface type.

05/15/2005

Problems to be solved

• (Distributed) transactions

• Remoting functionality

• Security (Authentication, Authorization)

• Persistency (object-relational gap, caching)

• Pooling (database connections, threads, objects)

• Scalability

• Legacy integration

J2EE Motivation• Component-based distributed applications for

the enterprise

• Consider security, speed, transactional and reliable behavior

• Avoid vendor-lock

• Fast application design and development

• “Write once, run everywhere”

6

Java 2 Platform• J2SE - Java 2 Standard Edition (desktop)

• J2ME - Java 2 Micro Edition (consumer device)

• J2EE - Java 2 Enterprise Edition (server)

11

11

The JavaTM Platform

OptionalPackages

Java 2Enterprise

Edition

(J2EE)

Java 2StandardEdition

(J2SE)

JVM

Java Card APIs

CardVM

OptionalPackages

Personal Basis Profile

Personal Profile

Foundation Profile

CDC

MIDP

CLDC

KVM

Java 2 Platform Micro Edition(J2METM)

* Under development in JCP

This is another picture that shows three flavors of Java technology. Java is being used at JavaCard at one end and at the supercomputer at the other end.

The key point in this picture is that the syntax and semantics of Java programming language is preserved regardless of which edition you use. And regardless where it is being used, it provides the secure, portable, and robust application development and deployment platform.

05/15/2005

J2EE Platform• First introduction in 1999, J2EE 1.4 approved by Java

Community Process in November 2003

• API compatibility for Enterprise Application Servers

• Standardized development and deployment of portable, distributed enterprise applications

• Multi-tier model for enterprise applications

• Standardized communication of application parts enables distributed applications

• Component-based development

• Re-usable discrete modules

• Portability through standards

• Integration of existing information systems

What Makes Up J2EE

• API and technology specification

• Development and deployment platform

• Reference implementation as part of the SDK

• Compatibility test suite

• J2EE brands, J2EE blueprints and best practises

• Sample codes

End-to-end Platform

72

72

The J2EE Platform Architecture

B2BApplications

B2CApplications

WebServices

WirelessApplications

Application ServerEnterprise

InformationSystems

ExistingApplications

This is somewhat simplified J2EE platform architecture. The key point in the picture is that regardless of who is the user of the service that is provided by the J2EE, that is, whether it is B2B application, or B2C application, or web services client, or J2ME based wireless devices, J2EE platform is the platform of choice for implementation because it provides highly scalable, highly available, highly reliable, and high performing implementation platform regardless of the fact that whether the services are exposed as web services or not.

05/15/2005

73

73

Client

Client

Client

Client

Client

ClientTier

Enterprise Information

TierMiddle

Tier

Enterprise Information

Systems (EIS):

RelationalDatabase,

Legacy Applications,

ERP Systems

Enterprise JavaBeans™

Enterprise JavaBeans

Other Services:JNDI, JMS,JavaMail™

J2EE

Application

Server

Web ServerJSP,

Servlets

Firewall

J2EE is End-to-End Solution

HTML/XML

I mentioned that J2EE is about building n-tier, web-based enterprise applications. That is, J2EE provides an end-to-end architecture covering from the client tier on the left side to the middle tier

where Web server and Application servers reside and enterprise information tier on right side which connects the middle tier systems to the backend enterprise information systems such as

relational databases, and legacy applications.

The clients can be either a full-blown Java applications or applet running inside a browser. Or more typically, the client could be a just regular HTML or XML browser communicating with the

web server through HTTP. Another form of client that is getting more pervasive in an enterprise environment is 3rd-party application which performs B2B transaction with your application

typically through XML. On the other side of the spectrum, the client could be wireless phones or cell phones with some kind of communication facilities. The clients could reside either behind the

firewall or within the firewall. The point here is that J2EE architecture accommodate these diverse

set of client types.

The middle tier typically contain web servers and application servers. In actual deployment, they could be running in a single physical platform or on multiple platforms. In some cases where

reliability and scalability are important, there could be multiple web servers and application servers. The web server receives HTTP requests from the clients and handle dynamic content

generation through either JSP or servlet or both. The JSP or servlet can then delegate any business logic processing to enterprise java beans running on the application server.

The key point here is that J2EE provides an end-to-end solution and deals with all these tiers with

open and standard technologies.

05/15/2005

J2EE Components• Self-contained functional software unit, written in Java

• Assembled into a J2EE application

• Communicates with other components

• Executed and managed by application server

• Client-side components: applications, applets

• Web components: Servlets, JavaServer Pages (JSP)

• Business components: Enterprise JavaBeans (EJB)

11

J2EE Modules• Contains of one or more J2EE components for the same

container type and one deployment descriptor

• Technically all JAR files, with own deployment descriptor

• EJB modules (.JAR) - EJB class files

• Web modules (.WAR) - Servlet class files, JSP files, class files, GIFs, HTML files

• Application client modules (.JAR) - class files

• Resource adapter modules (.RAR) - class files, native libraries, documentation; intended for JCA (EIS tier)

12

J2EE Containers• Management of components in containers

• Standardized runtime environment

• Interpose on all method calls

• Provide specific J2EE services, which can be expected by the component

• Enables platform-independent deployment

• Container settings as part of the assembled application (e.g. security, connectivity)

J2EE Containers10 OVERVIEW

Figure 1–5 J2EE Server and Containers

J2EE server

The runtime portion of a J2EE product. A J2EE server provides EJB and

web containers.

Enterprise JavaBeans (EJB) container

Manages the execution of enterprise beans for J2EE applications. Enterprise

beans and their container run on the J2EE server.

Web container

Manages the execution of JSP page and servlet components for J2EE appli-

cations. web components and their container run on the J2EE server.

Application client container

Manages the execution of application client components. Application clients

and their container run on the client.

Applet container

Manages the execution of applets. Consists of a web browser and Java Plug-

in running on the client together.

Web Services SupportWeb services are web-based enterprise applications that use open, XML-based

standards and transport protocols to exchange data with calling clients. The J2EE

14

Packaging• J2EE application is delivered as Enterprise

Archive File (EAR) - a JAR file with new extension

• Contains of J2EE modules and deployment descriptors

14 OVERVIEW

Figure 1–6 EAR File Structure

A J2EE module consists of one or more J2EE components for the same container

type and one component deployment descriptor of that type. An enterprise bean

module deployment descriptor, for example, declares transaction attributes and

security authorizations for an enterprise bean. A J2EE module without an appli-

cation deployment descriptor can be deployed as a stand-alone module. The four

types of J2EE modules are as follows:

• EJB modules, which contain class files for enterprise beans and an EJB

deployment descriptor. EJB modules are packaged as JAR files with a .jarextension.

• Web modules, which contain servlet class files, JSP files, supporting class

files, GIF and HTML files, and a web application deployment descriptor.

Web modules are packaged as JAR files with a .war (web archive) exten-

sion.

• Application client modules, which contain class files and an application

client deployment descriptor. Application client modules are packaged as

JAR files with a .jar extension.

• Resource adapter modules, which contain all Java interfaces, classes,

native libraries, and other documentation, along with the resource adapter

deployment descriptor. Together, these implement the Connector architec-

ture (see J2EE Connector Architecture, page 22) for a particular EIS.

Resource adapter modules are packaged as JAR files with an .rar(resource adapter archive) extension.

15

Deployment Descriptors

• XML document describing deployment setting

• J2EE deployment descriptor

• Defined by J2EE specification

• Own specification for each module type

• Runtime deployment descriptor

• J2EE implementation-specific settings

16

Responsibilities

77

77

ComponentsHandle

Containers and Components

! Concurrency

! Security

! Availability

! Scalability

! Persistence

! Transaction

! Life-cycle management

! Management

! Presentation

! Business Logic

ContainersHandle

We touched upon the roles of container and components a bit in the previous slide. Now let’s compare

the tasks that are being performed by containers and the ones performed by components side by side. As

we talked about in the previous slide, the platform vendors provide containers while you, as application

developers, develop your applications in the form of components and deploy them over the containers. As

you probably will notice, many of the tasks that the containers perform are system services that a typical

enterprise application would need.

First., container handles concurrency. That is, it handles concurrent access from multiple clients to your

business component so that you don’t have to deal with it. Each platform vendor might use different

synchronization schemes to support concurrency, however. Second, containers provide built-in security

framework so that implementing secure applications can be a matter of configuring some options on

authentication and access control at the time of deployment not at the time of code development. Next,

availability and scalability. We mentioned already that platform vendors compete in their

implementations especially in the area of availability and scalability. For example, one J2EE container

vendor might provide high availability by maintaining session state on a persistent storage. Another

vendor might choose to implement it in a different way.

Persistence and transaction can be also handled by the container if you choose to do so. Or you might

want to implement them on your own in your code, if more customized behavior is desired. Life-cycle

management. Containers handle the creation and destruction of your component instances according to

its own implementation scheme. Finally management and administration, some vendors might provide

better management tool for managing and administering various resources in the container.

So what do you have to do as developers? Very little really. You handle only presentation and focus

majority of your development effort on building business components.

05/15/2005

Application Settings• J2EE security model

• Restrict user access to system resources

• J2EE transactional model

• Specification of related methods as transactional unit

• JNDI lookup service

• Unified interface to naming and directory services

• J2EE remote connectivity model

• Management of client -> EJB method invocation

18

Container Settings

• EJB and service life cycles

• Database connection resource pooling

• Data persistence

• May be overriden by BMP entity beans

19

J2EE Role Model

• J2EE Product Provider

• Tool Provider

• Application Component Provider

• Enterprise Bean Developer, Web Component Developer, Application Client Developer, Application Assembler

• Application Deployer and Administrator

20

J2EE Products• Multiple compatible products:

Apache Geronimo 1.0, BEA WebLogic Server 9.0, IBM WebSphere AS 6.0, JBoss AS 4.0, Sun AS 8, Oracle AS 10g

• J2EE Compatibility Test Suite (CTS)

• Java Application Verification Kit (AVK) for the Enterprise

• J2EE reference implementation from Sun (source and binary)

J2EE 1.4 APIs

18 OVERVIEW

J2EE 1.4 APIsFigure 1–7 illustrates the availability of the J2EE 1.4 platform APIs in each J2EE

container type. The following sections give a brief summary of the technologies

required by the J2EE platform and the J2SE enterprise APIs that would be used

in J2EE applications.

Figure 1–7 J2EE Platform APIs

Enterprise JavaBeans TechnologyAn Enterprise JavaBeans™ (EJB™) component, or enterprise bean, is a body of

code having fields and methods to implement modules of business logic. You

can think of an enterprise bean as a building block that can be used alone or with

other enterprise beans to execute business logic on the J2EE server.

As mentioned earlier, there are three kinds of enterprise beans: session beans,

entity beans, and message-driven beans. Enterprise beans often interact with

databases. One of the benefits of entity beans is that you do not have to write any

SQL code or use the JDBC™ API (see JDBC API, page 22) directly to perform

22

J2EE APIs• Enterprise JavaBeans Technology (EJB)• Java Servlet Technology• JavaServer Pages Technology (JSP)• Java Message Service API (JMS)• Java Transaction API (JTA)• Java Mail API & SPI / Java Activation Framework (JAF)• Java API for XML Processing (JAXP)• Java API for XML-based RPC (JAX-RPC)• SOAP with Attachments API for Java (SAAJ)• Java API for XML Registries (JAXR)• J2EE Connector Architecture (JCA)• Java DataBase Connection (JDBC) API and SPI• Java Naming and Directory Interface (JNDI)• Java Authentication and Authorization Service (JASS)• Java Authorization Contract for Containers API (JACC)

J2EE Tiere ;-)

J2EE COMPONENTS 3

Figure 1–1 Multitiered Applications

J2EE ComponentsJ2EE applications are made up of components. A J2EE component is a self-con-

tained functional software unit that is assembled into a J2EE application with its

related classes and files and that communicates with other components. The

J2EE specification defines the following J2EE components:

• Application clients and applets are components that run on the client.

• Java Servlet and JavaServer Pages™ (JSP™) technology components are

web components that run on the server.

• Enterprise JavaBeans™ (EJB™) components (enterprise beans) are busi-

ness components that run on the server.

J2EE components are written in the Java programming language and are com-

piled in the same way as any program in the language. The difference between

J2EE components and “standard” Java classes is that J2EE components are

assembled into a J2EE application, are verified to be well formed and in compli-

ance with the J2EE specification, and are deployed to production, where they are

run and managed by the J2EE server.

24

Client Tier

• Web clients (“thin client”)

• Render web pages provided by web tier

• Pages may contain Java applets (embedded client application, running in the browser)

• Application clients (“rich client”)

• Direct connection to business tier (EJB)

25

Client Tier6 OVERVIEW

Figure 1–2 Server Communications

Web ComponentsJ2EE web components are either servlets or pages created using JSP technology

(JSP pages). Servlets are Java programming language classes that dynamically

process requests and construct responses. JSP pages are text-based documents

that execute as servlets but allow a more natural approach to creating static con-

tent.

Static HTML pages and applets are bundled with web components during appli-

cation assembly but are not considered web components by the J2EE specifica-

tion. Server-side utility classes can also be bundled with web components and,

like HTML pages, are not considered web components.

As shown in Figure 1–3, the web tier, like the client tier, might include a Java-

Beans component to manage the user input and send that input to enterprise

beans running in the business tier for processing.

Business ComponentsBusiness code, which is logic that solves or meets the needs of a particular busi-

ness domain such as banking, retail, or finance, is handled by enterprise beans

running in the business tier. Figure 1–4 shows how an enterprise bean receives

data from client programs, processes it (if necessary), and sends it to the enter-

26

Web Tier• Servlets: Java classes, which dynamically process

requests and construct responses

• JavaServer pages: Text-based documents, includes servlet snippets

• Static text data - HTML, WML, XML

• JSP elements for dynamic content

• Static HTML, applets, utility classes - bundled with J2EE application

27

Web TierBUSINESS COMPONENTS 7

prise information system tier for storage. An enterprise bean also retrieves data

from storage, processes it (if necessary), and sends it back to the client program.

Figure 1–3 Web Tier and J2EE Applications

Figure 1–4 Business and EIS Tiers

There are three kinds of enterprise beans: session beans, entity beans, and mes-

sage-driven beans. A session bean represents a transient conversation with a cli-

ent. When the client finishes executing, the session bean and its data are gone. In

contrast, an entity bean represents persistent data stored in one row of a database

table. If the client terminates or if the server shuts down, the underlying services

ensure that the entity bean data is saved. A message-driven bean combines fea-

28

Business Tier• Contains components with business code

• program logic which solves the need of a particular business domain functionality

• Business components are reflected as Enterprise JavaBean (EJB)

• Business logic as reusable component

• Different Bean types (Session, Entity, Message)

29

Business Tier

BUSINESS COMPONENTS 7

prise information system tier for storage. An enterprise bean also retrieves data

from storage, processes it (if necessary), and sends it back to the client program.

Figure 1–3 Web Tier and J2EE Applications

Figure 1–4 Business and EIS Tiers

There are three kinds of enterprise beans: session beans, entity beans, and mes-

sage-driven beans. A session bean represents a transient conversation with a cli-

ent. When the client finishes executing, the session bean and its data are gone. In

contrast, an entity bean represents persistent data stored in one row of a database

table. If the client terminates or if the server shuts down, the underlying services

ensure that the entity bean data is saved. A message-driven bean combines fea-

30

EIS Tier• Coupling with Enterprise Information Systems

• Enterprise resource planning (ERP) systems

• Mainframe transaction processing systems

• Database systems

• Other legacy information systems

• Integration of existing data and infrastructure

31

J2EE Application Anatomies

85

85

DB & EISResources

Browser

Stand-alone

Web Server EJB Server

Web Server EJB Server

Possible J2EE Application Anatomies

So this slide shows several different ways J2EE application can be built. Different forms of J2EE application can be built by combining the path between tiers.

One of the most common forms of J2EE application is represented in combined red arrows. In this form, browser talks to web tier in which servlet and and JSP components are created and deployed and these web tier components then talk to EJB tier in which EJB beans are created and deployed and these EJB beans in turn talk to backend databases or enterprise information systems.

Another common form is browser talks to web-tier and then the web-tier components talk to directly to backend databases or enterprise information systems. It is represented by red arrow between browser and web server and then dark brown arrow between web server and backend database.

It is also possible that the client could be standalone application, which can talk to directly to web-tier, EJB tier, or even directly to backend databases.

Also web tier components and EJB tier components can use components deployed in other web-tier or EJB tiers.

The point of this slide is to show that there are several different ways to build J2EE applications.

05/15/2005

J2EE Web Tier

84 GETTING STARTED WITH WEB APPLICATIONS

ally a web component generates a HTTPServletResponse object. The web

server converts this object to an HTTP response and returns it to the client.

Figure 3–1 Java Web Application Request Handling

Servlets are Java programming language classes that dynamically process

requests and construct responses. JSP pages are text-based documents that exe-

cute as servlets but allow a more natural approach to creating static content.

Although servlets and JSP pages can be used interchangeably, each has its own

strengths. Servlets are best suited for service-oriented applications (web service

endpoints are implemented as servlets) and the control functions of a presenta-

tion-oriented application, such as dispatching requests and handling nontextual

data. JSP pages are more appropriate for generating text-based markup such as

HTML, Scalable Vector Graphics (SVG), Wireless Markup Language (WML),

and XML.

Since the introduction of Java Servlet and JSP technology, additional Java tech-

nologies and frameworks for building interactive web applications have been

85

developed. These technologies and their relationships are illustrated in Figure 3–

2.

Figure 3–2 Java Web Application Technologies

Notice that Java Servlet technology is the foundation of all the web application

technologies, so you should familiarize yourself with the material in Chapter 11

even if you do not intend to write servlets. Each technology adds a level of

abstraction that makes web application prototyping and development faster and

the web applications themselves more maintainable, scalable, and robust.

Web components are supported by the services of a runtime platform called a

web container. A web container provides services such as request dispatching,

security, concurrency, and life-cycle management. It also gives web components

access to APIs such as naming, transactions, and email.

Certain aspects of web application behavior can be configured when the applica-

tion is installed, or deployed, to the web container. The configuration informa-

tion is maintained in a text file in XML format called a web application

deployment descriptor (DD). A DD must conform to the schema described in the

Java Servlet Specification.

Most web applications use the HTTP protocol, and support for HTTP is a major

aspect of web components. For a brief summary of HTTP protocol features see

Appendix C.

This chapter gives a brief overview of the activities involved in developing web

applications. First we summarize the web application life cycle. Then we

describe how to package and deploy very simple web applications on the Sun

Java System Application Server Platform Edition 8.1 2005Q1. We move on to

configuring web applications and discuss how to specify the most commonly

used configuration parameters. We then introduce an example—Duke’s Book-

Web Applications• Presentation-oriented web application

(JSP pages for generation of markup)

• Service-oriented web application(web service endpoints, usually as servlet)

• Web container as runtime platform (request dispatching, security, concurrency, life-cycle management, API for components)

• Life-cycle: code development, deployment descriptor development, compilation, packaging, deployment, usage

Web Modules90 GETTING STARTED WITH WEB APPLICATIONS

Figure 3–5 Web Module Structure

Packaging Web ModulesA web module must be packaged into a WAR in certain deployment scenarios

and whenever you want to distribute the web module. You package a web mod-

ule into a WAR using the Application Server deploytool utility, by executing

the jar command in a directory laid out in the format of a web module, or by

using the asant utility. This tutorial allows you to use use either the first or the

third approach. To build the hello1 application, follow these steps:

1. In a terminal window, go to <INSTALL>/j2eetutorial14/examples/web/hello1/.

2. Run asant build. This target will spawn any necessary compilations and

will copy files to the <INSTALL>/j2eetutorial14/examples/web/hello1/build/ directory.

• Web module as deployable unit

• .WAR file

• Portable format, described in Servlet specification

• Support for unpackaged modules

Java Servlets• Portable way for dynamic web content

• For any kind of request-response pattern, but HTTP-specific servlet classes (javax.servlet.http)

• Servlet life cycle: Instantiation through container, init method, service method, destroy method

• Possibility for event listeners in the WAR file (initialization, destruction, request, activation, passivation, invalidation)

• Concurrent access, synchronization in the code

Servlet vs. CGI

46

46

Servlet vs. CGI

CGI

Based

Webserver

CGI

Based

Webserver

Request CGI1Child for CGI1

CGI

Based

Webserver

Servlet Based Webserver

JVM

Request CGI1Child for CGI1

Request Servlet1

CGI

Based

Webserver

Servlet Based Webserver

JVM

Servlet1

Request CGI1Child for CGI1

Request CGI2

Request Servlet1

CGI

Based

Webserver

Child for CGI2

Servlet Based Webserver

JVM

Servlet1

Request CGI1Child for CGI1

Request CGI2

Request Servlet1

Request Servlet2

CGI

Based

Webserver

Child for CGI2

Servlet Based Webserver

JVM

Servlet1

Servlet2

Request CGI1Child for CGI1

Request CGI2

Request CGI1

Request Servlet1

Request Servlet2

CGI

Based

Webserver

Child for CGI2

Child for CGI1

Servlet Based Webserver

JVM

Servlet1

Servlet2

Request CGI1Child for CGI1

Request CGI2

Request CGI1

Request Servlet1

Request Servlet2

Request Servlet1

CGI

Based

Webserver

Child for CGI2

Child for CGI1

Servlet Based Webserver

JVM

Servlet1

Servlet2

Request CGI1Child for CGI1

This picture shows difference between CGI and servlet-based model. In CGI, for every HTTP request, a new process has to be created while in servlet model, it is the thread that gets created in the same Java VM (Virtual Machine) and that thread can stay there for serving other requests.

05/15/2005

Servlet Life Cycle• public void init() throws ServletException {}

• public void destroy() {}

• For GenericServlet, override public void service(ServletRequest, ServletResponse)

• For HttpServlet, override public void doGet(...) | doPost(...) | doPut(...) | doDelete(...)

• service() method as dispatcher

• Request object contains all relevant data (e.g. HttpServletRequest)

• Response object filled by servlet (e.g. HttpServletResponse)

Servlet Exampleimport java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException{ res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("Hello World");}}

Information Sharing

• Through private helper objects

• Through sharing of objects that are attributes of a public scope

• Through a database

• Through invocation of other web resources

• Synchronization is task of the developer

Exampleimport java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*;

public class HolisticCounter extends HttpServlet { static int classCount = 0; // shared by all instances int count = 0; // separate for each servlet static Hashtable instances = new Hashtable(); // also shared

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/plain"); PrintWriter out = res.getWriter(); count++; out.println("Since loading, this servlet instance has been accessed " + count + " times.");

instances.put(this, this); out.println("There are currently " + instances.size() + " instances."); classCount++; out.println("Across all instances, this servlet class has been " + "accessed " + classCount + " times."); }}

Client Sessions• Session is created automatically

• Timeout period definition (programmatically, deployment descriptor of WAR file)

• invalidate operation

public class CashierServlet extends HttpServlet {

public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Get the user's session and shopping cart HttpSession session = request.getSession(); ShoppingCart cart = (ShoppingCart)session.getAttribute("cart"); ... // Determine the total price of the user's books double total = cart.getTotal();

Scope Object Attributes

452 JAVA SERVLET TECHNOLOGY

Figure 11–1 shows the scoped attributes maintained by the Duke’s Bookstore

application.

Figure 11–1 Duke’s Bookstore Scoped Attributes

Controlling Concurrent Access to Shared ResourcesIn a multithreaded server, it is possible for shared resources to be accessed con-

currently. In addition to scope object attributes, shared resources include in-

memory data (such as instance or class variables) and external objects such as

files, database connections, and network connections. Concurrent access can

arise in several situations:

• Multiple web components accessing objects stored in the web context.

• Multiple web components accessing objects stored in a session.

• Multiple threads within a web component accessing instance variables. A

web container will typically create a thread to handle each request. If you

want to ensure that a servlet instance handles only one request at a time, a

servlet can implement the SingleThreadModel interface. If a servlet

implements this interface, you are guaranteed that no two threads will exe-

cute concurrently in the servlet’s service method. A web container can

Working with Filters

• Filters are web application components (like servlets), contained in the web archive

• Chained to the container’s processing pipeline, before request processing / after response sending

• Possibility to build up filter chains

• Add new / prototypical functionality through interception, apply adapter pattern

JavaServer Pages• Clear separation of presentation and business logic code

(HTML, XML vs. JavaBeans, own tags)

• Language for JSP pages, including access to server-side objects and custom tag libraries

• Support mixture of static and dynamic content

• Static data: HTML, SVG, WML, XML, ...

• JSP elements, expressed in ‘standard’ syntax (.jsp) or XML syntax (.jspx)

• In case, container translates JSP page to a servlet class and compiles the class

JSP Syntax

• JSP expression: <%= expression %>

• JSP Scriptlet: <% code %>

• JSP Declaration: <%! code %>

• JSP page directive: <%@ page att="val" %>

• Always XML equivalent defined<jsp:expression><jsp:directive.page att="val"\>

JSP Example<%@ page contentType="text/html; charset=UTF-8" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD><TITLE>Using JavaServer Pages</TITLE><BODY BGCOLOR="#FDF5E6" TEXT="#000000" LINK="#0000EE"><UL> <LI><B>Expression.</B><BR> Your hostname: <%= request.getRemoteHost() %>. <LI><B>Scriptlet.</B><BR> <% out.println("Attached GET data: " +request.getQueryString()); %> <LI><B>Declaration (plus expression).</B><BR> <%! private int accessCount = 0; %> Accesses to page since server reboot: <%= ++accessCount %>

<LI><B>Directive (plus expression).</B><BR> <%@ page import = "java.util.*" %> Current date: <%= new Date() %></UL></BODY></HTML>

Further JSP Features• HTTP request forwarding (jsp:forward)

• Use JavaBeans within the JSP page

<jsp:useBean id="test" class="hall.SimpleBean" /> <jsp:setProperty name="test" property="message" value="Hello WWW" /><jsp:getProperty name="test" property="message" />

• Scope attribute (PageContext (default), ServletRequest, HttpSession, ServletContext)

• Inclusion on compile / execution time

<%@ include file="url" %>

<jsp:include page="relative URL" />

Servlet-based Technologies

• JavaServer Pages Standard Tag Library (JSTL)

• Flow control, XML manipulation, internationalization, database access, ...

• JavaServer Faces

• API for UI representation and state handling

• Management of page navigation issues

• Realized as JSP tag library

• Works with ‘backing beans’, associated to a component

JSF Example<HTML> <HEAD> <title>Hello</title></HEAD> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <body bgcolor="white"> <f:view> <h:form id="helloForm" > <h2>Hi. My name is Duke. I'm thinking of a number from <h:outputText value="#{UserNumberBean.minimum}"/> to <h:outputText value="#{UserNumberBean.maximum}"/>. Can you guess it?</h2> <h:graphicImage id="waveImg" url="/wave.med.gif" /> <h:inputText id="userNo" value="#{UserNumberBean.userNumber}"> <f:validateLongRange minimum="#{UserNumberBean.minimum}" maximum="#{UserNumberBean.maximum}" /> </h:inputText> <h:commandButton id="submit" action="success" value="Submit" /> <h:message style="color: red” id="errors1" for="userNo"/> </h:form> </f:view> </HTML>

JSF and the Container

678 JAVASERVER FACES TECHNOLOGY

Figure 17–3 Duke’s Bookstore Application Objects

bookcatalog.jspDisplays a table containing all the books from the database and

allows the user to add a book to the shopping cart.

CashierBean The backing bean for the bookcashier.jsp page.

CatalogBean The backing bean for the bookcatalog.jsp page.

name componentA component represented by the name tag on the bookcash-ier.jsp page.

fanClub componentA component represented by the fanClub tag on the book-cashier.jsp page.

NameChanged value-

change listener

Handles the event of users entering their name in the name text

field rendered by the name tag on bookcashier.jsp.

ShoppingCartHolds the data for all the books that the user has added to the

shopping cart.

Table 17–3 JSP Pages and Objects of Duke’s Bookstore (Continued)

JSP Page or Server-

side Object Description

JSF Life CycleSTANDARD REQUEST PROCESSING LIFE CYCLE 683

Figure 17–4 JavaServer Faces Standard Request-Response Life Cycle

The life cycle handles both kinds of requests: initial requests and postbacks.

When a user makes an initial request for a page, he or she is requesting the page

for the first time. When a user executes a postback, he or she submits the form

contained on a page that was previously loaded into the browser as a result of

executing an initial request. When the life cycle handles an initial request, it only

executes the restore view and render response phases because there is no user

input or actions to process. Conversely, when the life cycle handles a postback, it

executes all of the phases.

Restore View PhaseWhen a request for a JavaServer Faces page is made, such as when a link or a

button is clicked, the JavaServer Faces implementation begins the restore view

phase.

During this phase, the JavaServer Faces implementation builds the view of the

page, wires event handlers and validators to components in the view, and saves

the view in the FacesContext instance. The FacesContext instance contains all

the information needed to process a single request. All the application’s compo-

nent tags, event handlers, converters, and validators have access to the Faces-Context instance.

Internationalization

• Tailoring of messages and labels

• Dispatcher servlet, JSP page in each language

• Isolate locale-sensitive data into resource bundles (Java property file)

• Date and number formatting

• Character encoding

Localization Example<application>

<locale-config><default-locale>en</default-locale><supported-locale>en</supported-locale><supported-locale>en_US</supported-locale><supported-locale>de</supported-locale>

</locale-config><message-bundle>

de.dcl.messageresource.MessageResources</message-bundle>

</application>---------------------------------------------------------------welcome=Welcome on this site.login={0} have been logged in on {1}.---------------------------------------------------------------<f:loadBundle basename="myPackage.MessageResources" var="msg"/><h:outputText value="#{msg.welcome}" /><h:outputFormat value="#{msg.login}">

<f:param value="Peter" /><f:param value="#{myBean.date}" />

</h:outputFormat>

Security in Web Applications

• HTTPS support is mandatory in J2EE-compliant web containers

• Security requirements: User identification and authentication, user account systems, authorization, audit logs, authentication schemes

• Declarative security (web.xml) vs. programmatic security (HttpServletRequest methods)

JAX-RPC• XML-based RPC API for building web services

• No need for generating or parsing SOAP data (proxy / stub generation)

• Service Endpoint Interface (SEI) in Java, only JAX-RPC types allowed

• since June 2002(before J2EE 1.4)

CREATING A SIMPLE WEB SERVICE AND CLIENT WITH JAX-RPC 321

Figure 8–1 illustrates how JAX-RPC technology manages communication

between a web service and client.

Figure 8–1 Communication Between a JAX-RPC Web Service and a Client

The starting point for developing a JAX-RPC web service is the service endpoint

interface. A service endpoint interface (SEI) is a Java interface that declares the

methods that a client can invoke on the service.

You use the SEI, the wscompile tool, and two configuration files to generate the

WSDL specification of the web service and the stubs that connect a web service

client to the JAX-RPC runtime. For reference documentation on wscompile, see

the Application Server man pages at http://docs.sun.com/db/doc/817-6092.

Together, the wscompile tool, the deploytool utility, and the Application Server

provide the Application Server’s implementation of JAX-RPC.

These are the basic steps for creating the web service and client:

1. Code the SEI and implementation class and interface configuration file.

2. Compile the SEI and implementation class.

3. Use wscompile to generate the files required to deploy the service.

4. Use deploytool to package the files into a WAR file.

5. Deploy the WAR file. The tie classes (which are used to communicate with

clients) are generated by the Application Server during deployment.

6. Code the client class and WSDL configuration file.

7. Use wscompile to generate and compile the stub files.

8. Compile the client class.

9. Run the client.

JAX-RPC Steps• Code and compile SEI, implementation classes and

interface configuration file

• Prepare package with wscompile and deploytool

• Deploy server application

• Code client classes and WSDL config file

• Use wscompile for stub files, compile and run the client application

JAX-RPC Types• Primitive types and the according classes

(boolean, byte, double, float, int, long, short)

• java.lang.String, java.math.BigDecimal, java.math.BigInteger, java.net.URI, java.util.Calendar, java.util.Date

• Arrays of supported JAX-RPC types

• Value types (members of JAX-RPC type)

• JavaBeans (properties of JAX-RPC type)

JAX-RPC Examplepackage helloservice; import java.rmi.Remote; import java.rmi.RemoteException; public interface HelloIF extends Remote { public String sayHello(String s) throws RemoteException; }

package helloservice; public class HelloImpl implements HelloIF { public String message ="Hello"; public String sayHello(String s) { return message + s; } }

JAX-RPC Interface Configuration File

<?xml version="1.0" encoding="UTF-8"?> <configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config"> <service name="MyHelloService" targetNamespace="urn:Foo" typeNamespace="urn:Foo" packageName="helloservice"> <interface name="helloservice.HelloIF"/> </service> </configuration>

wscompile -define -mapping build/mapping.xml -d build -nd build -classpath build config-interface.xml

JAX-RPC Packaging and Deployment

• Web service is implemented as servlet

• Deployment of web module (WAR file, web application deployment descriptor)

• Specific endpoint URI is defined on deployment time

• [URI]?wsdl is supported

Static Stub Client• Stub: local object that acts as a proxy for remote services

• Static Stub: Created at development time

• Needs only endpoint address at runtime

• Generation of stub classes with wscompile, based on WSDL configuration file

<configuration xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config"> <wsdl location="http://localhost:8080/hello-jaxrpc/hello?WSDL" packageName="staticstub"/> </configuration>

Static Stub Clientpackage staticstub; import javax.xml.rpc.Stub; public class HelloClient { private String endpointAddress; public static void main(String[] args) { try { Stub stub = (Stub)(new MyHelloService_Impl().getHelloIFPort()); stub._setProperty(javax.xml.rpc.Stub.ENDPOINT_ADDRESS_PROPERTY, args[0]); HelloIF hello = (HelloIF)stub; System.out.println(hello.sayHello("Duke!")); } catch (Exception ex) { ex.printStackTrace(); } } private static Stub createProxy() { return } }

Other Clients• Dynamic proxy client calls remote procedure through a

class that is created during runtime

• Dynamic invocation interface client can call the remote procedure with all information obtained at runtime (wscompile not needed)

• Application client is a J2EE application (EAR file), which locates the (local) service through JNDI

• JSP page can act as static stub client

• JAX-RPC allows advanced features (e.g. authentication)

Dynamic Proxy Clientpackage dynamicproxy; import java.net.URL; ... import dynamicproxy.HelloIF;

public class HelloClient { public static void main(String[] args) { try { String UrlString = args[0] + "?WSDL"; String nameSpaceUri = "urn:Foo"; String serviceName = "MyHelloService"; String portName = "HelloIFPort"; URL helloWsdlUrl = new URL(UrlString); ServiceFactory serviceFactory = ServiceFactory.newInstance(); Service helloService = serviceFactory.createService(helloWsdlUrl, new QName(nameSpaceUri, serviceName)); dynamicproxy.HelloIF myProxy = (dynamicproxy.HelloIF) helloService.getPort( new QName(nameSpaceUri, portName), dynamicproxy.HelloIF.class); System.out.println(myProxy.sayHello("Buzz")); } catch (Exception ex) { ex.printStackTrace(); }}}

DII Clientpackage dii; import javax.xml.rpc.Call; ...public class HelloClient { private static String qnameService = "MyHelloService"; private static String qnamePort = "HelloIF"; private static String BODY_NAMESPACE_VALUE = "urn:Foo"; private static String ENCODING_STYLE_PROPERTY = "javax.xml.rpc.encodingstyle.namespace.uri"; private static String NS_XSD = "http://www.w3.org/2001/XMLSchema"; private static String URI_ENCODING = "http://schemas.xmlsoap.org/soap/encoding/"; public static void main(String[] args) { try { ServiceFactory factory = ServiceFactory.newInstance(); Service service = factory.createService(new QName(qnameService)); QName port = new QName(qnamePort); Call call = service.createCall(port); call.setTargetEndpointAddress(args[0]); QName QNAME_TYPE_STRING = new QName(NS_XSD, "string"); call.setReturnType(QNAME_TYPE_STRING); call.setOperationName(new QName(BODY_NAMESPACE_VALUE,"sayHello")); call.addParameter("String_1", QNAME_TYPE_STRING, ParameterMode.IN); String[] params = { "Murph!" }; String result = (String)call.invoke(params); } catch (Exception ex) {ex.printStackTrace();}}}

Application Clientpackage appclient; import javax.xml.rpc.Stub; import javax.naming.*; public class HelloClient { private String endpointAddress; public static void main(String[] args) { try { Context ic = new InitialContext(); MyHelloService myHelloService = (MyHelloService) ic.lookup("java:comp/env/service/MyJAXRPCHello"); appclient.HelloIF helloPort = myHelloService.getHelloIFPort(); ((Stub)helloPort)._setProperty (Stub.ENDPOINT_ADDRESS_PROPERTY,args[0]); System.out.println(helloPort.sayHello("Jake!")); } catch (Exception ex) { ex.printStackTrace(); System.exit(1); }}}

JAX-RPC Summary

• J2EE clients should use stubs (loss of portability between JAX-RPC implementations)

• No service-specific exceptions with DII

• One-way communication only with DII

• J2ME supports only static stubs

• J2EE container manages service access (service.getPort())

Java API for XML Registries

• JAXR: Uniform API to XML registries for web services

• ebXML registry andrepository standard

• UDDI standard

400 JAVA API FOR XML REGISTRIES

Many methods in the JAXR API use a Collection object as an argument or a

returned value. Using a Collection object allows operations on several registry

objects at a time.

Figure 10–1 illustrates the architecture of JAXR. In the Application Server, a

JAXR client uses the capability level 0 interfaces of the JAXR API to access the

JAXR provider. The JAXR provider in turn accesses a registry. The Application

Server supplies a JAXR provider for UDDI registries.

Figure 10–1 JAXR Architecture

Implementing a JAXR ClientThis section describes the basic steps to follow in order to implement a JAXR

client that can perform queries and updates to a UDDI registry. A JAXR client is

a client program that can access registries using the JAXR API. This section cov-

ers the following topics:

• Establishing a Connection

• Querying a Registry

• Managing Registry Data

• Using Taxonomies in JAXR Clients

J2EE Business Tier

BUSINESS COMPONENTS 7

prise information system tier for storage. An enterprise bean also retrieves data

from storage, processes it (if necessary), and sends it back to the client program.

Figure 1–3 Web Tier and J2EE Applications

Figure 1–4 Business and EIS Tiers

There are three kinds of enterprise beans: session beans, entity beans, and mes-

sage-driven beans. A session bean represents a transient conversation with a cli-

ent. When the client finishes executing, the session bean and its data are gone. In

contrast, an entity bean represents persistent data stored in one row of a database

table. If the client terminates or if the server shuts down, the underlying services

ensure that the entity bean data is saved. A message-driven bean combines fea-

Enterprise Java Beans• Development and deployment of scalable,

transactional, server-side business logic components

• EJB container as runtime environment

• EJB client: servlet, application, other bean

• The ‘heart’ of J2EE

• EJB 2.1 specification,646 pages

J2EE COMPONENTS 3

Figure 1–1 Multitiered Applications

J2EE ComponentsJ2EE applications are made up of components. A J2EE component is a self-con-

tained functional software unit that is assembled into a J2EE application with its

related classes and files and that communicates with other components. The

J2EE specification defines the following J2EE components:

• Application clients and applets are components that run on the client.

• Java Servlet and JavaServer Pages™ (JSP™) technology components are

web components that run on the server.

• Enterprise JavaBeans™ (EJB™) components (enterprise beans) are busi-

ness components that run on the server.

J2EE components are written in the Java programming language and are com-

piled in the same way as any program in the language. The difference between

J2EE components and “standard” Java classes is that J2EE components are

assembled into a J2EE application, are verified to be well formed and in compli-

ance with the J2EE specification, and are deployed to production, where they are

run and managed by the J2EE server.

EJB as Java Component

• Every EJB is also a remote object (through RMI)

• Every EJB component is also a JavaBean component

• Introspectible properties with accessor methods

• EJBs run in a standardized runtime environment (container) and have a uniform deployment format

• Can rely on the existence of container services

J2EE & EJB

16

16

DB & EISResources

Browser

Stand-aloneApplication

Web Components EJBs

Web Components EJBs

EJB, EJB Server, EJB Client

Standalone EJB client talking to EJB server

web-tier EJB client talking to EJB server

EJB clients talking to EJB server

Now EJB clients are anything that invokes methods of EJB beans. EJB beans reside in EJB server. The EJB clients can be standalone applications or web-tier components. The EJB clients can be even other EJB beans.

06/01/2003

EJB Design Principles• EJB applications are loosely coupled

• Access to other components / services (from other vendors) through arbitrary names

• Can be authored without detailed knowledge of the environment

• Assembling to an application without code change

• EJB behavior is entirely specified by interfaces

• Increases portability and modularity

EJB Design Principles• EJB applications never manage resources

• Access to external resource through their container

• Efficient resource management (allocation, deallocation, sharing, pooling) by container

• Container configuration as administrative task, no programmatic interface

• Container provides system services: persistency, security, transactions, connection pooling, lifecycle management, threading

EJB Types• Session Bean

• Represents transient communication with client app

• When client is finished, session bean and data is gone

• Entity Bean

• Represents persistent data, one row of a database table

• When client is finished, data saving is ensured

• Message-driven Bean

• Java Message Service (JMS) listener component

• Session bean which reacts on asynchronous messages

76

Session Beans• Purpose: Performs a task for a client, similar to an

interactive session; hides business task complexity

• Only one client per session bean at the same time, session type is configured in the deployment descriptor

• Stateless Session Beans

• No conversational state, container can assign any instance to a client

• Stateful Session Beans

• Unique state information per client-bean session (conversational state)

Entity Beans• Represents business object in a persistent storage

(= row in a database table)

• Persistent, allow shared access, have primary keys, can participate in relationships with other entity beans

• Bean-managed persistence (BMP): State saving to database is implemented in the code

• Container-managed persistence (CMP): EJB container generates database calls (needs abstract schema), increases portability

• Abstract schema: part of deployment descriptor, specifies persistent fields and relationships

• Enterprise Java Beans Query Langauge

• Support for different multiplicity's and directions in relations

Message-Driven Beans

• Short-lived stateless JMS message listener component

• Messages can be send by any J2EE component

• Not intended to be directly used by clients or other components

• All instances of one message bean are equivalent

• Can be transaction-aware components

JMS• API for performing asynchronous messaging

• Client-oriented interfaces, interaction with message-oriented middleware (MOM), e.g. IBM MQ Series

• Roles: messaging clients, messaging destinations, and a JMS-compatible messaging provider

• Point-to-point or publish-subscribe pattern

• Support for filtering and transactional messaging

• Message types: TextMessage, BytesMessage, ObjectMessage, MapMessage, StreamMessage

EJB Interface Types• EJB must provide:

• Home interface (local / remote): Used by clients to create / find specific EJB types

• Client interface (local / remote): Business functionality provided to the client

• Implementation class(es)

• Message-driven beans need only implementation class

• Local clients run in the same JVM, no marshalling needed

Local Interface vs. Remote Interface

• Bean should either have local or remote interfaces

• Application clients usually work with remote interface

• Component distribution vs. access latency

• Tight or loosely coupling of related beans

• Container-managed entity bean relationship demands local access (and same JAR file)

• Remote interface of a stateless session bean can also provide a web service, instead of RMI

Client Interface• Remote client interface

• Extends javax.ejb.EJBObject, which in turn extends java.rmi.Remote

• Methods must throw RMIException

• Arguments and return values must be serializable

• Local client interface extends EJBLocalObject

import javax.ejb.EJBObject; import java.rmi.RemoteException; import java.math.*; public interface Converter extends EJBObject { public BigDecimal dollarToYen(BigDecimal dollars) throws RemoteException; public BigDecimal yenToEuro(BigDecimal yen) throws RemoteException; }

Home Interface• Client need a way to create an object reference

• Remote home interface extends EJBHome

• create(): Returns an object of the client interface type, multiple signatures supported

• Matching ejbCreate() object method for each create() in the home interface needed

import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBHome; public interface ConverterHome extends EJBHome { Converter create() throws RemoteException, CreateException; }

Implementation Class vs. Interfaces

• Container generates proxy classes for the implementation of the local / remote interfaces

• Business logic does NOT implement the local / remote interfaces, but one of the javax.ejb.EnterpriseBean derivations (SessionBean, EntityBean, or MessageDrivenBean)

• Ensures container-mediated client calls

• Binding of interfaces to implementation class through deployment descriptor

SessionBean Implementation Class• Implements SessionBean interface

• ejbCreate(): Initializes bean state

• ejbRemove(): Clean up of bean state

• ejbActivate(): Restore state information

• ejbPassivate(): Save state information

• setSessionContext(SessionContext): Retrieve context object from container (valid for whole bean lifetime)

• Optional notification about transaction boundaries by the container (SessionSynchronization interface)

Session Bean LifecycleTHE LIFE CYCLE OF A STATELESS SESSION BEAN 875

The Life Cycle of a Stateless Session BeanBecause a stateless session bean is never passivated, its life cycle has only two

stages: nonexistent and ready for the invocation of business methods. Figure 23–

5 illustrates the stages of a stateless session bean.

Figure 23–5 Life Cycle of a Stateless Session Bean

The Life Cycle of an Entity BeanFigure 23–6 shows the stages that an entity bean passes through during its life-

time. After the EJB container creates the instance, it calls the setEntityCon-text method of the entity bean class. The setEntityContext method passes the

entity context to the bean.

After instantiation, the entity bean moves to a pool of available instances. While

in the pooled stage, the instance is not associated with any particular EJB object

identity. All instances in the pool are identical. The EJB container assigns an

identity to an instance when moving it to the ready stage.

There are two paths from the pooled stage to the ready stage. On the first path,

the client invokes the create method, causing the EJB container to call the ejb-Create and ejbPostCreate methods. On the second path, the EJB container

874 ENTERPRISE BEANS

Figure 23–4 Life Cycle of a Stateful Session Bean

While in the ready stage, the EJB container may decide to deactivate, or passi-

vate, the bean by moving it from memory to secondary storage. (Typically, the

EJB container uses a least-recently-used algorithm to select a bean for passiva-

tion.) The EJB container invokes the bean’s ejbPassivate method immediately

before passivating it. If a client invokes a business method on the bean while it is

in the passive stage, the EJB container activates the bean, calls the bean’s ejbAc-tivate method, and then moves it to the ready stage.

At the end of the life cycle, the client invokes the remove method, and the EJB

container calls the bean’s ejbRemove method. The bean’s instance is ready for

garbage collection.

Your code controls the invocation of only two life-cycle methods: the createand remove methods in the client. All other methods in Figure 23–4 are invoked

by the EJB container. The ejbCreate method, for example, is inside the bean

class, allowing you to perform certain operations right after the bean is instanti-

ated. For example, you might wish to connect to a database in the ejbCreatemethod. See Chapter 31 for more information.

• Create / remove called by client

• Bean passivation / reactivation (in case) by container

Stateful Session Bean

Stateless Session Bean

EntityBean Implementation Class• Implements EntityBean interface

• ejbFindByPrimaryKey(): Finder method

• ejbPostCreate(): Called after according ejbCreate() and setup of the transaction context

• ejbLoad(): Load bean state from persistent storage

• ejbStore(): Save bean state to persistent storage

• [set|unset]EntityContext(EntityContext): Associate / disassociate bean identity context object

Entity Bean Lifecycle

• Client or container can cause state transition

• With BMP, ejbCreate / ejbActivate must set primary key field

• No association to EJB object identity in pooled state

876 ENTERPRISE BEANS

invokes the ejbActivate method. While an entity bean is in the ready stage, an

it’s business methods can be invoked.

There are also two paths from the ready stage to the pooled stage. First, a client

can invoke the remove method, which causes the EJB container to call the

ejbRemove method. Second, the EJB container can invoke the ejbPassivatemethod.

Figure 23–6 Life Cycle of an Entity Bean

At the end of the life cycle, the EJB container removes the instance from the pool

and invokes the unsetEntityContext method.

In the pooled state, an instance is not associated with any particular EJB object

identity. With bean-managed persistence, when the EJB container moves an

instance from the pooled state to the ready state, it does not automatically set the

primary key. Therefore, the ejbCreate and ejbActivate methods must assign a

MessageDrivenBean Implementation Class

• Implements MessageDrivenBean interface

• ejbCreate(): Single method, no argument

• setMessageDrivenContext(): Container stores identity context object

• ejbRemove(): Called before destruction

• Also implements javax.jms.MessageListener (onMessage() method)

Message-Driven Bean Lifecycle

• Non-existent or ready to receive messages

• Stateless implementation

THE LIFE CYCLE OF A MESSAGE-DRIVEN BEAN 877

value to the primary key. If the primary key is incorrect, the ejbLoad and ejb-Store methods cannot synchronize the instance variables with the database. In

the section The SavingsAccountBean Example (page 931), the ejbCreatemethod assigns the primary key from one of the input parameters. The ejbActi-vate method sets the primary key (id) as follows:

id = (String)context.getPrimaryKey();

In the pooled state, the values of the instance variables are not needed. You can

make these instance variables eligible for garbage collection by setting them to

null in the ejbPassivate method.

The Life Cycle of a Message-Driven BeanFigure 23–7 illustrates the stages in the life cycle of a message-driven bean.

The EJB container usually creates a pool of message-driven bean instances. For

each instance, the EJB container instantiates the bean and performs these tasks:

1. It calls the setMessageDrivenContext method to pass the context object

to the instance.

2. It calls the instance’s ejbCreate method.

Figure 23–7 Life Cycle of a Message-Driven Bean

Application Client• Create initial name context (JNDI name-to-object binding set)

• Obtain environment naming context of the application client

• Retrieve name-bound reference object from JNDI

• Narrow reference object to bean home interface

import java.math.*;Context initial = new InitialContext(); Context myEnv = (Context)initial.lookup("java:comp/env"); Object objref = myEnv.lookup("ejb/SimpleConverter"); ConverterHome home = (ConverterHome)PortableRemoteObject.narrow(objref, ConverterHome.class);Converter currencyConverter = home.create(); BigDecimal param = new BigDecimal ("100.00"); BigDecimal amount = currencyConverter.dollarToYen(param);

JNDI• Java Naming and Directory Interface

• Associate names and attributes with objects, provide way to access the objects by their name

• Binding: Association between a name and an object

• Context: Set of bindings, name can be bound to another subcontext (similar to FS directory structure)

• Entry point with javax.naming.InitialContext class

• Provider concept (LDAP, RMI registry, DNS, filesystem, NDS, NIS)

Web Client• Create initial name context (JNDI name-to-object binding set)

• Retrieve name-bound reference object from JNDI

• Narrow reference object to bean home interface

• Create instance through home interface and use it

<%@page import="javax.naming.*"%> <%@page import="javax.rmi.*"%><%@page import="org.example.*"%>...<%int op1 = Integer.parseInt(request.getParameter("op1"));int op2 = Integer.parseInt(request.getParameter("op2"));Context initial = new InitialContext(); Object objref = initial.lookup("AddBean"); AddRemoteHome home = (AddRemoteHome)PortableRemoteObject.narrow(objref, AddRemoteHome.class);AddRemote addB = home.create(); %>... <p>The addition result is <%= addB.add(op1,op2)%>

EJB Packaging

• Deployment descriptor (e.g. persistency type, transaction attributes)

• Enterprise bean classes

• Client (local / remote) and home interface

• Helper classes

872 ENTERPRISE BEANS

• Helper classes: Other classes needed by the enterprise bean class, such as

exception and utility classes.

You package the files in the preceding list into an EJB JAR file, the module that

stores the enterprise bean. An EJB JAR file is portable and can be used for differ-

ent applications. To assemble a J2EE application, you package one or more mod-

ules—such as EJB JAR files—into an EAR file, the archive file that holds the

application. When you deploy the EAR file that contains the bean’s EJB JAR

file, you also deploy the enterprise bean onto the Application Server. You can

also deploy an EJB JAR that is not contained in an EAR file.

Figure 23–3 Structure of an Enterprise Bean JAR

Naming Conventions for Enterprise Beans

Because enterprise beans are composed of multiple parts, it’s useful to follow a

naming convention for your applications. Table 23–2 summarizes the conven-

tions for the example beans in this tutorial.

EJB Naming Conventions

• EJB name: <name>Bean

• EJB class: <name>Bean

• Home interface: <name>Home

• Remote interface: <name>

• Local home interface: <name>LocalHome

• Local interface: <name>Local

More Container APIs• Java Transaction API (JTA)

• Descriptive vs. programmatic security

• EJB Timer Service

• XML document processing

• Java Management Extensions (JMX)

• J2EE Management Services

• EJBs with web service interface

Ende IEEE J2EE Courses

Ende

34 IEEE Special von Michael Glogl

Thank You

99