Movatterモバイル変換


[0]ホーム

URL:


Document Information

Preface

Part I Introduction

1.  Overview

2.  Using the Tutorial Examples

Part II The Web Tier

3.  Getting Started with Web Applications

4.  Java Servlet Technology

5.  JavaServer Pages Technology

6.  JavaServer Pages Documents

7.  JavaServer Pages Standard Tag Library

8.  Custom Tags in JSP Pages

9.  Scripting in JSP Pages

10.  JavaServer Faces Technology

11.  Using JavaServer Faces Technology in JSP Pages

12.  Developing with JavaServer Faces Technology

13.  Creating Custom UI Components

14.  Configuring JavaServer Faces Applications

15.  Internationalizing and Localizing Web Applications

Part III Web Services

16.  Building Web Services with JAX-WS

17.  Binding between XML Schema and Java Classes

18.  Streaming API for XML

19.  SOAP with Attachments API for Java

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

Thecart Example

The Business Interface

Session Bean Class

Life-Cycle Callback Methods

Business Methods

The Remove Method

Helper Classes

Building, Packaging, Deploying, and Running thecart Example

Building, Packaging, and Deploying thecart Example Using NetBeans IDE

Running thecart Application Client Using NetBeans IDE

Building, Packaging, and Deploying thecart Example Using Ant

Running thecart Application Client Using Ant

Theall Task

Undeploying thecart Example

A Web Service Example:helloservice

The Web Service Endpoint Implementation Class

Stateless Session Bean Implementation Class

Building, Packaging, Deploying, and Testing thehelloservice Example

Building, Packaging, and Deploying thehelloservice Example Using NetBeans IDE

Building, Packaging, and Deploying thehelloservice Example Using Ant

Testing the Service without a Client

Using the Timer Service

TheTimeout Method

Creating Timers

Canceling and Saving Timers

Getting Timer Information

Transactions and Timers

Thetimersession Example

Building, Packaging, Deploying, and Running thetimersession Example

Building, Packaging, Deploying, and Running thetimersession Example Using NetBeans IDE

Building, Packaging, and Deploying thetimersession Example Using Ant

Running thetimersession Application Client Using Ant

Handling Exceptions

23.  A Message-Driven Bean Example

Part V Persistence

24.  Introduction to the Java Persistence API

25.  Persistence in the Web Tier

26.  Persistence in the EJB Tier

27.  The Java Persistence Query Language

Part VI Services

28.  Introduction to Security in the Java EE Platform

29.  Securing Java EE Applications

30.  Securing Web Applications

31.  The Java Message Service API

32.  Java EE Examples Using the JMS API

33.  Transactions

34.  Resource Connections

35.  Connector Architecture

Part VII Case Studies

36.  The Coffee Break Application

37.  The Duke's Bank Application

Part VIII Appendixes

A.  Java Encoding Schemes

B.  About the Authors

Index

 

The Java EE 5 Tutorial

Java Coffee Cup logo
PreviousContentsNext

Thecart Example

Thecart session bean represents a shopping cart in an online bookstore. Thebean’s client can add a book to the cart, remove a book, orretrieve the cart’s contents. To assemblecart, you need the following code:

  • Session bean class (CartBean)

  • Remote business interface (Cart)

All session beans require a session bean class. All enterprise beans that permitremote access must have a remote business interface. To meet the needs ofa specific application, an enterprise bean may also need some helper classes. TheCartBean session bean uses two helper classes (BookException andIdVerifier) which are discussed inthe sectionHelper Classes.

The source code for this example is in thetut-install/javaeetutorial5/examples/ejb/cart/ directory.

The Business Interface

TheCart business interface is a plain Java interface that defines all thebusiness methods implemented in the bean class. If the bean class implements asingle interface, that interface is assumed to the business interface. The business interfaceis a local interface unless it is annotated with thejavax.ejb.Remote annotation; thejavax.ejb.Localannotation is optional in this case.

The bean class may implement more than one interface. If the beanclass implements more than one interface, either the business interfaces must be explicitly annotatedeither@Local or@Remote, or the business interfaces must be specified by decoratingthe bean class with@Local or@Remote. However, the following interfaces are excluded whendetermining if the bean class implements more than one interface:

  • java.io.Serializable

  • java.io.Externalizable

  • Any of the interfaces defined by thejavax.ejb package

The source code for theCart business interface follows:

package com.sun.tutorial.javaee.ejb;import java.util.List;import javax.ejb.Remote;@Remotepublic interface Cart {    public void initialize(String person) throws BookException;    public void initialize(String person, String id)         throws BookException;    public void addBook(String title);    public void removeBook(String title) throws BookException;    public List<String> getContents();    public void remove();}

Session Bean Class

The session bean class for this example is calledCartBean. Like anystateful session bean, theCartBean class must meet these requirements:

  • The class is annotated@Stateful.

  • The class implements the business methods defined in the business interface.

Stateful session beans also may:

  • Implement the business interface, a plain Java interface. It is good practice to implement the bean’s business interface.

  • Implement any optional life cycle callback methods, annotated@PostConstruct,@PreDestroy,@PostActivate, and@PrePassivate.

  • Implement any optional business methods annotated@Remove.

The source code for theCartBean class follows.

package com.sun.tutorial.javaee.ejb;import java.util.ArrayList;import java.util.List;import javax.ejb.Remove;import javax.ejb.Stateful;@Statefulpublic class CartBean implements Cart {    String customerName;    String customerId;    List<String> contents;    public void initialize(String person) throws BookException {        if (person == null) {            throw new BookException("Null person not allowed.");        } else {            customerName = person;        }        customerId = "0";        contents = new ArrayList<String>();    }    public void initialize(String person, String id)                 throws BookException {        if (person == null) {            throw new BookException("Null person not allowed.");        } else {            customerName = person;        }        IdVerifier idChecker = new IdVerifier();        if (idChecker.validate(id)) {            customerId = id;        } else {            throw new BookException("Invalid id: " + id);        }        contents = new ArrayList<String>();    }    public void addBook(String title) {        contents.add(title);    }    public void removeBook(String title) throws BookException {        boolean result = contents.remove(title);        if (result == false) {            throw new BookException(title + " not in cart.");        }    }    public List<String> getContents() {        return contents;    }    @Remove    public void remove() {        contents = null;    }}
Life-Cycle Callback Methods

Methods in the bean class may be declared as a life-cycle callbackmethod by annotating the method with the following annotations:

  • javax.annotation.PostConstruct

  • javax.annotation.PreDestroy

  • javax.ejb.PostActivate

  • javax.ejb.PrePassivate

Life-cycle callback methods must returnvoid and have no parameters.

@PostConstruct methods are invoked by the container on newly constructed bean instances afterall dependency injection has completed and before the first business method is invokedon the enterprise bean.

@PreDestroy methods are invoked after any method annotated@Remove has completed, and beforethe container removes the enterprise bean instance.

@PostActivate methods are invoked by the container after the container moves the beanfrom secondary storage to active status.

@PrePassivate methods are invoked by the container before the container passivates the enterprisebean, meaning the container temporarily removes the bean from the environment and savesit to secondary storage.

Business Methods

The primary purpose of a session bean is to run business tasks forthe client. The client invokes business methods on the object reference it getsfrom dependency injection or JNDI lookup. From the client’s perspective, the business methodsappear to run locally, but they actually run remotely in the session bean.The following code snippet shows how theCartClient program invokes the businessmethods:

cart.create("Duke DeEarl", "123");...cart.addBook("Bel Canto"); ...List<String> bookList = cart.getContents();...cart.removeBook("Gravity’s Rainbow");

TheCartBean class implements the business methods in the following code:

public void addBook(String title) {   contents.addElement(title);}public void removeBook(String title) throws BookException {   boolean result = contents.remove(title);   if (result == false) {      throw new BookException(title + "not in cart.");   }}public List<String> getContents() {   return contents;}

The signature of a business method must conform to these rules:

  • The method name must not begin withejb to avoid conflicts with callback methods defined by the EJB architecture. For example, you cannot call a business methodejbCreate orejbActivate.

  • The access control modifier must bepublic.

  • If the bean allows remote access through a remote business interface, the arguments and return types must be legal types for the Java RMI API.

  • If the bean is a web service endpoint, the arguments and return types for the methods annotated@WebMethod must be legal types for JAX-WS.

  • The modifier must not bestatic orfinal.

Thethrows clause can include exceptions that you define for your application. TheremoveBook method, for example, throws theBookException if the book is not in thecart.

To indicate a system-level problem, such as the inability to connect to adatabase, a business method should throw ajavax.ejb.EJBException. The container will notwrap application exceptions such asBookException. BecauseEJBException is a subclass ofRuntimeException,you do not need to include it in thethrows clause of thebusiness method.

The Remove Method

Business methods annotated withjavax.ejb.Remove in the stateful session bean class can beinvoked by enterprise bean clients to remove the bean instance. The container willremove the enterprise bean after a@Remove method completes, either normally or abnormally.

InCartBean, theremove method is a@Remove method:

@Removepublic void remove() {    contents = null;}

Helper Classes

TheCartBean session bean has two helper classes:BookException andIdVerifier. TheBookException is thrown by theremoveBook method, and theIdVerifier validates thecustomerId inone of thecreate methods. Helper classes may reside in the EJB JARfile that contains the enterprise bean class, or in an EAR that containsthe EJB JAR.

Building, Packaging, Deploying, and Running thecart Example

You can build, package, deploy, and run thecart application using either NetBeansIDE or the Ant tool.

Building, Packaging, and Deploying thecart Example Using NetBeans IDE

Follow these instructions to build, package, and deploy thecart example to yourApplication Server instance using NetBeans IDE.

  1. In NetBeans IDE, select File→Open Project.

  2. In the Open Project dialog, navigate totut-install/javaeetutorial5/examples/ejb/.

  3. Select thecart folder.

  4. Select the Open as Main Project and Open Required Projects check boxes.

  5. Click Open Project.

  6. In the Projects tab, right-click thecart project and select Undeploy and Deploy.

This builds and packages the application intocart.ear, located intut-install/javaeetutorial5/examples/ejb/cart/dist/, and deploys thisEAR file to your Application Server instance.

Running thecart Application Client Using NetBeans IDE

To runcart’s application client, select Run→Run Main Project. You will see theoutput of the application client in the Output pane:

...Retrieving book title from cart: Infinite JestRetrieving book title from cart: Bel CantoRetrieving book title from cart: Kafka on the ShoreRemoving "Gravity’s Rainbow" from cart.Caught a BookException: "Gravity’s Rainbow" not in cart.Java Result: 1run-cart-app-client:run-nb:BUILD SUCCESSFUL (total time: 14 seconds)
Building, Packaging, and Deploying thecart Example Using Ant

Now you are ready to compile the remote interface (Cart.java), the home interface(CartHome.java), the enterprise bean class (CartBean.java), the client class (CartClient.java), and the helperclasses (BookException.java andIdVerifier.java).

  1. In a terminal window, go to this directory:

    tut-install/javaeetutorial5/examples/ejb/cart/
  2. Type the following command:

    ant

    This command calls thedefault target, which builds and packages the application into an EAR file,cart.ear, located in thedist directory.

  3. Type the following command:

    ant deploy

    cart.ear will be deployed to the Application Server.

Running thecart Application Client Using Ant

When you run the client, the application client container injects any component referencesdeclared in the application client class, in this case the reference to theCart enterprise bean. To run the application client, perform the following steps.

  1. In a terminal window, go to this directory:

    tut-install/javaeetutorial5/examples/ejb/cart/
  2. Type the following command:

    ant run

    This task will retrieve the application client JAR,cartClient.jar and run the application client.cartClient.jar contains the application client class, the helper classBookException, and theCart business interface.

    This is the equivalent of running:

    appclient -client cartClient.jar
  3. In the terminal window, the client displays these lines:

    [echo] running application client container.[exec] Retrieving book title from cart: Infinite Jest[exec] Retrieving book title from cart: Bel Canto[exec] Retrieving book title from cart: Kafka on the Shore[exec] Removing "Gravity’s Rainbow" from cart.[exec] Caught a BookException: "Gravity’s Rainbow" not in cart.[exec] Result: 1
Theall Task

As a convenience, theall task will build, package, deploy, and run theapplication. To do this, enter the following command:

ant all

Undeploying thecart Example

To undeploycart.ear using NetBeans IDE:

  1. Click the Services tab.

  2. Expand the Servers node and locate the Application Server instance to which you deployedcart.

  3. Expand your Application Server instance node, then Applications→Enterprise Applications.

  4. Right-clickcart and select Undeploy.

To undeploycart.ear using Ant, enter the following command:

ant undeploy
PreviousContentsNext

Copyright © 2010, Oracle and/or its affiliates. All rights reserved.Legal Notices


[8]ページ先頭

©2009-2025 Movatter.jp