64
Java 2 Enterprise Edition Student Workbook

Java 2 Enterprise Edition - · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

  • Upload
    lykiet

  • View
    224

  • Download
    2

Embed Size (px)

Citation preview

Page 1: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 EnterpriseEdition

Student Workbook

Page 2: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Page ii Rev 2.1.2 © 2004 ITCourseware, LLC

Java 2 Enterprise Edition

Java 2 Enterprise EditionPublished by ITCourseware, LLC., 7245 South Havana Street, Suite 100, Centennial, CO 80112

Contributing Authors: Geof Dagley, Julie Johnson, Sihyung Park, Jamie Romero, Rob Roselius, RobSeitz, Rick Sussenbach, Todd Wright

Special thanks to: Many instructors whose ideas and careful review have contributed to the quality of thisworkbook, and the many students who have offered comments, suggestions, criticisms, and insights.

Copyright © 2003-2004 by ITCourseware, LLC. All rights reserved. No part of this book may bereproduced or utilized in any form or by any means, electronic or mechanical, including photo-copying,recording, or by an information storage retrieval system, without permission in writing from the publisher.Inquiries should be addressed to ITCourseware, LLC., 7245 South Havana Street, Suite 150, Centennial,Colorado, 80112. (303) 302-5280.

All brand names, product names, trademarks, and registered trademarks are the property of their respectiveowners.

Page 3: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

© 2004 ITCourseware, LLC Rev 2.1.2 Page iii

Java 2 Enterprise Edition

Contents

Chapter 1 - Course Introduction ............................................................................................................... 1

Course Objectives .............................................................................................................................. 2Course Overview ................................................................................................................................ 4Using the Workbook ........................................................................................................................... 5Suggested References ......................................................................................................................... 6

Chapter 2 - J2EE ...................................................................................................................................... 9

J2EE Overview ................................................................................................................................. 10Client Tier ......................................................................................................................................... 12Middle Tier ....................................................................................................................................... 14Application Server Tier ..................................................................................................................... 16The J2EE Platform ............................................................................................................................ 18J2EE Skills ........................................................................................................................................ 20

Chapter 3 - Getting Started with JSP ...................................................................................................... 23

Dynamic Web Content ...................................................................................................................... 24The JSP Solution ............................................................................................................................... 26JSP Syntax ........................................................................................................................................ 28JSP Deployment ................................................................................................................................ 30Variables and Expressions ................................................................................................................. 32Implicit Objects ................................................................................................................................. 34page and taglib Directives .................................................................................................................. 36Include and Forward ......................................................................................................................... 38Exception Handling ........................................................................................................................... 40Labs ................................................................................................................................................. 42

Chapter 4 - Forms and JavaBeans .......................................................................................................... 45

HTML Forms ................................................................................................................................... 46JavaBeans ......................................................................................................................................... 48JavaBeans and JSP ........................................................................................................................... 50Bean Properties ................................................................................................................................ 52

Page 4: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Page iv Rev 2.1.2 © 2004 ITCourseware, LLC

Java 2 Enterprise Edition

Property Types ................................................................................................................................. 54Properties and Forms ........................................................................................................................ 56Bean Scopes ..................................................................................................................................... 58Labs ................................................................................................................................................. 60

Chapter 5 - Introduction to JSTL ............................................................................................................ 63

JSP Expression Language .................................................................................................................. 64Expression Language Implicit Objects ............................................................................................... 66What is JSTL? .................................................................................................................................. 68Core Tags - Conditionals .................................................................................................................. 70Core Tags - Iteration and Import ....................................................................................................... 72XML Manipulation Tags .................................................................................................................... 74Internationalization Tags .................................................................................................................... 76SQL Tags.......................................................................................................................................... 78Labs ................................................................................................................................................. 80

Chapter 6 - Servlet Basics ...................................................................................................................... 83

Browsers, Servers and Servlets ......................................................................................................... 84The Basic Servlet .............................................................................................................................. 86The Servlet Life Cycle ....................................................................................................................... 88The HttpServlet Approach ................................................................................................................ 90More do Methods ............................................................................................................................. 92Threading in Servlets ......................................................................................................................... 94Debugging ......................................................................................................................................... 96Labs ................................................................................................................................................. 98

Chapter 7 - Request and Response ....................................................................................................... 101

Request and Response Basics ......................................................................................................... 102The HttpServletRequest Object ...................................................................................................... 104Request Headers ............................................................................................................................. 106Status Codes .................................................................................................................................. 108Response Headers .......................................................................................................................... 110Ensuring Valid Characters ................................................................................................................ 112Labs ............................................................................................................................................... 114

Page 5: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

© 2004 ITCourseware, LLC Rev 2.1.2 Page v

Java 2 Enterprise Edition

Chapter 8 - Session Tracking ................................................................................................................ 117

Understanding Cookies ................................................................................................................... 118The Cookie Class ........................................................................................................................... 120Cookies in JSP ............................................................................................................................... 122Cookie Properties ........................................................................................................................... 124Session Tracking ............................................................................................................................. 126The HttpSession Class .................................................................................................................... 128Sessions in JSP ............................................................................................................................... 130....................................................................................................................................................... 130Encoding URLs ............................................................................................................................... 132Terminating Sessions ....................................................................................................................... 134Labs ............................................................................................................................................... 136

Chapter 9 - Web Applications ............................................................................................................... 139

Web Application Components ......................................................................................................... 140ServletContext ................................................................................................................................ 142Forward and Include ....................................................................................................................... 144Supporting Files .............................................................................................................................. 146Deployment Descriptor ................................................................................................................... 148Deployment Descriptor Elements .................................................................................................... 150Security - Authentication ................................................................................................................. 152Security in the J2EE Application Server ........................................................................................... 154Security - Authorization ................................................................................................................... 156Labs ............................................................................................................................................... 158

Chapter 10 - Introduction to JNDI ........................................................................................................ 161

Naming and Directory Services ....................................................................................................... 162Namespaces and Contexts .............................................................................................................. 164Naming Operations ......................................................................................................................... 166Bindings .......................................................................................................................................... 168Attributes ........................................................................................................................................ 170Directory Operations....................................................................................................................... 172DNS Lookups with JNDI ............................................................................................................... 174JNDI in J2EE .................................................................................................................................. 176Labs ............................................................................................................................................... 178

Page 6: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Page vi Rev 2.1.2 © 2004 ITCourseware, LLC

Java 2 Enterprise Edition

Chapter 11 - Introduction to JDBC ....................................................................................................... 181

The JDBC Connectivity Model ....................................................................................................... 182Database Programming ................................................................................................................... 184Connecting to the Database ............................................................................................................. 186Creating a SQL Query .................................................................................................................... 188Getting the Results ........................................................................................................................... 190Updating Database Data ................................................................................................................. 192Finishing Up .................................................................................................................................... 194Labs ............................................................................................................................................... 196

Chapter 12 - JDBC SQL Programming ................................................................................................. 199

Error Checking and the SQLException Class .................................................................................. 200The SQLWarning Class ................................................................................................................... 202The Statement Interface .................................................................................................................. 204The ResultSet Interface ................................................................................................................... 206Updatable Result Sets ..................................................................................................................... 208JDBC Types ................................................................................................................................... 210Executing SQL Queries ................................................................................................................... 212ResultSetMetaData ......................................................................................................................... 214Executing SQL Updates .................................................................................................................. 216Transaction Management ................................................................................................................. 218JDBC SQL Escape Syntax ............................................................................................................. 220Labs ............................................................................................................................................... 222

Chapter 13 - Advanced JDBC .............................................................................................................. 225

Using a PreparedStatement ............................................................................................................. 226Parameterized Statements ............................................................................................................... 228Stored Procedures .......................................................................................................................... 230ResultSets from Stored Procedures ................................................................................................. 232The execute() Method ..................................................................................................................... 234Batch Updates ................................................................................................................................ 236RowSets ......................................................................................................................................... 238DatabaseMetaData ......................................................................................................................... 240Large Objects ................................................................................................................................. 242The DriverManager Class ............................................................................................................... 244Types of JDBC Driver .................................................................................................................... 246Labs ............................................................................................................................................... 248

Page 7: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

© 2004 ITCourseware, LLC Rev 2.1.2 Page vii

Java 2 Enterprise Edition

Chapter 14 - DataSources .................................................................................................................... 251

DataSources ................................................................................................................................... 252Connection Pools in the J2EE Application Server ............................................................................ 254Data Sources in the J2EE Application Server .................................................................................. 256Connecting to a DataSource............................................................................................................ 258Labs ............................................................................................................................................... 260

Chapter 15 - Introduction to JavaMail ................................................................................................... 263

Mail Systems and JavaMail ............................................................................................................. 264The javax.mail Packages ................................................................................................................. 266Establishing a Session ...................................................................................................................... 268The Message Interface .................................................................................................................... 270Sending a Message ......................................................................................................................... 272Message Stores .............................................................................................................................. 274Mail Folders ................................................................................................................................... 276Multipart Messages ......................................................................................................................... 278

Chapter 16 - JMS ................................................................................................................................. 281

Introduction to JMS Concepts ........................................................................................................ 282What is JMS ? ................................................................................................................................ 284Parent Interfaces and GMD ............................................................................................................ 286JMS Definitions ............................................................................................................................... 288Message Object .............................................................................................................................. 290Multi-Threading and JMS Exception ............................................................................................... 292PTP Domain and Interfaces ............................................................................................................. 294Pub/Sub Domain and Interfaces ...................................................................................................... 296J2EE Application Server Administered Objects ............................................................................... 298Creating the Client ........................................................................................................................... 300Handling the Message ..................................................................................................................... 302Producing the Message ................................................................................................................... 304Labs ............................................................................................................................................... 306

Page 8: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Page viii Rev 2.1.2 © 2004 ITCourseware, LLC

Java 2 Enterprise Edition

Chapter 17 - EJB and the J2EE Architecture ......................................................................................... 309

Evolution of Distributed Computing on the Web .............................................................................. 310The J2EE Solution........................................................................................................................... 312The Enterprise JavaBean ................................................................................................................. 314Roles in Enterprise JavaBeans Development .................................................................................... 316EJB Container and Application Server ............................................................................................. 318Web Services and J2EE .................................................................................................................. 320

Chapter 18 - Getting Started with EJB .................................................................................................. 323

Defining the Bean Class ................................................................................................................... 324Remote Interface ............................................................................................................................. 326Writing Business Methods ............................................................................................................... 328Home Interface ............................................................................................................................... 330Deployment Descriptors and Deployment ....................................................................................... 332The Client ....................................................................................................................................... 334Locating the Bean ........................................................................................................................... 336Create an Enterprise Bean Instance ................................................................................................. 338Invoking the Bean’s Methods .......................................................................................................... 340Compiling and Running the Client .................................................................................................... 342Labs ............................................................................................................................................... 344

Chapter 19 - Three Types of EJB.......................................................................................................... 347

A Session Bean ............................................................................................................................... 348A Message-Driven Bean ................................................................................................................. 350An Entity Bean ................................................................................................................................ 352What About State?.......................................................................................................................... 354Stateless Session Beans .................................................................................................................. 356Stateful Session Beans .................................................................................................................... 358MDB Code .................................................................................................................................... 360Entity Bean Persistence Models ...................................................................................................... 362Entity Bean Code ............................................................................................................................ 364Deployment Descriptor ................................................................................................................... 366Labs ............................................................................................................................................... 368

Page 9: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

© 2004 ITCourseware, LLC Rev 2.1.2 Page ix

Java 2 Enterprise Edition

Chapter 20 - Case Study ...................................................................................................................... 371

Account Local and Local Home Interfaces ...................................................................................... 372Account EJB ................................................................................................................................... 374ejb-jar.xml....................................................................................................................................... 376sun-ejb-jar.xml ................................................................................................................................ 378Teller Remote and Home Interfaces ................................................................................................. 380TellerEJB ........................................................................................................................................ 382ejb-jar.xml - Take 2 ........................................................................................................................ 384Teller.html........................................................................................................................................ 386Teller Servlet ................................................................................................................................... 388TransferBean ................................................................................................................................... 390Results.jsp....................................................................................................................................... 392web.xml .......................................................................................................................................... 394application.xml ................................................................................................................................ 396

Appendix A - Deploying a JSP with the deploytool ................................................................................ 399

WAR Wizard .................................................................................................................................. 400Deploying the WAR ........................................................................................................................ 402Changing the WAR.......................................................................................................................... 404

Solutions ............................................................................................................................................... 407

Index..................................................................................................................................................... 471

Page 10: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Page x Rev 2.1.2 © 2004 ITCourseware, LLC

Java 2 Enterprise Edition

Page 11: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Course Introduction

© 2004 ITCourseware, LLC Rev 2.1.2 Page 1

Chapter 1

Chapter 1 - Course Introduction

Page 12: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 2 Rev 2.1.2 © 2004 ITCourseware, LLC

Describe the structure and use of J2EE technologies.

Create dynamic HTML with JavaServer Pages.

Simplify JSPs with JavaBeans.

Create and use custom tag libraries.

Create dynamic HTML with Java Servlets.

Read request header and form information.

Use the HttpSession API to track session information.

Look up objects and manipulate name-to-object bindings using JNDI.

Write Java programs that interface with databases via JDBC.

Use JavaMail to interface with mail servers

Develop distributed applications with CORBA and JavaIDL

Describe the Enterprise JavaBean architecture.

Write session, entity and message-driven beans.

Use Java Message Services to decouple transaction providers andconsumers.

Course Objectives

Page 13: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Course Introduction

© 2004 ITCourseware, LLC Rev 2.1.2 Page 3

Chapter 1

Page 14: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 4 Rev 2.1.2 © 2004 ITCourseware, LLC

Audience: Java programmers who will use the J2EE to develop transportabledistributed applications.

Prerequisites: Java Programming. Some Java development experience.Familiarity with JavaBeans, RMI and XML is recommended.

Classroom Environment:

A workstation per student.

Course Overview

Page 15: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Course Introduction

© 2004 ITCourseware, LLC Rev 2.1.2 Page 5

Chapter 1

Using the Workbook

Chapter 2 Servlet Basics

© 2002 ITCourseware, LLC Rev 2.0.0 Page 17

Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date

along with the current date:

Today.java

...

public class Today extends GenericServlet {

private Date bornOn;

public void service(ServletRequest request,

ServletResponse response) throws ServletException, IOException

{

...

// Write the document

out.println("This servlet was born on " + bornOn.toString());

out.println("It is now " + today.toString());

}

public void init() {

bornOn = new Date();

}

}

Hands On:

The init() method is

called when the servlet is

loaded into the container.

This workbook design is based on a page-pair, consisting of a Topic page and a Support page. When youlay the workbook open flat, the Topic page is on the left and the Support page is on the right. The Topicpage contains the points to be discussed in class. The Support page has code examples, diagrams, screenshots and additional information. Hands On sections provide opportunities for practical application of keyconcepts. Try It and Investigate sections help direct individual discovery.

In addition, there is an index for quick look-up. Printed lab solutions are in the back of the book as well ason-line if you need a little help.

Java Servlets

Page 16 Rev 2.0.0 © 2002 ITCourseware, LLC

� The servlet container controls the life cycle of the servlet.

� When the first request is received, the container loads the servlet class

and calls the init() method.

� For every request, the container uses a separate thread to call

the service() method.

� When the servlet is unloaded, the container calls the destroy()

method.

� As with Java’s finalize() method, don’t count on this being

called.

� Override one of the init() methods for one-time initializations, instead of

using a constructor.

� The simplest form takes no parameters.

public void init() {...}

� If you need to know container-specific configuration information, use

the other version.

public void init(ServletConfig config) {...

� Whenever you use the ServletConfig approach, always call the

superclass method, which performs additional initializations.

super.init(config);

The Servlet Life Cycle

The Topic page providesthe main topics for

classroom discussion.

The Support page hasadditional information,

examples and suggestions.

Code examples are in afixed font and shaded. Theon-line file name is listedabove the shaded area.

Screen shots showexamples of what youshould see in class.

Topics are organized intofirst ( ), second ( ) and

third ( ) level points.

Pages are numberedsequentially throughout

the book, making lookupeasy.

Callout boxes point outimportant parts of the

example code.

Page 16: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 6 Rev 2.1.2 © 2004 ITCourseware, LLC

Bergsten, Hans. 2003. JavaServer Pages, 3rd Edition. O'Reilly & Associates, Sebastopol, CA.ISBN 0596005636.

Eckstein, Robert, ed. 2002. Java Enterprise Best Practices. O'Reilly & Associates, Sebastopol,CA. ISBN 0596003846.

Fields, Duane K., Mark A. Kolb, and Shawn Bayern. 2001. Web Development with JavaServerPages. Second Edition. Manning Publications Co., Greenwich, CT. ISBN 193011012X.

Flanagan, David, Jim Farley, and William Crawford. 2002. Java Enterprise in a Nutshell, 2ndEdition. O'Reilly & Associates, Sebastopol, CA. ISBN 0596001525.

Hall, Marty. 2003. Core Servlets and JavaServer Pages. Prentice Hall PTR, Upper Saddle River,NJ. ISBN 0130092290.

Hunter, Jason and William Crawford. 2001. Java Servlet Programming, 2nd Edition. O'Reilly &Associates, Sebastopol, CA. ISBN 0596000405.

Kassem, Nicholas. 2000. Designing Enterprise Applications with the Java 2 Platform, EnterpriseEdition. Addison-Wesley, Menlo Park, CA. ISBN 0201702770.

Monson-Haefel, Richard. 2001. Enterprise JavaBeans, Third Edition. O’Reilly & Associates,Sebastopol, CA. ISBN 0596002262.

Roman, Ed, Scott W. Ambler, Tyler Jewell and Floyd Marinescu. 2001. Mastering EnterpriseJavaBeans, Second Edition. John Wiley & Sons, New York, NY. ISBN 0471417114.

Tremblett, Paul. 2000. Instant JavaServer Pages. Osborne McGraw-Hill, New York, NY.ISBN 0072126019.

http://java.sun.com/j2ee

http://java.sun.com/products/jsp/jstl/

http://java.sun.com/products/servlet

http://www.theserverside.com

Suggested References

Page 17: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Course Introduction

© 2004 ITCourseware, LLC Rev 2.1.2 Page 7

Chapter 1

Page 18: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 8 Rev 2.1.2 © 2004 ITCourseware, LLC

Page 19: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

J2EE

© 2004 ITCourseware, LLC Rev 2.1.2 Page 9

Chapter 2

Chapter 2 - J2EE

Objectives

Explain the J2EE multi-tiered applicationmodel.

Describe the J2EE technologies and howthey are related.

Decide which J2EE skills variousdevelopers will require.

Page 20: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 10 Rev 2.1.2 © 2004 ITCourseware, LLC

The Java 2 Enterprise Edition (J2EE) was designed to make the integration oflarge distributed applications as simple and flexible as possible.

There is a limited set of skills that developers need to learn for their part of theapplication.

J2EE helps the developer focus on the part of the application that is specific tothe business, instead of on the semantics of making the pieces work together.

The J2EE specification describes the architecture of an application, as well asthe specific protocols for communication.

The various developers are guaranteed that their section of the application willcommunicate seamlessly with the others.

The choice of tools and products is also less of a concern because they alladhere to the same standards.

Each tier could be written using different tools, and they would still worktogether.

J2EE Overview

Page 21: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

J2EE

© 2004 ITCourseware, LLC Rev 2.1.2 Page 11

Chapter 2

The J2EE platform supports several models for the deployment of J2EE applications.

A two-tier model places all of the presentation and business logic on the client system, with remote accessto a database.

A three-tier model places the presentation on the client system, but places the business logic on anapplication server, which accesses a remote database.

The standard model places the display only on the client, with the presentation logic in the middle tier with aweb server. The business logic is on an application server, with remote access to a database. This is themodel that is discussed here.

The J2EE Standard Application Programming Model

Web Server

Servlet/JSP Container

JNDI

AppServer

JavaMail

EJB Container

JMS Connector

LegacyJDBC

Web Browser

HTML/JavaScript

Client Tier Middle Tier Application Server Tier

RMI

HTTP

Page 22: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 12 Rev 2.1.2 © 2004 ITCourseware, LLC

Most J2EE clients are run within a web browser such as Internet Explorer orNetscape.

Using browser-based clients means that an application does not need tobe installed and maintained on the client machine.

Every time the client is run, it is downloaded from a web server and runslocally.

The client is responsible for the display of data and for interacting with the enduser.

HTML is typically used for the display of data within a browser.

HTML can be combined with JavaScript to allow more flexible display and moresophisticated interaction with the user.

JavaScript provides simple data validation of user input.

Java Applets can also be embedded within an HTML document to allow for theuse of the entire Java 2 language.

Applets are rarely used in J2EE clients because they provide moreoverhead and functionality than is typically needed.

J2EE also allows for clients that are stand-alone Java applications.

This allows implementation of a 2-tier model.

Business logic that would normally exist in the middle tier would beplaced in the client application.

The client would use JDBC to connect to a database directly.

Client Tier

Page 23: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

J2EE

© 2004 ITCourseware, LLC Rev 2.1.2 Page 13

Chapter 2

The web browser displays an HTML document that uses JavaScript to validate the data entry. When theuser clicks the button, a request is sent to the middle tier's web server.

Web Browser

HTML/JavaScript

HTTP

<html>

<head>

<title>Human resources</title>

<script language="JavaScript">

...

</head>

</html>

Page 24: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 14 Rev 2.1.2 © 2004 ITCourseware, LLC

The middle tier defines the presentation logic of a J2EE application.

Presentation logic is used to set the flow of the client application.

The middle tier generates the HTML and JavaScript that is displayed inthe client.

The middle tier consists primarily of a web container.

The web container is a web server, like Apache or IIS, that can also runJava servlets and JavaServer Pages (JSPs).

Servlets are programs written in Java that are invoked by a web server based ona request by a web browser.

Servlets generate web pages dynamically.

Servlets do not contain business logic; they communicate with EnterpriseJavaBeans (EJBs) to get data.

JSPs are a combination of HTML tags, data and JSP scripts.

JSPs are converted into servlets that are run in the web container.

Servlets or JSPs can access EJBs in the application server to perform businesslogic.

Servlets locate EJBs with Java Naming and Directory Interface (JNDI).

JNDI references are defined in XML deployment descriptors.

The XML deployment descriptors are packaged with the servlets,JSPs and any supporting files (e.g., images) into a web archive(.war) file for deployment.

Middle Tier

Page 25: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

J2EE

© 2004 ITCourseware, LLC Rev 2.1.2 Page 15

Chapter 2

When the web server receives a request for a document that is a servlet, or that includes a JavaServer Page,it processes the request with a Servlet/JSP container. This container can be integrated into the web server,or be an add-on product.

JSPs are converted into servlets by the container. The servlet is then executed. It will request informationthat it needs from an EJB in the application server tier. It will output an HTML document that can bedisplayed in the client's browser.

Web Server

HTTP request

HTTP response

Servlet/JSP Container

JavaServer Page/Servlet

JNDI/RMI

Page 26: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 16 Rev 2.1.2 © 2004 ITCourseware, LLC

The application server tier consists primarily of an EJB container.

Each EJB is a Java component that encapsulates data and functionality.

The EJBs provide the business logic of the application.

The container is responsible for running various EJBs when they arerequested from the middle tier.

It is also possible for other EJBs, or even for clients, to make requestsof an EJB.

The EJBs are located using JNDI, and the commucationbetween the requestor and the EJB takes place using the RMIprotocol.

Several APIs are available to the EJBs.

Java Database Connectivity (JDBC) allows connections to relationaldatabases.

Java Connectivity API (JCA), and Java Message Service (JMS)provide access to legacy systems.

JavaMail is used to send email messages when necessary.

EJBs are packaged along with their XML deployment descriptors in Javaarchive (.jar) files.

When the application server also serves as the Servlet/JSP container, .jar and.war files can be packaged and deployed in an enterprise archive (.ear) file.

Application Server Tier

Page 27: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

J2EE

© 2004 ITCourseware, LLC Rev 2.1.2 Page 17

Chapter 2

When an EJB container receives a request, it will invoke the appropriate EJB. The EJB can then accessdatabases, legacy systems, other EJBs and non-Java components. It can send information back to thereqestor when it has completed its task.

Dozens of EJB containers, also called EJB servers, are available for purchase, such as:

BEA Weblogic ServerIBM WebSphere Application ServerOracle Application Server. . . and many others

The choice of a product is based on features such as security, resource management, integration with othertools and price.

Since all products adhere to the J2EE standards, switching products to meet changing needs is always anoption. Sun Microsystems offers the reference implementation, J2EE 1.3 SDK, which is primarily used fortesting of EJBs. It is not as robust and full-featured as the commercial products.

EJB Container

EJB EJB

JNDI/RMI JNDI/RMI

JMS

JCA

mainframe

CORBA

C++ Object

JavaMail other

users

JDBC

Database

Message-Oriented

Middleware

Page 28: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 18 Rev 2.1.2 © 2004 ITCourseware, LLC

The J2EE encompasses more than just the application programming model thathas been described.

The J2EE Platform specifies a set of required APIs and policies needed to runJ2EE applications.

Any operating system can be used, as long as the J2EE platform isavailable.

The J2EE 1.4 Application Server can be used to develop and deploy J2EEapplications.

Production use of the Application Server is free of charge, however,commercial application servers may be more reliable and scalable.

The J2EE Compatibility Test Suite is a set of tests designed to verify that aproduct is compatible with the J2EE platform standard.

Vendors compete on implementations, rather than on standard APIs.

This ensures application portability.

The J2EE Platform

Page 29: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

J2EE

© 2004 ITCourseware, LLC Rev 2.1.2 Page 19

Chapter 2

All EJB implementations, even the J2EE 1.4 Application Server, have proprietary entries indeployment descriptors for defining things such as security and database connections. While the codemay work across implementations, adjustments will have to be made to the deployment descriptorsthat are packaged with the JARs.

The J2EE 1.4 Application Server can be downloaded for free from the http://java.sun.com website.

Page 30: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 20 Rev 2.1.2 © 2004 ITCourseware, LLC

There are a few basic skills each of your developers will need to master.

These skills depend on which tier they will be developing for.

For the client tier, developers will need to learn:

HTMLJavaScript

For the middle tier, developers will need to learn:

Java 2 languageJavaServer PagesJava ServletsJNDI

For the application server tier, developers will need to learn:

Java 2 languageEnterprise JavaBeansJDBC

The learning of additional APIs and technologies will depend on other existingproducts and systems that need to be integrated into the overall application.

EJB developers may also need to learn JMS or JCA to communicate witha mainframe system or use JavaIDL to communicate with a C++application through CORBA.

Client tier developers may need to learn Java Applets for browser-baseduser interfaces that demand more than HTML forms can provide.

J2EE Skills

Page 31: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

J2EE

© 2004 ITCourseware, LLC Rev 2.1.2 Page 21

Chapter 2

Full list of J2EE APIs and Technologies

Clients:HTMLJavaScriptJava AppletsJ2SE clientsJava Swing

Middle Tier Servers:ServletsJSP - JavaServer PagesXML - Extensible Markup LanguageJAXP - Java API for XML ParsingHTTP/HTTPS - HyperText Transfer Protocol (Secure)

Application Servers:EJB - Enterprise JavaBeansJDBC - Java DataBase ConnectivityJavaMail (with MIME types)JAF - Java Activation Framework (for MIME types with JavaMail)JCA - Java Connector APIJAAS - Java Authentication and Authorization Service (for use with JCA)JMS - Java Message ServiceJTS - Java Transaction Service (for access to CORBA)JTA - Java Transaction API

Communication:JNDI - Java Naming and Directory InterfaceRMI-IIOP - Java Remote Method Invocation over Internet Inter-ORB ProtocolRMI-JRMP - Java Remote Method Invocation over JRMPJavaIDL - Java Interface Definition Language (for interfacing with CORBA)

Web Services:JAX-RPC - Java API for XML-Based RPCJAXR - Java API for XML RegistriesSAAJ - SOAP with Attachments API for Java

Management and Deployment:J2EE Management ModelJ2EE Deployment APIJMX - Java Management Extension

Page 32: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 22 Rev 2.1.2 © 2004 ITCourseware, LLC

Page 33: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 6 Servlet Basics

© 2004 ITCourseware, LLC Rev 2.1.2 Page 83

Chapter 6 - Servlet Basics

Objectives

Write a servlet to generate simpletext.

Use the three entry points into aservlet.

Debug Java Servlets.

Page 34: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 84 Rev 2.1.2 © 2004 ITCourseware, LLC

Browsers provide access to web content, usually by interpreting HTMLdocuments to display information.

Most common browsers understand extensions to HTML, such asJavaScript, that provide some programming capability.

Sometimes known as Dynamic HTML (DHTML), these scriptinglanguages are limited to simple validation and localized functionality(they are not allowed access to other servers, such as RDBMSs orORBs).

Web servers provide documents to browsers.

The browser specifies the document it’s looking for in the form of aURL.

The URL often specifies a static file for the server to retrieve.

Since they are static files, they must be created and made availableprior to the request.

Other techniques allow the server to run a program that generates thedocument on-the-fly.

Dynamically generated documents can contain time-sensitive oruser-specific information, produced as needed.

Servlets are a powerful and efficient mechanism for providing dynamic webcontent.

Browsers, Servers and Servlets

Page 35: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 6 Servlet Basics

© 2004 ITCourseware, LLC Rev 2.1.2 Page 85

A servlet-capable web server contains or has access to a servlet container. The servlet container executesany servlets that are requested with its JVM. Since servlets are written in Java, they have all of thecapabilities of the Java language. A servlet can access an RDBMS through JDBC, an ORB throughCORBA, or just about any other type of server application.

Web Browser

Client

Web Server

Servlet

URL="http://localhost/servlets/Name"tp://localhost/servlport

Internet

HTML

J2EE Application Server

Page 36: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 86 Rev 2.1.2 © 2004 ITCourseware, LLC

A servlet is a class that extends javax.servlet.GenericServlet.

GenericServlet declares an abstract service() method, which is called bythe servlet container whenever it receives a request for the servlet.

Your servlet must override the service() method.

This is where you generate the document that is returned to the browser.

service() is passed a ServletRequest and a ServletResponse as parameters.

The ServletRequest gives you information about the request, such asCGI parameters.

Use the ServletResponse to write the document to the browser.

Specify the document type.

response.setContentType("text/html");

Get a PrintWriter.

PrintWriter out = res.getWriter();

Write to the PrintWriter just as you would to System.out.

out.println("Hello, World!");

The Basic Servlet

Page 37: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 6 Servlet Basics

© 2004 ITCourseware, LLC Rev 2.1.2 Page 87

Hands On:

Create a servlet by extending the javax.servlet.GenericServlet class:

Today.javaimport java.io.*;import java.util.*;import javax.servlet.*;

public class Today extends GenericServlet {public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException{

// Get the current system time and dateDate today = new Date();// Specify the response’s MIME typeresponse.setContentType("text/plain");// Get the OutputStreamPrintWriter out = response.getWriter();// Write the documentout.println(today.toString());

}}

Run the asant command in your chapter directory to compile the servlet into the proper directorystructure, build a .war file, and deploy it. Visit http://localhost:8080/ServletBasics/Today to viewyour servlet.

Page 38: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 88 Rev 2.1.2 © 2004 ITCourseware, LLC

The servlet container controls the life cycle of the servlet.

When the first request is received, the container loads the servlet class andcalls the init() method.

For every request, the container uses a separate thread to call theservice() method.

When the servlet is unloaded, the container calls the destroy() method.

As with Java’s finalize() method, don’t count on this being called.

Override one of the init() methods for one-time initializations, instead of using aconstructor.

The simplest form takes no parameters.

public void init() {...}

If you need to know container-specific configuration information, use theother version.

public void init(ServletConfig config) {...

Whenever you use the ServletConfig approach, always call thesuperclass method, which performs additional initializations.

super.init(config);

The Servlet Life Cycle

Page 39: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 6 Servlet Basics

© 2004 ITCourseware, LLC Rev 2.1.2 Page 89

Hands On:

Add an init() method to your Today servlet that initializes a bornOn date, then print the bornOn date alongwith the current date:

Today.java...

public class Today extends GenericServlet {private Date bornOn;public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException{

...// Write the documentout.println("This servlet was born on " + bornOn.toString());out.println("It is now " + today.toString());

}public void init() {

bornOn = new Date();}

}

Try It:

Deploy and test the new version of your servlet.

Page 40: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 90 Rev 2.1.2 © 2004 ITCourseware, LLC

Theoretically, servlets can be used for protocols other than HTTP.

A servlet might provide documents via FTP or SMTP.

Currently, servlet containers only work with web servers.

Java provides a special class for HTTP servlets, called HttpServlet.

HttpServlet extends GenericServlet.

HttpServlet is in the javax.servlet.http package.

You should extend HttpServlet for your web servlets.

HttpServlet defines HTTP-specific methods, so that you candifferentiate between request methods.

You can override doGet() to handle GET requests.

You can override doPost() to handle POST requests.

doGet() and doPost() take an HttpServletRequest and anHttpServletResponse as parameters, which provide HTTP-specific functionality.

These specialized versions of ServletRequest andServletResponse allow you to set or get headers or cookies.

Extend HttpServlet even if you don’t differentiate between GET and POSTrequests.

Have your doPost() method call doGet(), or vice versa.

The HttpServlet Approach

Page 41: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 6 Servlet Basics

© 2004 ITCourseware, LLC Rev 2.1.2 Page 91

Hands On:

Change your Today servlet to extend HTTPServlet, converting your service() method to doGet() andadding doPost():

Today.java

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

public class Today extends HttpServlet {private Date bornOn;public void doGet(HttpServletRequest request,

HttpServletResponse response)throws ServletException, IOException {

// Get the current system time and dateDate today = new Date();...out.println("It is now " + today.toString());

}public void doPost(HttpServletRequest request,

HttpServletResponse response)throws ServletException, IOException {

doGet(request, response);}...

}

Try It:

Deploy and test the HTTP version of your servlet.

The doPost() method callsthe doGet() method.

Page 42: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 92 Rev 2.1.2 © 2004 ITCourseware, LLC

HTTP defines several request methods, each of which can be handled by anHttpServlet.

A GET request usually comes from a user typing a URL into the browseror clicking on a link.

Override the doGet() method for GET requests.

A POST request usually comes form an HTML form, where<FORM method="POST" ...

Override the doPost() method for POST requests.

The doDelete() method handles DELETE requests.

The doPut() method handles PUT requests.

doOptions() and doTrace() handle OPTIONS and TRACE requests,respectively.

If you don’t override these methods, the HttpServlet class willhandle them for you.

There is no method for handling HEAD requests.

HttpServlet automatically gets the header information from thedoGet() method.

More do Methods

Page 43: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 6 Servlet Basics

© 2004 ITCourseware, LLC Rev 2.1.2 Page 93

The vast majority of HTTP requests are GET, POST or HEAD requests. Most servlets will override thedoGet() or doPost() method. The other do methods are rarely used.

The HEAD method is used whenever the client wants only header information, not the data in thedocument. Since the header for a HEAD request is supposed to be the same as the header for a GETrequest, the servlet container calls doGet() to get the information.

The PUT method requests that the body of the request be stored at the specified URI.

The DELETE method requests that the data at the specified URI is removed.

Extreme care must be taken when using PUT and DELETE requests to prevent security problems.

The TRACE method requests that the body of the request be returned intact. This is used for debugging.

A sample HTTP request:

GET /examples/servlet/Today HTTP/1.0Connection: Keep-AliveUser-Agent: Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)Host: 127.0.0.1:8080accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*accept-language: en-usaccept-encoding: gzip, deflate

Page 44: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 94 Rev 2.1.2 © 2004 ITCourseware, LLC

A web container creates one instance of the servlet class to handle all requests.

As each request is received, the container assigns it to a thread.

Several requests may access the servlet’s methods simultaneously.

As a servlet developer, you need to protect shared data.

You can control access with synchronized methods.

Threading in Servlets

Page 45: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 6 Servlet Basics

© 2004 ITCourseware, LLC Rev 2.1.2 Page 95

Page 46: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 96 Rev 2.1.2 © 2004 ITCourseware, LLC

Debugging

Since servlets run within a servlet container, they are more difficult to debug thanregular applications.

You may not be able to set breakpoints or watch variables.

One technique is to review the actual HTML source that the servlet generates.

Browsers generally provide a View Source menu option.

You can return an error page to the client.

HttpResponse defines a sendError() method.

You can build a regular page to show what happened.

try {...} catch (Exception e) {

PrintWriter errOut = response.getWriter();e.printStackTrace(errOut);

}

You can log the error to the server’s log file.

GenericServlet defines a log() method that takes a String as aparameter.

Page 47: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 6 Servlet Basics

© 2004 ITCourseware, LLC Rev 2.1.2 Page 97

HandleError.java

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

public class HandleError extends HttpServlet {public void doGet(HttpServletRequest request,

HttpServletResponse response)throws IOException

{response.setContentType("text/plain");PrintWriter out = null;try {

// Get the OutputStreamout = response.getWriter();// Write the documentDate data = null;out.println(data.toString());

} catch (Exception e) {String message = e.getClass().getName() + ": " + e.getMessage();log(message);if (out != null) {

e.printStackTrace(out);} else {

response.sendError(500, message);}

}}public void doPost(HttpServletRequest request,

HttpServletResponse response)throws IOException

{doGet(request, response);

}}

The log file name and location depend upon your web container and configuration. For the J2EEApplication Server, it may be something like c:\Sun\AppServer\domains\domain1\logs.

Write an error message tothe server's log file.

Write the stack trace tothe browser or return a

server error.

Page 48: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 98 Rev 2.1.2 © 2004 ITCourseware, LLC

Write a servlet that shows the minimum and maximum values for the eight Java primitive types.Hint: The wrapper classes in the java.lang package define minimum and maximum values.(Solution: JavaTypes.java)

Make your JavaTypes.java servlet accessible from a GET or POST method.(Solution: JavaTypes2.java)

Catch any exceptions that may be thrown within your servlet and display the stack trace in the clientbrowser. Test your servlet by purposely throwing an exception, such as a NullPointerException.(Solution: ExceptionHandler.java)

Labs

Page 49: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 6 Servlet Basics

© 2004 ITCourseware, LLC Rev 2.1.2 Page 99

Page 50: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 100 Rev 2.1.2 © 2004 ITCourseware, LLC

Page 51: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 17 EJB and the J2EE Architecture

© 2004 ITCourseware, LLC Rev 2.1.2 Page 309

Chapter 17 - EJB and the J2EE Architecture

Objectives

Explain the structure and usage ofEnterprise JavaBeans.

Describe the relationship betweenEJBs, EJB containers and anapplication server.

Describe distributed computingtechniques and the evolution of EJB.

Distinguish container-managedservices from bean-managedservices.

Describe the three main roles inbuilding a J2EE application.

Install the J2EE ReferenceImplementation.

Page 52: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 310 Rev 2.1.2 © 2004 ITCourseware, LLC

The combination of CGI and Perl was initially the most popular way to createdynamic HTML pages.

A single "Internet Programmer" was responsible for all aspects of webdevelopment.

While relatively easy to develop, CGI/Perl servers proved to be inefficientat runtime.

CORBA allows a developer to invoke programs or objects in other servers.

Developers can implement CORBA in many different languages, on manydifferent platforms.

CORBA servers, or ORBs, provide location transparency between theclient and server.

CORBA requires a significant amount of overhead for relatively lacklusterperformance.

CORBA is not implementation independent, thus one CORBA applicationcannot be guaranteed to run on all CORBA servers.

Transaction Process Monitors (TPM), in combination with CORBA, providetransaction management and application server functionality.

TPMs are proprietary to an implementation.

Application Servers provide a framework for system-level services.

This framework frees up the developer to concentrate on business logic,not on system level services.

Evolution of Distributed Computing on theWeb

Page 53: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 17 EJB and the J2EE Architecture

© 2004 ITCourseware, LLC Rev 2.1.2 Page 311

Transaction Process Monitors (TPMs), such as CICS from IBM and Tuxedo from BEA, provide mission-critical applications with a high-speed server platform. A TPM manages the environment of the application,providing functionality such as fault tolerance, resource management and transaction support.

A major drawback to TPMs is the fact that they are not object-based. In fact, most TPM applications arewritten in COBOL.

Page 54: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 312 Rev 2.1.2 © 2004 ITCourseware, LLC

J2EE is a set of related specifications for enterprise application development anddeployment consisting of many complementary technologies.

The Web container is responsible for an application's web presentation.

JavaServer Pages (JSP) is one of the presentation layers of J2EE.

Servlets provide the control layer and separate the interface from thebusiness logic.

The EJB container holds and manages the Enterprise JavaBeans.

The EJB container can use several different APIs to interact with EnterpriseJavaBeans.

JDBC (Java Database Connectivity) facilitates the interaction of the EJBcontainer and the database source.

JNDI (Java Naming and Directory Interface) is used to locate resources.

JMS (Java Message Service) provides for asynchronous messagingbetween servers.

JavaMail is Java's email API.

JTA / JTS (Java Transaction API / Java Transaction Service) facilitatebean-managed transactions.

J2EE facilitates the separation of roles in web application development.

The J2EE Solution

Page 55: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 17 EJB and the J2EE Architecture

© 2004 ITCourseware, LLC Rev 2.1.2 Page 313

Page 56: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 314 Rev 2.1.2 © 2004 ITCourseware, LLC

The Enterprise JavaBeans architecture is a distributed component architecturefor creating reusable and platform-independent applications.

Enterprise JavaBeans encapsulate business logic.

An EJB developer concentrates on fulfilling business requirements, not onthe environment or network architecture.

The EJB container manages both session and entity beans.

Session beans are the task-oriented component of EJB.

Contain task-oriented business logic.

Coordinate entity beans, system resources and other session beans.

Data does not survive server crashes.

Entity beans represent real-world business objects.

Usually represent data in an existing database.

Can be located via a primary key or other unique identifier.

Data is persistent and survives server crashes.

Message-driven beans are message consumers in MOM architectures.

The Enterprise JavaBean

Page 57: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 17 EJB and the J2EE Architecture

© 2004 ITCourseware, LLC Rev 2.1.2 Page 315

Container-managed services vs. bean-managed services:

The purpose of an Enterprise JavaBean container is to provide system level services, such as persistenceand transaction management. These services allow a Bean Provider to concentrate on the business logicrequired by the application.

The Bean Provider should use as many of these container-managed services as possible. Doing so allowsfaster bean development, implementation of standardized system level services, decoupling of system levelservices from business logic, increased code reuse and less code complexity.

The declarative nature of container-managed services may prove limiting when the bean requires servicesthat depend on parameters that are dynamic. The Bean Provider can specify bean-managed services in thedeployment descriptor, overriding some services while using the container for the remaining ones.

The disadvantage to bean-managed services lies in limitations on portability, reusability and increased codecomplexity. The Bean Provider should use container-managed services wherever possible and bean-managed services only when necessary.

Page 58: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 316 Rev 2.1.2 © 2004 ITCourseware, LLC

The Enterprise JavaBeans Specification 2.0 defines three roles in thedevelopment of Enterprise JavaBeans.

The Bean Provider creates the enterprise bean and is only responsible forthe bean as an individual unit.

The Bean Provider is required to provide the enterprise bean code(including home and remote interfaces and entries in thedeployment descriptor that apply to that particular enterprise bean).

The Application Assembler puts together a set of enterprise beans(potentially provided by disparate sources) into an application with theEJBs working in conjunction.

The Application Assembler is required to package all beans of anapplication in their respective archive files (.jar, .war, or .ear files)and make edits to the deployment descriptor to enable correctcommunications between the beans.

The Deployer is responsible for deploying the application (provided bythe Application Assembler) on a specific application server environment.

The Deployer primarily makes necessary changes to environmentvariables and mapping of logical variables to physical variables,such as matching security roles (logically defined in theapplication) to users and groups (defined in the application server).

Roles in Enterprise JavaBeans Development

Page 59: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 17 EJB and the J2EE Architecture

© 2004 ITCourseware, LLC Rev 2.1.2 Page 317

The roles listed on the facing page are the ones that are important in the development of an EJB and itsincorporation into a web application. The EJB 2.0 specification defines three additional roles: EJB ServerProvider, EJB Container Provider, and System Administrator. These roles are primarily concerned with thedevelopment and administration of the EJB environment, instead of bean development, so we will not befocusing on them in this class.

Page 60: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 318 Rev 2.1.2 © 2004 ITCourseware, LLC

The EJB container provides system-level functions for its deployed EJBs.

Accessibility through the home interface.

Resource management.

Security management.

Transaction management.

Persistence management.

Concurrency.

Asynchronous messaging.

The application server wraps around the EJB container, providing additionalsystem support.

Clustering: a set of interconnected servers.

Load balancing: balances the workload among the clustered servers.

Fail-Over: monitors the servers in the cluster and restarts any servers thatare down.

The application server and the EJB container are combined and come from thesame vendor.

Application servers often include a web server.

EJB Container and Application Server

Page 61: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 17 EJB and the J2EE Architecture

© 2004 ITCourseware, LLC Rev 2.1.2 Page 319

EJB application servers must follow the specification provided by Sun. How the specification isimplemented is up to the application server vendor. EJB servers can have differences in services provided.The specification only indicates functions of the container, not of the application server.

Page 62: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 320 Rev 2.1.2 © 2004 ITCourseware, LLC

Web Services allow a client to access server-side functionality, over a wellknown transport protocol (usually HTTP), using XML in a programmaticfashion.

The most common XML vocabulary for Web Services is the SimpleObject Access Protocol (SOAP).

Web Services define a programmatic interface for the client to use insteadof a browser-based web interface, as is typical with Web Applications.

The programmatic interface can be described using another XMLvocabulary: Web Services Description Language (WSDL).

J2EE 1.4 bundles the JAX-RPC libraries.

JAX-RPC provides a layer of abstraction above SOAP and WSDL,freeing the developer to program to an API instead of directly codingXML.

JAX-RPC tools are used to generate stub and skeleton code tohandle the SOAP messaging for you.

As a developer, you write an interface and implementation, then use the JAX-RPC tools to generate the rest.

The implementation, called the service endpoint, can come in two flavors:

Servlet endpoint - a class that runs in the J2EE web container.

EJB endpoint - a stateless session bean that runs in the EJB container

Regardless of the type of endpoint, JAX-RPC hides the SOAP messagingfrom the implementation code.

Web Services and J2EE

Page 63: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Chapter 17 EJB and the J2EE Architecture

© 2004 ITCourseware, LLC Rev 2.1.2 Page 321

For more information on web services in J2EE see: http://java.sun.com/developer/technicalArticles/J2EE/j2ee_ws/

Java

Client

stub

JAX-RPC

Client Runtime

skeleton

Non-Java

Client

JAX-RPC

Runtime

Service

Endpoint

Implementation

J2EE Application Server

SOAP/HTTP

request()

resp

onse

SOAP/HTTP

request()

response

SOA

P/HTTP

SOA

P/HTTP

Page 64: Java 2 Enterprise Edition -  · PDF fileMail Systems and JavaMail ... Use the HttpSession API to track session information. ... The Java 2 Enterprise Edition (J2EE)

Java 2 Enterprise Edition

Page 322 Rev 2.1.2 © 2004 ITCourseware, LLC