Dec. 4, 2008, 4:30 a.m.
posted by maxidax
A Simple SAAJ ExampleThe best way to learn SAAJ is to jump right in and build a simple SOAP message using the API. Listing 13-1 shows the BookQuote request message you've seen before. -1 A Simple SOAP Message
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:mh="http://www.Monson-Haefel.com/jwsbook/BookQuote">
<soap:Body>
<mh:getBookPrice>
<isbn>0321146182</isbn>
</mh:getBookPrice>
</soap:Body>
</soap:Envelope>
SaajExample_1 in Listing 13-2 uses the SAAJ API to create the SOAP message, which is semantically equivalent to the SOAP message shown in Listing 13-1. -2 Using SAAJ to Create a Simple SOAP Message
package com.jwsbook.saaj;
import javax.xml.soap.*;
public class SaajExample_1 {
public static void main(String [] args) throws SOAPException{
MessageFactory msgFactory = MessageFactory.newInstance();
SOAPMessage message = msgFactory.createMessage();
message.getSOAPHeader().detachNode();
SOAPBody body = message.getSOAPBody();
SOAPElement getBookPrice = body.addChildElement(
"getBookPrice",
"mh",
"http://www.Monson-Haefel.com/jwsbook/BookQuote");
getBookPrice.setEncodingStyle(SOAPConstants.URI_NS_SOAP_ENCODING);
SOAPElement isbn = getBookPrice.addChildElement("isbn");
isbn.addTextNode("0321146182");
SaajOutputter.writeToScreen(message);
}
}
To run SaajExample_1 and the rest of the examples in this book, you'll need to have a J2EE platform installed, the proper classpaths set up, and supporting Web services deployed. You'll know if SaajExample_1 is working properly by the lack of error messages—if there is a problem a SOAPException will be thrown and displayed on the output screen. The rest of this chapter will use SaajExample_1 and similar examples to discuss the SAAJ API and how to use its various classes and interfaces. Although you will frequently use the SAAJ API inside J2EE message handlers for JAX-RPC service endpoints and EJB endpoints, the examples in this chapter are standalone applications. This approach spares you the arduous process of deploying a J2EE component every time you want to test an example. |
- Comment