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

Overview of SAAJ

SAAJ Messages

The Structure of an XML Document

What Is in a Message?

SAAJ and DOM

SAAJ Connections

SOAPConnection Objects

SAAJ Tutorial

Creating and Sending a Simple Message

Creating a Message

Parts of a Message

Accessing Elements of a Message

Adding Content to the Body

Getting aSOAPConnection Object

Sending a Message

Getting the Content of a Message

Adding Content to the Header

Adding Content to theSOAPPart Object

Adding a Document to the SOAP Body

Manipulating Message Content Using SAAJ or DOM APIs

Adding Attachments

Creating anAttachmentPart Object and Adding Content

Accessing anAttachmentPart Object

Adding Attributes

Header Attributes

Using SOAP Faults

Overview of SOAP Faults

Creating and Populating aSOAPFault Object

Retrieving Fault Information

Code Examples

Request Example

Header Example

Building and Running the Header Example

DOM and DOMSource Examples

Examining theDOMExample Class

Examining theDOMSrcExample Class

Building and Running the DOM and DOMSource Examples

Attachments Example

Building and Running the Attachments Example

SOAP Fault Example

Building and Running the SOAP Fault Example

Further Information about SAAJ

Part IV Enterprise Beans

20.  Enterprise Beans

21.  Getting Started with Enterprise Beans

22.  Session Bean Examples

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

Code Examples

The first part of this tutorial uses code fragments to walk youthrough the fundamentals of using the SAAJ API. In this section, you willuse some of those code fragments to create applications. First, you will seethe programRequest.java. Then you will see how to run the programsHeaderExample.java,DOMExample.java,DOMSrcExample.java,Attachments.java, andSOAPFaultTest.java.


Note -Before you run any of the examples, follow the preliminary setup instructions inBuilding the Examples.


Request Example

The classRequest puts together the code fragments used in the sectionSAAJ Tutorialand adds what is needed to make it a complete example of aclient sending a request-response message. In addition to putting all the code together,it addsimport statements, amain method, and atry/catch block with exception handling.

import javax.xml.soap.*;import javax.xml.namespace.QName;import java.util.Iterator;import java.net.URL;public class Request {    public static void main(String[] args)    {        try {            SOAPConnectionFactory soapConnectionFactory =                SOAPConnectionFactory.newInstance();            SOAPConnection connection =                soapConnectionFactory.createConnection();            MessageFactory factory = MessageFactory.newInstance();            SOAPMessage message = factory.createMessage();            SOAPHeader header = message.getSOAPHeader();            SOAPBody body = message.getSOAPBody();            header.detachNode();            QName bodyName = new QName("http://wombat.ztrade.com",                "GetLastTradePrice", "m");            SOAPBodyElement bodyElement = body.addBodyElement(bodyName);            QName name = new QName("symbol");            SOAPElement symbol = bodyElement.addChildElement(name);            symbol.addTextNode("SUNW");            URL endpoint = new URL("http://wombat.ztrade.com/quotes");            SOAPMessage response = connection.call(message, endpoint);            connection.close();            SOAPBody soapBody = response.getSOAPBody();            Iterator iterator = soapBody.getChildElements(bodyName);            bodyElement = (SOAPBodyElement)iterator.next();            String lastPrice = bodyElement.getValue();            System.out.print("The last price for SUNW is ");            System.out.println(lastPrice);        } catch (Exception ex) {            ex.printStackTrace();        }    }}

For theRequest class to be runnable, the second argument supplied to thecall method would have to be a valid existing URI, and this isnot true in this case.

Header Example

The exampleHeaderExample.java, based on the code fragments in the sectionAdding Attributes, creates amessage that has several headers. It then retrieves the contents of the headersand prints them. The example generates either a SOAP 1.1 message or aSOAP 1.2 message, depending on arguments you specify. You will find the codeforHeaderExample in the following directory:

tut-install/javaeetutorial5/examples/saaj/headers/src/
Building and Running the Header Example

To build the program using NetBeans IDE, follow these steps:

  1. In NetBeans IDE, choose Open Project from the File menu.

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

  3. Select theheaders folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

    A Reference Problems dialog appears. Click Close.

  6. Right-click theheaders project and choose Resolve Reference Problems.

  7. In the Resolve Reference Problems dialog, select the first of the missing JAR files and click Resolve.

    The missing files areactivation.jar,javaee.jar, andappserv-ws.jar.

  8. Navigate to theas-install/lib/ directory.

  9. Select the missing JAR file (activation.jar, for example) and click Open.

    In the Resolve Reference Problems dialog, all the files have green check marks to the left of their names.

  10. Click Close.

  11. Right-click the project and choose Build.

To run the program using NetBeans IDE, follow these steps:

  1. Right-click theheaders project and choose Properties.

  2. Select Run from the Categories tree.

  3. In the Arguments field, type the following:

    1.1

    This argument specifies the version of SOAP to be used in generating the message.

  4. Click OK.

  5. Right-click the project and choose Run.

  6. Right-click the project and choose Properties.

  7. Select Run from the Categories tree.

  8. In the Arguments field, type the following:

    1.2
  9. Click OK.

  10. Right-click the project and choose Run.

To build and run HeaderExample using Ant, go to the directorytut-install/javaeetutorial5/examples/saaj/headers/.Use one of the following commands:

ant run-headers -Dsoap=1.1
ant run-headers -Dsoap=1.2

When you run HeaderExample to generate a SOAP 1.1 message, you will seeoutput similar to the following:

----- Request Message ----<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header><ns:orderDesk xmlns:ns="http://gizmos.com/NSURI" SOAP-ENV:actor="http://gizmos.com/orders"/><ns:shippingDesk xmlns:ns="http://gizmos.com/NSURI" SOAP-ENV:actor="http://gizmos.com/shipping"/><ns:confirmationDesk xmlns:ns="http://gizmos.com/NSURI" SOAP-ENV:actor="http://gizmos.com/confirmations" SOAP-ENV:mustUnderstand="1"/><ns:billingDesk xmlns:ns="http://gizmos.com/NSURI" SOAP-ENV:actor="http://gizmos.com/billing"/></SOAP-ENV:Header><SOAP-ENV:Body/></SOAP-ENV:Envelope>Header name is {http://gizmos.com/NSURI}orderDeskActor is http://gizmos.com/ordersmustUnderstand is falseHeader name is {http://gizmos.com/NSURI}shippingDeskActor is http://gizmos.com/shippingmustUnderstand is falseHeader name is {http://gizmos.com/NSURI}confirmationDeskActor is http://gizmos.com/confirmationsmustUnderstand is trueHeader name is {http://gizmos.com/NSURI}billingDeskActor is http://gizmos.com/billingmustUnderstand is false

When you run HeaderExample to generate a SOAP 1.2 message, you will seeoutput similar to the following:

----- Request Message ----<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"><env:Header><ns:orderDesk xmlns:ns="http://gizmos.com/NSURI"  env:role="http://gizmos.com/orders"/><ns:shippingDesk xmlns:ns="http://gizmos.com/NSURI" env:role="http://gizmos.com/shipping"/><ns:confirmationDesk xmlns:ns="http://gizmos.com/NSURI" env:mustUnderstand="true" env:role="http://gizmos.com/confirmations"/><ns:billingDesk xmlns:ns="http://gizmos.com/NSURI" env:relay="true" env:role="http://gizmos.com/billing"/></env:Header><env:Body/></env:Envelope>Header name is {http://gizmos.com/NSURI}orderDeskRole is http://gizmos.com/ordersmustUnderstand is falserelay is falseHeader name is {http://gizmos.com/NSURI}shippingDeskRole is http://gizmos.com/shippingmustUnderstand is falserelay is falseHeader name is {http://gizmos.com/NSURI}confirmationDeskRole is http://gizmos.com/confirmationsmustUnderstand is truerelay is falseHeader name is {http://gizmos.com/NSURI}billingDeskRole is http://gizmos.com/billingmustUnderstand is falserelay is true

DOM and DOMSource Examples

The examplesDOMExample.java andDOMSrcExample.java show how to add a DOM documentto a message and then traverse its contents. They show two ways todo this:

  • DOMExample.java creates a DOM document and adds it to the body of a message.

  • DOMSrcExample.java creates the document, uses it to create aDOMSource object, and then sets theDOMSource object as the content of the message’s SOAP part.

You will find the code forDOMExample andDOMSrcExample in the followingdirectory:

tut-install/javaeetutorial5/examples/saaj/dom/src/
Examining theDOMExample Class

DOMExample first creates a DOM document by parsing an XML document. The fileit parses is one that you specify on the command line.

static Document document;...    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();    factory.setNamespaceAware(true);    try {        DocumentBuilder builder = factory.newDocumentBuilder();        document = builder.parse( new File(args[0]) );        ...

Next, the example creates a SOAP message in the usual way. Thenit adds the document to the message body:

        SOAPBodyElement docElement = body.addDocument(document);

This example does not change the content of the message. Instead, it displaysthe message content and then uses a recursive method,getContents, to traversethe element tree using SAAJ APIs and display the message contents in areadable form.

public void getContents(Iterator iterator, String indent) {    while (iterator.hasNext()) {        Node node = (Node) iterator.next();        SOAPElement element = null;        Text text = null;        if (node instanceof SOAPElement) {            element = (SOAPElement)node;            QName name = element.getElementQName();            System.out.println(indent + "Name is " + name.toString());            Iterator attrs = element.getAllAttributesAsQNames();            while (attrs.hasNext()){                QName attrName = (QName)attrs.next();                System.out.println(indent + " Attribute name is " +                     attrName.toString());                System.out.println(indent + " Attribute value is " +                     element.getAttributeValue(attrName));            }            Iterator iter2 = element.getChildElements();            getContents(iter2, indent + " ");        } else {            text = (Text) node;            String content = text.getValue();            System.out.println(indent + "Content is: " + content);            }        }    }
Examining theDOMSrcExample Class

DOMSrcExample differs fromDOMExample in only a few ways. First, after it parsesthe document,DOMSrcExample uses the document to create aDOMSource object. This codeis the same as that ofDOMExample except for the last line:

    static DOMSource domSource;    ...    try {        DocumentBuilder builder = factory.newDocumentBuilder();        Document document = builder.parse(new File(args[0]));        domSource = new DOMSource(document);        ...

Then, afterDOMSrcExample creates the message, it does not get the header andbody and add the document to the body, asDOMExample does. Instead,DOMSrcExample gets the SOAP part and sets theDOMSource object as its content:

// Create a messageSOAPMessage message = messageFactory.createMessage();// Get the SOAP part and set its content to domSourceSOAPPart soapPart = message.getSOAPPart();soapPart.setContent(domSource);

The example then uses thegetContents method to obtain the contents of boththe header (if it exists) and the body of the message.

The most important difference between these two examples is the kind of documentyou can use to create the message. BecauseDOMExample adds the document tothe body of the SOAP message, you can use any valid XMLfile to create the document. But becauseDOMSrcExample makes the document the entire contentof the message, the document must already be in the form of avalid SOAP message, and not just any XML document.

Building and Running the DOM and DOMSource Examples

When you runDOMExample andDOMSrcExample, you can specify one of twosample XML files in the directorytut-install/javaeetutorial5/examples/saaj/dom/:

  • slide.xml, a file that consists only of a message body

  • domsrc.xml, an example that has a SOAP header (the contents of theHeaderExample SOAP 1.1 output) and the same message body asslide.xml

You can use either of these files when you runDOMExample. You canusedomsrc.xml to runDOMSrcExample.

To build the programs using NetBeans IDE, follow these steps:

  1. In NetBeans IDE, choose Open Project from the File menu.

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

  3. Select thedom folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

    A Reference Problems dialog appears. Click Close.

  6. Right-click thedom project and choose Resolve Reference Problems.

  7. In the Resolve Reference Problems dialog, select the first of the missing JAR files and click Resolve.

    The missing files areactivation.jar,javaee.jar, andappserv-ws.jar.

  8. Navigate to theas-install/lib/ directory.

  9. Select the missing JAR file (activation.jar, for example) and click Open.

    In the Resolve Reference Problems dialog, all the files have green check marks to the left of their names.

  10. Click Close.

  11. Right-click the project and choose Build.

To runDOMExample using NetBeans IDE, follow these steps:

  1. Right-click thedom project and choose Properties.

  2. Select Run from the Categories tree.

  3. Click Browse next to the Main Class field.

  4. In the Browse Main Classes dialog, selectDomExample.

  5. Click Select Main Class.

  6. In the Arguments field, type the following:

    slide.xml
  7. Click OK.

  8. Right-click the project and choose Run.

To runDOMSrcExample using NetBeans IDE, follow these steps:

  1. Right-click thedom project and choose Properties.

  2. Select Run from the Categories tree.

  3. Click Browse next to the Main Class field.

  4. In the Browse Main Classes dialog, selectDomSrcExample.

  5. Click Select Main Class.

  6. In the Arguments field, type the following:

    domsrc.xml
  7. Click OK.

  8. Right-click the project and choose Run.

To run the examples using Ant, go to the directorytut-install/javaeetutorial5/examples/saaj/dom/.

To runDOMExample using Ant, use the following command:

ant run-dom -Dxml-file=slide.xml

To runDOMSrcExample using Ant, use the following command:

ant run-domsrc -Dxml-file=domsrc.xml

When you runDOMExample using the fileslide.xml, you will see outputthat begins like the following:

     Running DOMExample.     Name is slideshow      Attribute name is author      Attribute value is Yours Truly      Attribute name is date      Attribute value is Date of publication      Attribute name is title      Attribute value is Sample Slide Show      Content is: ...

When you runDOMSrcExample using the filedomsrc.xml, you will see outputthat begins like the following:

     Running DOMSrcExample.     Header contents:     Content is:      Name is {http://gizmos.com/NSURI}orderDesk      Attribute name is SOAP-ENV:actor      Attribute value is http://gizmos.com/orders     Content is:     ...

If you runDOMSrcExample with the fileslide.xml, you will see runtimeerrors.

Attachments Example

The exampleAttachments.java, based on the code fragments in the sectionsCreating anAttachmentPart Object and Adding Content andAccessing anAttachmentPart Object, creates a message that has a text attachment and an image attachment.It then retrieves the contents of the attachments and prints the contents ofthe text attachment. You will find the code for theAttachments class inthe following directory:

tut-install/javaeetutorial5/examples/saaj/attachments/src/

Attachments first creates a message in the usual way. It then creates anAttachmentPart for the text attachment:

AttachmentPart attachment1 = message.createAttachmentPart();

After it reads input from a file into a string namedstringContent,it sets the content of the attachment to the value of thestring and the type totext/plain and also sets a content ID.

attachment1.setContent(stringContent, "text/plain");attachment1.setContentId("attached_text");

It then adds the attachment to the message:

message.addAttachmentPart(attachment1);

The example uses ajavax.activation.DataHandler object to hold a reference to the graphicthat constitutes the second attachment. It creates this attachment using the form ofthecreateAttachmentPart method that takes aDataHandler argument.

// Create attachment part for imageURL url = new URL("file:///../xml-pic.jpg");DataHandler dataHandler = new DataHandler(url);AttachmentPart attachment2 = message.createAttachmentPart(dataHandler);attachment2.setContentId("attached_image");message.addAttachmentPart(attachment2);

The example then retrieves the attachments from the message. It displays thecontentIdandcontentType attributes of each attachment and the contents of the text attachment.

Building and Running the Attachments Example

TheAttachments class takes a text file as an argument. You can specifyany text file. Theattachments directory contains a file namedaddr.txt that youcan use.

To build the program using NetBeans IDE, follow these steps:

  1. In NetBeans IDE, choose Open Project from the File menu.

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

  3. Select theattachments folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

    A Reference Problems dialog appears. Click Close.

  6. Right-click theattachments project and choose Resolve Reference Problems.

  7. In the Resolve Reference Problems dialog, select the first of the missing JAR files and click Resolve.

    The missing files areactivation.jar,javaee.jar, andappserv-ws.jar.

  8. Navigate to theas-install/lib/ directory.

  9. Select the missing JAR file (activation.jar, for example) and click Open.

    In the Resolve Reference Problems dialog, all the files have green check marks to the left of their names.

  10. Click Close.

  11. Right-click the project and choose Build.

To run the program using NetBeans IDE, follow these steps:

  1. Right-click theattachments project and choose Properties.

  2. Select Run from the Categories tree.

  3. In the Arguments field, type the name of a text file:

    addr.txt
  4. Click OK.

  5. Right-click the project and choose Run.

To runAttachments using Ant, go to the directorytut-install/javaeetutorial5/examples/saaj/attachments/. Use thefollowing command:

ant run-att -Dfile=path-name

Specify a text file as thepath-name argument:

ant run-att -Dfile=addr.txt

When you runAttachments using this file, you will see output like thefollowing:

Running Attachments.Attachment attached_text has content type text/plainAttachment contains:Update address for Sunny Skies, Inc., to10 Upbeat StreetPleasant Grove, CA 95439USAAttachment attached_image has content type image/jpeg

SOAP Fault Example

The exampleSOAPFaultTest.java, based on the code fragments in the sectionsCreating and Populating aSOAPFault Object andRetrieving Fault Information, creates a message that has aSOAPFault object. It then retrieves thecontents of theSOAPFault object and prints them. You will find the codeforSOAPFaultTest in the following directory:

tut-install/javaeetutorial5/examples/saaj/fault/src/

LikeHeaderExample, theSOAPFaultTest class contains code that allows you to generate eithera SOAP 1.1 or a SOAP 1.2 message.

Building and Running the SOAP Fault Example

To build the program using NetBeans IDE, follow these steps:

  1. In NetBeans IDE, choose Open Project from the File menu.

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

  3. Select thefault folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

    A Reference Problems dialog appears. Click Close.

  6. Right-click thefault project and choose Resolve Reference Problems.

  7. In the Resolve Reference Problems dialog, select the first of the missing JAR files and click Resolve.

    The missing files areactivation.jar,javaee.jar, andappserv-ws.jar.

  8. Navigate to theas-install/lib/ directory.

  9. Select the missing JAR file (activation.jar, for example) and click Open.

    In the Resolve Reference Problems dialog, all the files have green check marks to the left of their names.

  10. Click Close.

  11. Right-click the project and choose Build.

To run the program using NetBeans IDE, follow these steps:

  1. Right-click thefault project and choose Properties.

  2. Select Run from the Categories tree.

  3. In the Arguments field, type the following:

    1.1

    This argument specifies the version of SOAP to be used in generating the message.

  4. Click OK.

  5. Right-click the project and choose Run.

  6. Right-click the project and choose Properties.

  7. Select Run from the Categories tree.

  8. In the Arguments field, type the following:

    1.2
  9. Click OK.

  10. Right-click the project and choose Run.

To build and runSOAPFaultTest using Ant, go to the directorytut-install/javaeetutorial5/examples/saaj/fault/. Use oneof the following commands:

ant run-fault -Dsoap=1.1
ant run-fault -Dsoap=1.2

When you runSOAPFaultTest to generate a SOAP 1.1 message, you will seeoutput like the following (line breaks have been inserted in the message forreadability):

Here is what the XML message looks like:<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>SOAP-ENV:Client</faultcode><faultstring>Message does not have necessary info</faultstring><faultactor>http://gizmos.com/order</faultactor><detail><PO:order xmlns:PO="http://gizmos.com/orders/">Quantity element does not have a value</PO:order><PO:confirmation xmlns:PO="http://gizmos.com/confirm">Incomplete address: no zip code</PO:confirmation></detail></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>SOAP fault contains: Fault code = {http://schemas.xmlsoap.org/soap/envelope/}Client Local name = Client Namespace prefix = SOAP-ENV, bound to http://schemas.xmlsoap.org/soap/envelope/ Fault string = Message does not have necessary info Fault actor = http://gizmos.com/order Detail entry = Quantity element does not have a value Detail entry = Incomplete address: no zip code

When you run SOAPFaultTest to generate a SOAP 1.2 message, the output lookslike this:

Here is what the XML message looks like:<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"><env:Header/><env:Body><env:Fault><env:Code><env:Value>env:Sender</env:Value></env:Code><env:Reason><env:Text xml:lang="en-US">Message does not have necessary info</env:Text></env:Reason><env:Role>http://gizmos.com/order</env:Role><env:Detail><PO:order xmlns:PO="http://gizmos.com/orders/">Quantity element does not have a value</PO:order><PO:confirmation xmlns:PO="http://gizmos.com/confirm">Incomplete address: no zip code</PO:confirmation></env:Detail></env:Fault></env:Body></env:Envelope>SOAP fault contains: Fault code = {http://www.w3.org/2003/05/soap-envelope}Sender Local name = Sender Namespace prefix = env, bound to http://www.w3.org/2003/05/soap-envelope Fault reason text = Message does not have necessary info Fault role = http://gizmos.com/order Detail entry = Quantity element does not have a value Detail entry = Incomplete address: no zip code
PreviousContentsNext

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


[8]ページ先頭

©2009-2025 Movatter.jp