67
Enterprise JavaBeans Using BEA WebLogic Student Workbook

Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

  • Upload
    ngoanh

  • View
    234

  • Download
    5

Embed Size (px)

Citation preview

Page 1: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeansUsing

BEA WebLogic

Student Workbook

Page 2: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Page ii Rev 2.1.1 © 2004 ITCourseware, LLC

Enterprise JavaBeans Using BEA WebLogic

Enterprise JavaBeans Using BEA WebLogic

Sihyung Park

Published by ITCourseware, LLC, 7245 South Havana St., Suite 100, Centennial, CO 80112

Editor: Rick Sussenbach

Assistant Editor: Jan Waleri

Special thanks to: Many instructors whose ideas and careful review have contributed to the qualityof this workbook, including Jimmy Ball, Jamie Romero, and Rob Roselius and the many students whohave offered comments, suggestions, criticisms, and insights.

Copyright © 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 photocopying,recording, or by an information storage retrieval system, without permission in writing from thepublisher. Inquiries should be addressed to ITCourseware, LLC, 7245 South Havana St., Suite 100,Centennial, Colorado, 80112. (303) 302-5280

All brand names, product names, trademarks, and registered trademarks are the property of theirrespective owners.

Sihyung Park is lead developer and principal of New Decade Software, LLC.He has provided consulting to many Fortune 500 companies on a variety oftopics, including distributed computing, Java and the Internet. Mr. Parkholds a Master’s Degree in Telecommunications and a CIS degree from theUniversity of Colorado, Boulder. E-mail Mr. Park at [email protected].

Page 3: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

© 2004 ITCourseware, LLC Rev 2.1.1 Page iii

Enterprise JavaBeans Using BEA WebLogic

Contents

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

Course Objectives ............................................................................................................................ 10Course Overview .............................................................................................................................. 12Using the Workbook ......................................................................................................................... 13Suggested References ....................................................................................................................... 14

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

Evolution of Distributed Computing on the Web ................................................................................ 18The J2EE Solution............................................................................................................................. 20The Enterprise JavaBean ................................................................................................................... 22Roles in Enterprise JavaBeans Development ...................................................................................... 24EJB Container and Application Server ............................................................................................... 26

Chapter 3 - Getting Started ..................................................................................................................... 29

Defining the Bean Class ..................................................................................................................... 30Remote Interface ............................................................................................................................... 32Writing Business Methods ................................................................................................................. 34Home Interface ................................................................................................................................. 36Building with Ant ............................................................................................................................... 38Deployment ...................................................................................................................................... 40Configured Deployment .................................................................................................................... 42Automatic Deploy ............................................................................................................................. 44The Client ......................................................................................................................................... 46Locating the Bean ............................................................................................................................. 48Create an Enterprise Bean Instance ................................................................................................... 50Invoking the Bean’s Methods ............................................................................................................ 52Compiling and Running the Client Code............................................................................................. 54Labs ................................................................................................................................................. 56

Page 4: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Page iv Rev 2.1.1 © 2004 ITCourseware, LLC

Enterprise JavaBeans Using BEA WebLogic

Chapter 4 - The javax.ejb Package ......................................................................................................... 59

The Remote Interface ........................................................................................................................ 60The Home Interface .......................................................................................................................... 62The Local Interface ........................................................................................................................... 64The Local Interface Usage ................................................................................................................ 66Container Objects ............................................................................................................................. 68SessionBean Interface ....................................................................................................................... 70EntityBean Interface .......................................................................................................................... 72MessageDrivenBean Interface ........................................................................................................... 74EJB Exceptions ................................................................................................................................. 76EJB Context ..................................................................................................................................... 78Three Contexts ................................................................................................................................. 80Other Interfaces ................................................................................................................................ 82Labs ................................................................................................................................................. 84

Chapter 5 - Session Beans ...................................................................................................................... 87

A Session Bean ................................................................................................................................. 88What About State?............................................................................................................................ 90Stateless Session Beans .................................................................................................................... 92Lifecycle of a Stateless Session Bean ................................................................................................ 94Stateless Deployment Descriptors ..................................................................................................... 96Stateful Session Beans ...................................................................................................................... 98Lifecycle of a Stateful Session Bean ................................................................................................ 100Stateful Deployment Descriptors ..................................................................................................... 102HttpSessions and Cookies .............................................................................................................. 104Labs ............................................................................................................................................... 106

Chapter 6 - Deployment and Deployment Descriptors........................................................................... 109

Web Application Structure .............................................................................................................. 110Deploying a WebLogic Web Application ......................................................................................... 112Packaging an Enterprise Application ................................................................................................ 114EJB Deployment Process ................................................................................................................ 116The Deployment Descriptor ............................................................................................................ 118Structural Data ................................................................................................................................ 120Assembly ........................................................................................................................................ 122

Page 5: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

© 2004 ITCourseware, LLC Rev 2.1.1 Page v

Enterprise JavaBeans Using BEA WebLogic

weblogic-ejb-jar.xml ....................................................................................................................... 124weblogic-cmp-jar.xml ..................................................................................................................... 126Compile .......................................................................................................................................... 128Bundling .......................................................................................................................................... 130Labs ............................................................................................................................................... 132

Chapter 7 - EJB Clients ........................................................................................................................ 135

Client Types .................................................................................................................................... 136Deploying a Web Application .......................................................................................................... 138The JNDI API ................................................................................................................................ 140Lookup with JNDI .......................................................................................................................... 142PortableRemoteObject.narrow( ) .................................................................................................... 144Using the Bean ................................................................................................................................ 146Labs ............................................................................................................................................... 148

Chapter 8 - Entity Beans ....................................................................................................................... 151

An Entity Bean ................................................................................................................................ 152Persistence Models ......................................................................................................................... 154EntityBean Home Interface .............................................................................................................. 156Finder Methods .............................................................................................................................. 158Primary Key ................................................................................................................................... 160The Component Interface ................................................................................................................ 162Lifecycle of an Entity Bean .............................................................................................................. 164Entity Beans and Local Interfaces .................................................................................................... 166Labs ............................................................................................................................................... 168

Chapter 9 - Bean-Managed Persistence ................................................................................................ 171

Why BMP? .................................................................................................................................... 172Create a Connection Pool ............................................................................................................... 174Create a Connection Pool (cont'd) .................................................................................................. 176Create a DataSource....................................................................................................................... 178Create ............................................................................................................................................. 180Remove .......................................................................................................................................... 182Load ............................................................................................................................................... 184Store ............................................................................................................................................... 186ejbFindByPrimaryKey and Other Finder Methods .......................................................................... 188BMP Deployment Descriptors......................................................................................................... 190Labs ............................................................................................................................................... 192

Page 6: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Page vi Rev 2.1.1 © 2004 ITCourseware, LLC

Enterprise JavaBeans Using BEA WebLogic

Chapter 10 - Container-Managed Persistence ...................................................................................... 195

Why CMP? .................................................................................................................................... 196Two Layers of Responsibility ........................................................................................................... 198Coding Conventions in the Abstract Entity Bean .............................................................................. 200ejb-jar.xml....................................................................................................................................... 202weblogic-ejb-jar.xml ....................................................................................................................... 204weblogic-cmp-jar.xml ..................................................................................................................... 206Container-Managed Relationships ................................................................................................... 208Types of CMP Relationships ........................................................................................................... 210Types of CMP Relationships (cont'd) .............................................................................................. 212EJBQL: Finders in CMP ................................................................................................................. 214EJBQL: Finders in CMP (cont'd) .................................................................................................... 216Cascading Delete ............................................................................................................................ 218Automatic Primary Key Generation ................................................................................................. 220Limitations of CMP ......................................................................................................................... 222Labs ............................................................................................................................................... 224

Chapter 11 - Transactions ..................................................................................................................... 227

Transactions in EJB ......................................................................................................................... 228Container-Managed Transactions .................................................................................................... 230Transaction Support Attributes ........................................................................................................ 232Bean-Managed Transactions ........................................................................................................... 234SessionSynchronization ................................................................................................................... 236Labs ............................................................................................................................................... 238

Chapter 12 - EJB Security .................................................................................................................... 241

Security Issues ................................................................................................................................ 242Authentication ................................................................................................................................. 244Authorization ................................................................................................................................... 246Securing Web Applications .............................................................................................................. 248Security and Deployment Descriptor ............................................................................................... 250Bean-Managed Security .................................................................................................................. 252Bean-Managed Security and Deployment Descriptor ...................................................................... 254Labs ............................................................................................................................................... 256

Page 7: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

© 2004 ITCourseware, LLC Rev 2.1.1 Page vii

Enterprise JavaBeans Using BEA WebLogic

Chapter 13 - JMS ................................................................................................................................. 259

Introduction to JMS Concepts ........................................................................................................ 260What is JMS ? ................................................................................................................................ 262Parent Interfaces and GMD ............................................................................................................ 264JMS Definitions ............................................................................................................................... 266Message Object .............................................................................................................................. 268Multi-Threading and JMS Exception ............................................................................................... 270PTP Domain and Interfaces ............................................................................................................. 272Pub/Sub Domain and Interfaces ...................................................................................................... 274JMS Server Setup........................................................................................................................... 276JMS Destination and ConnectionFactory......................................................................................... 278Creating the Subscriber ................................................................................................................... 280Handling the Message ..................................................................................................................... 282Producing the Message ................................................................................................................... 284Labs ............................................................................................................................................... 286

Chapter 14 - Message-Driven Beans .................................................................................................... 289

MessageDriven Beans ..................................................................................................................... 290Asynchronous Processing ................................................................................................................ 292Comparing MDBs........................................................................................................................... 294MDB Interfaces .............................................................................................................................. 296MDB Deployment Descriptor Elements........................................................................................... 298Labs ............................................................................................................................................... 300

Appendix A - Supporting Technologies .................................................................................................. 303

JDBC ............................................................................................................................................. 304Database Transaction Isolation Levels ............................................................................................. 306XML .............................................................................................................................................. 308RMI ................................................................................................................................................ 310Servlets ........................................................................................................................................... 312The JSP Solution ............................................................................................................................. 314

Solutions ............................................................................................................................................... 317

Index..................................................................................................................................................... 419

Page 8: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Page viii Rev 2.1.1 © 2004 ITCourseware, LLC

Enterprise JavaBeans Using BEA WebLogic

Page 9: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 1 Course Introduction

© 2003 ITCourseware, LLC Rev 2.1.1 Page 9

Chapter 1 - Course Introduction

Page 10: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 10 Rev 2.1.1 © 2003 ITCourseware, LLC

Describe the Enterprise JavaBean architecture.

Write session beans.

Write entity beans.

Deploy EJBs within an EJB Container.

Locate and use an Enterprise JavaBean from a client.

Access relational database information from a bean.

Manage EJB transactions.

Use the EJB security mechanisms.

Explain the difference between container-managed services and bean-managed services.

Use Java Message Services and message-driven beans to decouple transactionproviders and consumers.

Course Objectives

Page 11: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 1 Course Introduction

© 2003 ITCourseware, LLC Rev 2.1.1 Page 11

Page 12: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 12 Rev 2.1.1 © 2003 ITCourseware, LLC

Course Overview

Audience: Java programmers who wish to use Enterprise JavaBeans todevelop distributed intranet and internet applications.

Prerequisites: Java Programming for the Enterprise and some Javadevelopment experience. Familiarity with RMI and JDBC is required.

Classroom Environment:

Workstation per student with access to a BEA WebLogic applicationserver.

Page 13: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 1 Course Introduction

© 2003 ITCourseware, LLC Rev 2.1.1 Page 13

Using the Workbook

This workbook design is based on a page-pair, consisting of a Topic page and a Support page.When you lay the workbook open flat, the Topic page is on the left and the Support page is on theright. The Topic page contains the points to be discussed in class. The Support page has codeexamples, diagrams, screen shots and additional information. Hands On sections provideopportunities for practical application of key concepts. Try It and Investigate sections helpdirect individual discovery.

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

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.

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 throughoutthe book, making lookup

easy.

Callout boxes point outimportant parts of the

example code.

Page 14: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 14 Rev 2.1.1 © 2003 ITCourseware, LLC

Suggested References

DeMichiel, Linda G., L. Umit Yalinalp and Sangjeev Krishnan. "Enterprise JavaBeansSpecification Version 2.0." [on-line]. May 31, 2000. Available from java.sun.com/products/ejb/docs.html.

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

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.

Wrox Multi-Team, et.al. 2000. Professional Java Server Programming, J2EE Edition. WroxPress, Chicago, IL. ISBN 1861004656.

java.sun.com/j2eewww.bea.comwww.ejbean.comwww.theserverside.come-docs.bea.com

Page 15: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 1 Course Introduction

© 2003 ITCourseware, LLC Rev 2.1.1 Page 15

Page 16: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 16 Rev 2.1.1 © 2003 ITCourseware, LLC

Page 17: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 2 EJB and the J2EE Architecture

© 2003 ITCourseware, LLC Rev 2.1.1 Page 17

Chapter 2 - 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.

Page 18: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using WebLogic

Page 18 Rev 2.1.1 © 2003 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 beinefficient at runtime.

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

Developers can implement CORBA in many different languages, onmany different platforms.

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

CORBA requires a significant amount of overhead for relativelylackluster performance.

CORBA is not implementation independent, thus one CORBAapplication cannot 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 businesslogic, not on system level services.

Evolution of Distributed Computing on theWeb

Page 19: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 2 EJB and the J2EE Architecture

© 2003 ITCourseware, LLC Rev 2.1.1 Page 19

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

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

Page 20: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using WebLogic

Page 20 Rev 2.1.1 © 2003 ITCourseware, LLC

J2EE is a set of related specifications for enterprise application developmentand deployment 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 theEJB container and the database source.

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

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 21: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 2 EJB and the J2EE Architecture

© 2003 ITCourseware, LLC Rev 2.1.1 Page 21

JSP

Servlets

Session Beans

Entity Beans

Enterprise Information Systems

JNDI

JDBC

Web Container

EJB Container

Database

Page 22: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using WebLogic

Page 22 Rev 2.1.1 © 2003 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, noton the 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 sessionbeans.

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.

The Enterprise JavaBean

Page 23: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 2 EJB and the J2EE Architecture

© 2003 ITCourseware, LLC Rev 2.1.1 Page 23

Container-managed services vs. bean-managed services:

The purpose of an Enterprise JavaBean container is to provide system level services, such aspersistence and transaction management. These services allow a Bean Provider to concentrate on thebusiness logic required by the application.

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

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

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

Page 24: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using WebLogic

Page 24 Rev 2.1.1 © 2003 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 responsiblefor the bean as an individual unit.

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

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 ofan application in their respective archive files (.jar, .war, or.ear files) and make edits to the deployment descriptor to enablecorrect communications between the beans.

The Deployer is responsible for deploying the application (providedby the Application Assembler) on a specific application serverenvironment.

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

Roles in Enterprise JavaBeans Development

Page 25: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 2 EJB and the J2EE Architecture

© 2003 ITCourseware, LLC Rev 2.1.1 Page 25

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: EJBServer Provider, EJB Container Provider, and System Administrator. These roles are primarilyconcerned with the development and administration of the EJB environment, instead of beandevelopment, so we will not be focusing on them in this class.

Page 26: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using WebLogic

Page 26 Rev 2.1.1 © 2003 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 serversthat are down.

The application server and the EJB container are combined and come fromthe same vendor.

Application servers often include a web server.

EJB Container and Application Server

Page 27: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 2 EJB and the J2EE Architecture

© 2003 ITCourseware, LLC Rev 2.1.1 Page 27

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 servicesprovided. The specification only indicates functions of the container, not of the application server.Additionally, application servers add some proprietary functionality that is not indicated by thespecification.

For instance, WebLogic provides the following non-standardized services:

Automatic Primary Key Generation.WebLogic Query Language (WLQL).In-Memory Stateful Session Beans.Read-Only Entity Beans.

There are also differences between implementations of EJB application servers. These productsconform to the specification, implementing the interfaces. However, the underlying technology canvary significantly.

Page 28: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using WebLogic

Page 28 Rev 2.1.1 © 2003 ITCourseware, LLC

Page 29: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 86 Rev 2.1.1 © 2003 ITCourseware, LLC

Page 30: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 5 Session Beans

© 2003 ITCourseware, LLC Rev 2.1.1 Page 87

Chapter 5 - Session Beans

Objectives

Write a session bean.

Describe the purpose of a sessionbean.

Explain the difference betweenstateless and stateful session beans.

Maintain state outside of the EJBcontainer.

Page 31: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 88 Rev 2.1.1 © 2003 ITCourseware, LLC

A session bean implements business logic.

The bean methods conceal the complexities of business tasks from theclient.

Business logic is de-coupled from the client presentation layer,enabling a more flexible and reusable design.

Examples of the roles of business logic components include payroll,inventory, order entry, etc.

A session bean presents a simple interface to the client.

A session bean client is generally another web application component,such as a JSP, a servlet or another EJB.

The bean coordinates other resources to accomplish a coarse-grained task.

Session beans can be transaction aware.

A Session Bean

Page 32: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 5 Session Beans

© 2003 ITCourseware, LLC Rev 2.1.1 Page 89

Session bean interaction with a database:

Entity beans are typically used to interact with databases. This process, however, can be resource-intensive. There are times when you should use a session bean, instead of an entity bean, to retrievedata from the database:

1. When the data that you are retrieving does not need to be shared across the enterprise (among manysystems).

2. When the data that you need does not represent a business object.

3. Just for the purpose of lookup: A session bean can return a string instead of the remote interface.

Session beans can become transaction aware by implementing the SessionSynchronization interface.

Page 33: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 90 Rev 2.1.1 © 2003 ITCourseware, LLC

State is an object's awareness of its attributes.

Conversational state is maintenance of object attributes across methodcalls.

Stateful session beans have conversational state and attribute values that canbe used by other methods.

Stateless session beans do not have conversational state.

They maintain state only within the duration of one method call.

Attributes can be placed inside the bean, but cannot be relied on.

Attributes are shared between many clients, resulting ininconsistent values.

Stateless session beans are dedicated to one client only for the durationof the method call.

The bean is then returned to the pool in the container.

What About State?

Page 34: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 5 Session Beans

© 2003 ITCourseware, LLC Rev 2.1.1 Page 91

Page 35: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 92 Rev 2.1.1 © 2003 ITCourseware, LLC

Stateless session beans do not have conversational state across method calls.

The container pools the stateless session beans.

They are only dedicated to a single client for the duration of one method call.

Therefore, they should be used when the entire task can beaccomplished via one method call.

Stateless session beans are a group of related generic services.

While it is possible to put object attributes in the stateless session bean, thelifecycle management of the container makes them unreliable for maintaininga persistent state.

A stateless session bean can have only one ejbCreate() method.

The ejbCreate() method cannot have any parameters.

Stateless Session Beans

Page 36: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 5 Session Beans

© 2003 ITCourseware, LLC Rev 2.1.1 Page 93

CurrencyConverterEJB.java...public class CurrencyConverterEJB implements SessionBean {

private static double yenRate=0.00749;private static double euroRate=0.86675;private static double gbpRate=1.412;private SessionContext context;

public double usdToYen(double dollars) {return dollars / yenRate;

}public double usdToEuro(double dollars) {

return dollars / euroRate;}public double usdToGBP(double dollars) {

return dollars / gbpRate;}public double yenToUSD(double yen) {

return yen * yenRate;}public double euroToUSD(double euro) {

return euro * euroRate;}public double gbpToUSD(double gbp) {

return gbp * gbpRate;}public CurrencyConverterEJB() {}public void ejbCreate() {}public void ejbRemove() {}public void ejbActivate() {}public void ejbPassivate() {}public void setSessionContext(SessionContext sc) {

context = sc;}

}

Page 37: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 94 Rev 2.1.1 © 2003 ITCourseware, LLC

There are two stages in a stateless session bean's lifecycle.

The container management of the Method Ready Pool involvestransition of the bean from a Does Not Exist state to a Method Readystate and back.

Method Invocation from the client begins with the create() method ofthe home interface.

The container then returns a handle to the EJB container object.

The client invokes a business method on the remote interface.

The container assigns a method ready stateless session beanfrom the pool and invokes the matching business method in thebean.

The bean is only dedicated to the client for the duration of themethod call.

The client then invokes the remove() method of the remoteinterface and the container removes the client's handle to thecontainer object.

The bean remains in the pool.

There is no need for the container to invoke the callback methodsejbActivate() and ejbPassivate() because the bean has no state.

Lifecycle of a Stateless Session Bean

Page 38: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 5 Session Beans

© 2003 ITCourseware, LLC Rev 2.1.1 Page 95

Lifecycle of a stateless session bean:

Transition Container Calls

Container management of the Method Ready Pool:

Try it:

Build the CurrencyConverter bean with buildconverter.xml. You can then buildCurrencyConverterClient with buildconverterclient.xml and use it to test your bean.

Does Not Exist

Method Ready Pool

ejbRemove()

1. newInstance()

2. setSessionContext()

3. ejbCreate()

tsixEtoNseoDmorfydaeRdohteMot

(ecnatsnIwen ) ssalcehtfo)(txetnoCnoisseStes ecnatsniehtfo

)(etaerCbje ecnatsniehtfo

ydaeRdohteMmorftsixEtoNseoDot

)(evomeRbje forebmunehtecuderotredroniloopehtnisnaebydaeRdohteM

Page 39: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 96 Rev 2.1.1 © 2003 ITCourseware, LLC

The differentiator for stateless vs. stateful session beans is an element in thedeployment descriptor.

Stateless session beans usually do not have field data, but this is not arequirement.

Stateless session beans can have only one ejbCreate() method.

Define a stateless session bean with the <session-type> element in the ejb-jar.xml deployment descriptor:

<session-type>Stateless</session-type>

The weblogic-ejb-jar.xml deployment descriptor must have a <stateless-session-descriptor> element for each stateless session bean defined in theejb-jar.xml file.

Within the <stateless-session-descriptor> you can define the initialand maximum number of beans in the method ready pool.

Stateless Deployment Descriptors

Page 40: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 5 Session Beans

© 2003 ITCourseware, LLC Rev 2.1.1 Page 97

converter-ejb-jar.xml...<ejb-jar>

<enterprise-beans><session>

<ejb-name>CurrencyConverter</ejb-name><home>CurrencyConverterHome</home><remote>CurrencyConverter</remote><ejb-class>CurrencyConverterEJB</ejb-class><session-type>Stateless</session-type><transaction-type>Container</transaction-type>

</session></enterprise-beans>

</ejb-jar>

converter-weblogic-ejb-jar.xml...<weblogic-ejb-jar>

<weblogic-enterprise-bean><ejb-name>CurrencyConverter</ejb-name><stateless-session-descriptor>

<pool><max-beans-in-free-pool>400</max-beans-in-free-pool><initial-beans-in-free-pool>2</initial-beans-in-free-pool>

</pool></stateless-session-descriptor><jndi-name>converter</jndi-name>

</weblogic-enterprise-bean></weblogic-ejb-jar>

Page 41: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 98 Rev 2.1.1 © 2003 ITCourseware, LLC

Stateful session beans have conversational state across method calls.

They are not pooled.

They are dedicated to one client for the life of the bean.

Stateful session beans become integrated with the client, providingservices for that client until the client is done with it.

Stateful session beans should be used when the task cannot be accomplished viaone method call.

There is an in-memory replication feature for stateful session beans.

A backup of the stateful bean on another server will resume control of thesession in the case of a primary server failure.

A session bean is made stateful with the <session-type>stateful</session-type>element in the deployment descriptor.

Stateful session beans are allowed to overload the ejbCreate() method.

Stateful Session Beans

Page 42: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 5 Session Beans

© 2003 ITCourseware, LLC Rev 2.1.1 Page 99

ShoppingCartEJB.java...public class ShoppingCartEJB implements SessionBean {

private HashMap items;

public void addItem(String code, String descr, int quantity,double price) {

ArrayList item = new ArrayList();item.add(descr);item.add(new Integer(quantity));item.add(new Double(price));items.put(code,item);

}public void removeItem(String code) {

if (!items.containsKey(code)) {throw new EJBException(code + " not in item list.");

}items.remove(code);

}public Set getItems() {

return new HashSet(items.keySet());}public String getLine(String code) {

if (!items.containsKey(code)) {throw new EJBException(code + " not in item list.");

}ArrayList item = (ArrayList) items.get(code);String line = "";for (Iterator i=item.iterator(); i.hasNext(); ) {

line = line + i.next().toString() + " ";}return line;

}public void ejbCreate(int count) {

items = new HashMap(count);}...

}

Page 43: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 100 Rev 2.1.1 © 2003 ITCourseware, LLC

The three stages in the lifecycle of a stateful session bean are:

Does not Exist, when no instances are created.

Cache, when the bean is assigned to its client and ready to be used.

Passive, when the non-transient attributes and association to thecontainer object are serialized to secondary memory.

Lifecycle of a Stateful Session Bean

Lifecycle of a stateful session bean:

Does Not Exist

Cache

ejbRemove()

1. newInstance()

2. setSessionContext()

3. ejbCreate()

ejbActivate()

ejbPassivate()

Passive

timeout

instance throws system

exception from any method

Page 44: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 5 Session Beans

© 2003 ITCourseware, LLC Rev 2.1.1 Page 101

Transition Container Calls

Try it:

Build the ShoppingCart bean with buildcart.xml. You can then build ShoppingCartClient withbuildcartclient.xml and use it to test your bean.

tsixEtoNseoDmorfehcaCot

)(etaerc )sretemaraplaitiniemosgnissap(ecafretniemohehtno)(ecnatsnIwen ssalcnaebehtno

)(etaerCbje ivdessapsretemaraphtiw(ecnatsniehtfo )(etaerc )noissesehtotdengissatcejboreniatnocBJEehtoteldnahasnruteR

tneilcehtotecnatsninaeb

morf ehcaCevissaPot

)(etavissaPbje ebehttahtsenimretedreniatnocfidellac ebnacnaegarotsyradnocesotdevom

egarotsyradnocesotdezilaireserasecnatsninaeB

evissaPmorfot ehcaC

ecafretnietomerehtnodohtemssenisubasekovnitneilCyromemyramirpotderotser)s(etubirttaecnatsnI

)(etavitcAbje reniatnocehtybdellacyletaidemmisi

evissaPmorftsixEtoNseoDot

devomerebotsdeennaebehttahtsenimretedreniatnoCdevomeroslasinaebehthtiwdetaicossatcejboreniatnocBJE

morf ehcaCtsixEtoNseoDot

)...(evomer -ro-ecafretniemohehtfo)(evomer ecafretnietomerehtfo

)(evomeRbje ecnatsniehtfo ehtsevomer tcejboreniatnocBJE

Page 45: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 102 Rev 2.1.1 © 2003 ITCourseware, LLC

Define a stateful session bean with the <session-type> element in the ejb-jar.xml deployment descriptor:

<session-type>Stateful</session-type>

The weblogic-ejb-jar.xml deployment descriptor must have a<stateful-session-descriptor> element for each stateful session bean definedin the ejb-jar.xml file.

Within the <stateful-session-descriptor> you can define thepassivation characteristics of your bean.

Use a value of NRU (Not Recently Used) for <cache-type> if lazypassivation is desired.

With lazy passivation, the bean is removed after <idle-timeout-seconds> has expired; no passivation will occur.

If <max-beans-in-cache> is reached, then passivation willoccur.

NRU is the default.

LRU (Least Recently Used) should be the value for <cache-type> ifeager passivation is desired.

With LRU, passivation will occur when the <max-beans-in-cache> value is attained or if the <idle-timeout-seconds> expires.

The location of the passivated bean files is specified in the<persistent-store-dir> entry.

The directory is relative to domain_dir/server_name.

Stateful Deployment Descriptors

Page 46: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 5 Session Beans

© 2003 ITCourseware, LLC Rev 2.1.1 Page 103

cart-ejb-jar.xml...<ejb-jar>

<enterprise-beans><session>

<ejb-name>ShoppingCart</ejb-name><home>ShoppingCartHome</home><remote>ShoppingCart</remote><ejb-class>ShoppingCartEJB</ejb-class><session-type>Stateful</session-type><transaction-type>Container</transaction-type>

</session></enterprise-beans>

</ejb-jar>

cart-weblogic-ejb-jar.xml...<weblogic-ejb-jar>

<weblogic-enterprise-bean><ejb-name>ShoppingCart</ejb-name><stateful-session-descriptor>

<stateful-session-cache><max-beans-in-cache>1000</max-beans-in-cache><idle-timeout-seconds>600</idle-timeout-seconds><cache-type>NRU</cache-type>

</stateful-session-cache><persistent-store-dir>/passive-dir</persistent-store-dir>

</stateful-session-descriptor><jndi-name>cart</jndi-name>

</weblogic-enterprise-bean></weblogic-ejb-jar>

Page 47: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 104 Rev 2.1.1 © 2003 ITCourseware, LLC

An HttpSession object can maintain conversational state for a stateless sessionbean.

The HttpSession object must be accessed from a servlet or JSP.

A session ID is held in a cookie in the client browser.

If your client doesn’t accept cookies, you can perform URLrewriting.

The HttpSession object is held inside the web container.

The HttpSession object is usually dependent on the implementation.

All of the servlets and JSP pages within that HTTP session share thesession object.

The HttpSession object holds more than conversational state: it holds state forthe entire session.

Depending upon the implementation, many application servers provideredundancy for the HttpSession object in an abstract environment.

The HttpSession object may survive server crashes (but this is not stated in theJ2EE Specification).

You can push state information all the way back to the client browser withcookies or hidden fields.

HttpSessions and Cookies

Page 48: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 5 Session Beans

© 2003 ITCourseware, LLC Rev 2.1.1 Page 105

Page 49: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 106 Rev 2.1.1 © 2003 ITCourseware, LLC

Create a stateless session bean to implement your Inventory interface. Compile and deploythe bean.(Solution: InventoryEJB.java)

Write a client application that first prints out the current inventory, then adds automobiles and,finally, displays the entire inventory. When running the client application multiple times, is theinventory re-initialized? Why or why not?(Solutions: build.xml, InventoryClient.java, Inventory.txt, ejb-jar.xml, weblogic-ejb-jar.xml)

Change the state of your bean from stateless to stateful.(Solutions: build2.xml, InventoryEJB2.java, InventoryHome2.java, InventoryClient2.java,ejb-jar2.xml, weblogic-ejb-jar2.xml)

Labs

Page 50: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 5 Session Beans

© 2003 ITCourseware, LLC Rev 2.1.1 Page 107

Page 51: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 12 EJB Security

© 2003 ITCourseware, LLC Rev 2.1.1 Page 241

Chapter 12 - EJB Security

Objectives

Use role-driven access control.

Use the java.security.Principalobject.

Add security attributes to a bean'sdeployment descriptor.

Page 52: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 242 Rev 2.1.1 © 2003 ITCourseware, LLC

There are three kinds of security in Enterprise JavaBeans.

Authentication is the process that determines the validity of the user tryingto access a protected resource.

Authorization takes place once the user is logged into the system and thesystem determines which resources the user can access.

Secure Communications are ensured by encrypted data transfer betweenclient and server.

Secure HTTP (HTTPS) is the protocol that is used for datacommunications between the web server and the client.

HTTPS is not a part of the EJB Specification, but Weblogicsupports SSL version 3 through the web browser.

- WebLogic's t3s protocol can be used between app servers.

Security Issues

Page 53: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 12 EJB Security

© 2003 ITCourseware, LLC Rev 2.1.1 Page 243

WebLogic resources that can be secured include:

eventsservletsJDBC connection poolsJMS destinationsJNDI contextsconnectionssocketsfilesenterprise applications and resources, such as databasesEJBs

Page 54: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 244 Rev 2.1.1 © 2003 ITCourseware, LLC

The J2EE authentication service determines the identity and validity of a user byquerying the user id and password.

J2EE authentication service is a security realm that is separate from the operatingsystem.

A security realm is an environment that shares a common set of securitypolicies and users.

There are two realms within the J2EE authentication service:

Certificate realm is used to authenticate web browser clients when usingthe HTTPS protocol.

Authentication of a user (the browser) in the certificate realm is viaan X509 certificate.

In the file realm, users and groups are defined in the application serverenvironment.

WebLogic provides a default realm called myrealm.

myrealm information is contained in an embedded LDAP server.

You can edit the realm through the WebLogic server console.

Authentication

Page 55: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 12 EJB Security

© 2003 ITCourseware, LLC Rev 2.1.1 Page 245

Page 56: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 246 Rev 2.1.1 © 2003 ITCourseware, LLC

The process that determines whether a J2EE user has permission to accessmethods of an enterprise bean uses both physical and logical identity.

The physical identity of a user and group is defined in the operatingenvironment of the application server.

The logical identity of the user is defined in the deployment descriptor ofthe application by the Application Assembler.

Users and groups are mapped to roles at deployment time by the Deployer.

By keeping the physical and logical identities separate, the application isportable across different operating environments.

The authorization process begins when a user logs in to the system and iswrapped by an object that implements the java.security.Principal interface(contained in the EJBContext).

The Principal must be assigned at least one role that has permission toinvoke the method.

The Principal is propagated to all method calls and subsequent methodcalls.

Authorization

Page 57: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 12 EJB Security

© 2003 ITCourseware, LLC Rev 2.1.1 Page 247

Define physical identities in the WebLogic server console.

Define logical identities (roles) in the ejb-jar.xml deployment descriptor.

Link a physical identity to a logical identity with a <security-role-assignment> in theweblogic-ejb-jar.xml deployment descriptor.

When a user tries to invoke a method on a protected resource, the WebLogic server performsthe following to ensure the user is authenticated and has the required authority:

1. If the user is not already authenticated, authentication is requested. If the user fails theauthentication request, it is rejected.

2. WebLogic examines its security policies to determine if the set of required permissions for theresource is granted to the user.

3. If the user has the required permission, the user is allowed to invoke the method. Otherwise, therequest is rejected.

Page 58: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 248 Rev 2.1.1 © 2003 ITCourseware, LLC

Servlets are among the protected resources within WebLogic server.

To secure a servlet, define a <security-constraint> within the web.xmldeployment descriptor.

The <security-constraint> links a resource to a role.

You must also define a <security-role> in the web.xml file.

Logical roles are mapped to physical principals in the<security-role-assignment> of the weblogic.xml deployment descriptor.

The <login-config> element specifies the authentication mechanism for theapplication.

J2EE supports standard browser authentication, HTML formauthentication and certificate authentication.

Securing Web Applications

Page 59: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 12 EJB Security

© 2003 ITCourseware, LLC Rev 2.1.1 Page 249

You can secure a web application with entries in the web.xml and weblogic.xml deploymentdescriptors:

web.xml...

<login-config><auth-method>BASIC</auth-method>

</login-config><security-role>

<role-name>manager</role-name></security-role>

<ejb-ref><ejb-ref-name>ejb/Converter</ejb-ref-name><ejb-ref-type>Session</ejb-ref-type><home>CurrencyConverterHome</home><remote>CurrencyConverter</remote><ejb-link>CurrencyConverterBean</ejb-link>

</ejb-ref></web-app>

weblogic.xml...

<security-role-assignment><role-name>manager</role-name><principal-name>SalesManagers</principal-name>

</security-role-assignment></weblogic-web-app>

Page 60: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 250 Rev 2.1.1 © 2003 ITCourseware, LLC

The Application Assembler defines security roles, determines the methods thatthe role is authorized to invoke, and maps roles to role references.

Use the <security-role> tag to define a role.

It can contain an optional <description> sub-element.

The <security-role> must have a <role-name> sub-element defined.

There must be a corresponding <security-role-assignment> in theweblogic-ejb-jar.xml file.

Methods the security role has permission to invoke are declared within the<method-permission> elements of the deployment descriptor.

The <role-name> sub-element maps to the role name of thecorresponding security role definition.

One or more <method> tag pairs define which methods can be called bythis role.

The <method> tag contains the following sub-elements:

<ejb-name>: name of the enterprise bean.

<method-name>: name of the method the role has permission toinvoke.

To specify all methods, use an asterisk (*).

Use the method name to specify an individual method.

Security and Deployment Descriptor

Page 61: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 12 EJB Security

© 2003 ITCourseware, LLC Rev 2.1.1 Page 251

Try it:

You can build the CurrencyConverter application with build.xml. Deploy Converter.ear and test itby accessing http://localhost:7001/converter/converter.

ejb-jar.xml...<ejb-jar>

<enterprise-beans><session>

<ejb-name>CurrencyConverterBean</ejb-name>...

</session></enterprise-beans><assembly-descriptor>

<security-role><role-name>mgr</role-name>

</security-role><method-permission>

<role-name>mgr</role-name><method>

<ejb-name>CurrencyConverterBean</ejb-name><method-name>*</method-name>

</method></method-permission>

</assembly-descriptor></ejb-jar>

weblogic-ejb-jar.xml...<weblogic-ejb-jar>

...<security-role-assignment>

<role-name>mgr</role-name><principal-name>SalesManagers</principal-name>

</security-role-assignment></weblogic-ejb-jar>

Page 62: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 252 Rev 2.1.1 © 2003 ITCourseware, LLC

By managing security directly in the code, the Bean Provider can control securitywithout re-deploying the enterprise bean.

Since the logic that controls bean security is in the code, access can bedetermined based upon a dynamic parameter.

Using Bean-Managed Security (BMS), parameters such as time ofday, state of another object and the value of an attribute candetermine whether a Principal is granted access to a resource.

State-based security uses the java.security.Principal object to represent auser, group, or other identity in the operating environment of theapplication server.

The EJBContext object invokes security methods.

getCallerPrincipal() determines the physical identity (user, group,smart card, etc.) of the Principal.

isCallerInRole() determines if the Principal is in a role that isauthorized to invoke a protected method.

Bean-Managed Security

Page 63: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 12 EJB Security

© 2003 ITCourseware, LLC Rev 2.1.1 Page 253

Get the Principal object:

EJBContext context;...Principal thePrincipal = context.getCallerPrincipal();

Get the user id of the Principal:

String userName = context.getCallerPrincipal().getName();

Determine if the Principal is assigned a role authorized to invoke the method. The role name passedto isCallerInRole is the one that was defined by the Bean Provider.

boolean isInRole = context.isCallerInRole("Level1");

Page 64: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 254 Rev 2.1.1 © 2003 ITCourseware, LLC

The Bean Provider defines the <security-role-ref> to aid the ApplicationAssembler when identifying the security roles of the application.

It contains the following tag pairs:

<description> : an optional description of the role reference.

<role-name> : the name of the security role reference.

Since the Bean Provider may be a third party, the <role-name> ofthe <security-role-ref> may not match the <role-name> of the<security-role> tag pair.

<role-link> : the <role-name> of the security role that this security rolereference is linking to.

It must be present even if the <role-name> of the security rolereference is the same as the <role-name> of the <security-role>tag pair.

The <role-link> value is typically written by the ApplicationAssembler.

Bean-Managed Security and DeploymentDescriptor

Page 65: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 12 EJB Security

© 2003 ITCourseware, LLC Rev 2.1.1 Page 255

ejb-jar2.xml...<ejb-jar>

<display-name>SalesPersonJAR</display-name><enterprise-beans>

<entity><display-name>SalesPersonEJB</display-name><ejb-name>SalesPersonEJB</ejb-name><home>SalesPersonHome</home><remote>SalesPerson</remote><ejb-class>SalesPersonEJB</ejb-class><persistence-type>Bean</persistence-type><prim-key-class>java.lang.Integer</prim-key-class><security-role-ref>

<role-name>Level1</role-name><role-link>dealer</role-link>

</security-role-ref></entity>

</enterprise-beans><assembly-descriptor>

<security-role><description>A dealer at the dealership</description><role-name>dealer</role-name>

</security-role></assembly-descriptor>

</ejb-jar>

(Use the <method-params> tag pair to distinguish between methods that are overloaded.)

Page 66: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Enterprise JavaBeans Using BEA WebLogic

Page 256 Rev 2.1.1 © 2003 ITCourseware, LLC

Using the WebLogic server console, create a new user named "Jim" with a password of"password9" in the "staff" group.

Modify the SalesPerson bean source in the chapter directory by adding an accessor methodcalled getPrincipal(). This method should return the account used by the container to accessyour bean methods.(Solutions: SalesPerson.java, SalesPersonHome.java, SalesPersonEJB.java)

Write the deployment descriptors for the SalesPerson bean as an entity bean with container-managed persistence. Set up the security roles to give the "staff" account access to the find andget methods in your bean.(Solutions: ejb-jar.xml, weblogic-ejb-jar.xml, weblogic-cmp-jar.xml)

Compile SalesPersonServlet.java and deploy it with the EJB as an enterprise application inyour app server. Run the client from your browser. When prompted for a username/passwordpair, type in "Jim" for the username and "password9" for the password. Verify that the servletruns successfully.(Solutions: build.xml, application.xml, web.xml, weblogic.xml)

Modify SalesPersonServlet.java to call the getPrincipal() method. Display the contents for atleast one of the bean objects. Redeploy the application and run it again.(Solutions: SalesPersonServlet.java)

Labs

Page 67: Enterprise JavaBeans Using BEA WebLogic - · PDF fileChapter 2 Servlet Basics ... Enterprise JavaBeans Using BEA WebLogic ... transaction management and application server functionality

Chapter 12 EJB Security

© 2003 ITCourseware, LLC Rev 2.1.1 Page 257