﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-liuzheng-文章分类-WebService</title><link>http://www.blogjava.net/liuzheng/category/28171.html</link><description /><language>zh-cn</language><lastBuildDate>Fri, 11 Jan 2008 04:05:25 GMT</lastBuildDate><pubDate>Fri, 11 Jan 2008 04:05:25 GMT</pubDate><ttl>60</ttl><item><title>Web Service中有关WSDL的学习心得</title><link>http://www.blogjava.net/liuzheng/articles/174523.html</link><dc:creator>刘铮 </dc:creator><author>刘铮 </author><pubDate>Fri, 11 Jan 2008 02:20:00 GMT</pubDate><guid>http://www.blogjava.net/liuzheng/articles/174523.html</guid><wfw:comment>http://www.blogjava.net/liuzheng/comments/174523.html</wfw:comment><comments>http://www.blogjava.net/liuzheng/articles/174523.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/liuzheng/comments/commentRss/174523.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/liuzheng/services/trackbacks/174523.html</trackback:ping><description><![CDATA[WSDL很重要的几个Elements：<br />
<table class="ex" width="100%" border="1">
    <tbody>
        <tr>
            <td valign="top">&lt;portType&gt;</td>
            <td valign="top">The operations performed by the web service</td>
        </tr>
        <tr>
            <td valign="top">&lt;message&gt;</td>
            <td valign="top">The messages used by the web service</td>
        </tr>
        <tr>
            <td valign="top">&lt;types&gt;</td>
            <td valign="top">The data types used by the web service</td>
        </tr>
        <tr>
            <td valign="top">&lt;binding&gt;</td>
            <td valign="top">The communication protocols used by the web service</td>
        </tr>
    </tbody>
</table>
1.从&lt;service&gt;作为入口，&lt;service&gt;的子元素&lt;address&gt;定义了webservice 的URL&nbsp;&nbsp;&nbsp;，子元素&lt;port&gt;与一个binding相关联<br />
2.在&lt;binding&gt;中定义了跟什么&lt;portType&gt;进行绑定，及其怎样绑定，使用的是rpc还是document，还定义了绑定了哪些方法&lt;operation&gt;,及其方法里面的&lt;input&gt;和&lt;output&gt;的message内容。这里就和&lt;message&gt;相关联了<br />
3.在&lt;message&gt;中使用&lt;part&gt;详细的规定了message中内容。其中内容的规范&lt;type&gt;就和&lt;types&gt;联系起来了<br />
4.&lt;types&gt;主要是定义了具体的schema<br />
<img src ="http://www.blogjava.net/liuzheng/aggbug/174523.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/liuzheng/" target="_blank">刘铮 </a> 2008-01-11 10:20 <a href="http://www.blogjava.net/liuzheng/articles/174523.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>使用spring-ws进行webservice服务器端的开发</title><link>http://www.blogjava.net/liuzheng/articles/170363.html</link><dc:creator>刘铮 </dc:creator><author>刘铮 </author><pubDate>Tue, 25 Dec 2007 09:48:00 GMT</pubDate><guid>http://www.blogjava.net/liuzheng/articles/170363.html</guid><wfw:comment>http://www.blogjava.net/liuzheng/comments/170363.html</wfw:comment><comments>http://www.blogjava.net/liuzheng/articles/170363.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/liuzheng/comments/commentRss/170363.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/liuzheng/services/trackbacks/170363.html</trackback:ping><description><![CDATA[Spring Web Services offer another endpoint with which you can aggregate multiple handling into one<br />
controller, thus grouping functionality together. This model is based on annotations, so you can use it only with<br />
Java 5 and higher. Here is an example that uses the same marshalled objects as above:<br />
package samples;<br />
import org.springframework.ws.server.endpoint.annotation.Endpoint;<br />
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;<br />
@Endpoint<br />
public class AnnotationOrderEndpoint {<br />
&nbsp;&nbsp;&nbsp;&nbsp;private final OrderService orderService;<br />
&nbsp;&nbsp;&nbsp;&nbsp;public AnnotationOrderEndpoint(OrderService orderService) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;this.orderService = orderService;<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;@PayloadRoot(localPart = "orderRequest", namespace = "http://samples")<br />
&nbsp;&nbsp;&nbsp;&nbsp;public Order getOrder(OrderRequest orderRequest) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;return orderService.getOrder(orderRequest.getId());<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;&nbsp;@PayloadRoot(localPart = "order", namespace = "http://samples")<br />
&nbsp;&nbsp;&nbsp;&nbsp;public void order(Order order) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;orderService.createOrder(order);<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}<br />
By annotating the class with @Endpoint, you mark it as a Spring-WS endpoint. Because the endpoint class can<br />
have multiple request handling methods, we need to instruct Spring-WS which method to invoke for which<br />
request. This is done using the @PayloadRoot annotation: the getOrder method will be invoked for requests<br />
with a orderRequest local name and a http://samples namespace URI; the order method for requests with a<br />
order local name. For more information about these annotations, refer to Section 5.4.3,<br />
&#8220;MethodEndpointMapping&#8221;.
<p><br />
&nbsp;</p>
<p>&lt;?xml version="1.0" encoding="UTF-8"?&gt;<br />
&lt;beans xmlns="http://www.springframework.org/schema/beans"<br />
&nbsp;xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br />
&nbsp;xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"&gt;</p>
<p>&nbsp;&lt;description&gt;<br />
&nbsp;&nbsp;This web application context contains Spring-WS beans. The beans<br />
&nbsp;&nbsp;defined in this context are automatically detected by Spring-WS,<br />
&nbsp;&nbsp;similar to the way Controllers are picked up in Spring Web MVC.<br />
&nbsp;&lt;/description&gt;</p>
<p>&nbsp;&lt;bean<br />
&nbsp;&nbsp;class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping"&gt;<br />
&nbsp;&nbsp;&lt;description&gt;<br />
&nbsp;&nbsp;&nbsp;Detects @PayloadRoot annotations on @Endpoint bean methods.<br />
&nbsp;&nbsp;&nbsp;The MarshallingAirlineEndpoint has such annotations. It uses<br />
&nbsp;&nbsp;&nbsp;two interceptors: one that logs the message payload, and the<br />
&nbsp;&nbsp;&nbsp;other validates it accoring to the 'airline.xsd' schema<br />
&nbsp;&nbsp;&nbsp;file.<br />
&nbsp;&nbsp;&lt;/description&gt;<br />
&nbsp;&lt;/bean&gt;<br />
&nbsp;&lt;bean id="echo"<br />
&nbsp;&nbsp;class="org.springframework.ws.wsdl.wsdl11.DynamicWsdl11Definition"&gt;<br />
&nbsp;&nbsp;&lt;description&gt;<br />
&nbsp;&nbsp;&nbsp;This bean definition represents a WSDL definition that is<br />
&nbsp;&nbsp;&nbsp;generated at runtime, based on the builder defined below. It<br />
&nbsp;&nbsp;&nbsp;can be retrieved by going to /echo/echo.wsdl (i.e. the bean<br />
&nbsp;&nbsp;&nbsp;name corresponds to the filename).<br />
&nbsp;&nbsp;&lt;/description&gt;<br />
&nbsp;&nbsp;&lt;property name="builder"&gt;<br />
&nbsp;&nbsp;&nbsp;&lt;description&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;The builder creates a WSDL from the 'echo.xsd' schema.<br />
&nbsp;&nbsp;&nbsp;&nbsp;It detects all elements that ends with 'Request', finds<br />
&nbsp;&nbsp;&nbsp;&nbsp;corresponding 'Response' messages, and creates an<br />
&nbsp;&nbsp;&nbsp;&nbsp;operation based on that. All operations are put in a<br />
&nbsp;&nbsp;&nbsp;&nbsp;portType with name 'Echo', and binding and service are<br />
&nbsp;&nbsp;&nbsp;&nbsp;created.<br />
&nbsp;&nbsp;&nbsp;&lt;/description&gt;<br />
&nbsp;&nbsp;&nbsp;&lt;bean<br />
&nbsp;&nbsp;&nbsp;&nbsp;class="org.springframework.ws.wsdl.wsdl11.builder.XsdBasedSoap11Wsdl4jDefinitionBuilder"&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name="schema" value="/WEB-INF/echo.xsd" /&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name="portTypeName" value="Echo" /&gt;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&lt;property name="locationUri"<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value="http://localhost:8080/echoweb/services" /&gt;<br />
&nbsp;&nbsp;&nbsp;&lt;/bean&gt;<br />
&nbsp;&nbsp;&lt;/property&gt;<br />
&nbsp;&lt;/bean&gt;<br />
&nbsp;&lt;bean id="echoEndpoint" class="com.vanad.EchoEndpoint"&gt;<br />
&nbsp;&nbsp;&lt;description&gt;This endpoint handles echo requests.&lt;/description&gt;<br />
&nbsp;&nbsp;&lt;property name="echoService" ref="echoService" /&gt;<br />
&nbsp;&lt;/bean&gt;<br />
&nbsp;&lt;bean id="echoService" class="com.vanad.EchoServiceImpl"&gt;<br />
&nbsp;&nbsp;&lt;description&gt;This bean is our "business" service.&lt;/description&gt;<br />
&nbsp;&lt;/bean&gt;</p>
<p>&nbsp;&lt;bean id="payloadLoggingInterceptor"<br />
&nbsp;&nbsp;class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor"&gt;<br />
&nbsp;&lt;/bean&gt;</p>
<p>&nbsp;&lt;bean id="soapEnvelopeLoggingInterceptor"<br />
&nbsp;&nbsp;class="org.springframework.ws.soap.server.endpoint.interceptor.SoapEnvelopeLoggingInterceptor"&gt;<br />
&nbsp;&lt;/bean&gt;<br />
&nbsp;&lt;bean<br />
&nbsp;&nbsp;class="org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter"&gt;<br />
&nbsp;&nbsp;&lt;constructor-arg ref="marshaller" /&gt;<br />
&nbsp;&lt;/bean&gt;<br />
&nbsp;&lt;bean id="marshaller"<br />
&nbsp;&nbsp;class="org.springframework.oxm.jaxb.Jaxb2Marshaller"&gt;<br />
&nbsp;&nbsp;&lt;property name="contextPath" value="com.vanad.schema" /&gt;<br />
&nbsp;&lt;/bean&gt;<br />
&lt;/beans&gt;</p>
<p><br />
&nbsp;</p>
也就是说用spring开发webservice需要配置一下文件：<br />
1.EndPoint，如果使用标记的话，就可以不用继承任何类<br />
2.EndpointMapping，Detects @PayloadRoot annotations on @Endpoint bean methods.<br />
3.DynamicWsdl11Definition。动态生成WSDL<br />
如果使用JAXB作为Object和XML的映射，那么还需要<br />
4.Marshaller一般为Jaxb2Marshaller<br />
5.如果是使用的标记的话，还需要MarshallingMethodEndpointAdapter，一般现在使用<br />
&nbsp;&nbsp;&nbsp;&nbsp;GenericMarshallingMethodEndpointAdapter
<img src ="http://www.blogjava.net/liuzheng/aggbug/170363.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/liuzheng/" target="_blank">刘铮 </a> 2007-12-25 17:48 <a href="http://www.blogjava.net/liuzheng/articles/170363.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>使用SAAJ的子元素的添加</title><link>http://www.blogjava.net/liuzheng/articles/168406.html</link><dc:creator>刘铮 </dc:creator><author>刘铮 </author><pubDate>Tue, 18 Dec 2007 02:14:00 GMT</pubDate><guid>http://www.blogjava.net/liuzheng/articles/168406.html</guid><wfw:comment>http://www.blogjava.net/liuzheng/comments/168406.html</wfw:comment><comments>http://www.blogjava.net/liuzheng/articles/168406.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/liuzheng/comments/commentRss/168406.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/liuzheng/services/trackbacks/168406.html</trackback:ping><description><![CDATA[private void handleBookListRequest(SOAPBody replyBody) throws SOAPException {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Create a BookTitles element containing an entry<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // for each book title.<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: red">&nbsp;SOAPBodyElement bodyElement = replyBody.addBodyElement(BOOK_TITLES_NAME);<br />
</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Add 'xsi:type = "SOAP-ENC:Array"'<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bodyElement.addAttribute(<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; soapFactory.createName("type", XMLSCHEMA_INSTANCE_PREFIX, <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; XMLSCHEMA_INSTANCE_URI), SOAP_ENC_PREFIX + ":Array");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Add 'SOAP-ENC:arrayType = "xsd:string[]"<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bodyElement.addAttribute(<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; soapFactory.createName("arrayType", SOAP_ENC_PREFIX, <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SOAPConstants.URI_NS_SOAP_ENCODING), XMLSCHEMA_PREFIX +<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ":string[]");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; // Add an array entry for each book <br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String[] titles = BookImageServletData.getBookTitles(&nbsp; );<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; for (int i = 0; i &lt; titles.length; i++) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; SOAPElement titleElement = <span style="color: red">bodyElement</span>.addChildElement("item");<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; titleElement.addTextNode(titles[i]);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <br />
&nbsp;&nbsp;&nbsp; }<br />
<br />
注意红色字体，addChildElement
<dt><strong>返回：</strong>
<dd>一个实例，表示实际添加到树的新 SOAP 元素。</dd>
<dt>以后要使用<span style="color: red">bodyElement才能添加他的子元素，从而形成树。</span></dt>
<img src ="http://www.blogjava.net/liuzheng/aggbug/168406.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/liuzheng/" target="_blank">刘铮 </a> 2007-12-18 10:14 <a href="http://www.blogjava.net/liuzheng/articles/168406.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>使用SAAJ处理SOAP</title><link>http://www.blogjava.net/liuzheng/articles/168276.html</link><dc:creator>刘铮 </dc:creator><author>刘铮 </author><pubDate>Mon, 17 Dec 2007 09:27:00 GMT</pubDate><guid>http://www.blogjava.net/liuzheng/articles/168276.html</guid><wfw:comment>http://www.blogjava.net/liuzheng/comments/168276.html</wfw:comment><comments>http://www.blogjava.net/liuzheng/articles/168276.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/liuzheng/comments/commentRss/168276.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/liuzheng/services/trackbacks/168276.html</trackback:ping><description><![CDATA[<p>The foundation of Web services lies in the sending and receiving of messages in a standard format so that all systems can understand them. Typically, that format is SOAP. A SOAP message can be generated and sent manually, but the SOAP with Attachments API for Java (SAAJ) -- an offshoot of the Java API for XML Messaging (JAXM) -- automates many of the required steps, such as creating connections or creating and sending the actual messages. This tip chronicles the creation and sending of a synchronous SOAP message.</p>
<p>The process involves five steps:</p>
<ol>
    <li>Creating a SOAP connection
    <li>Creating a SOAP message
    <li>Populating the message
    <li>Sending the message
    <li>Retrieving the reply </li>
</ol>
<p>SAAJ is available as part of the Java Web Services Developer Pack 1.2 (see <a href="http://www.ibm.com/developerworks/xml/library/x-jaxmsoap/#resources">Resources</a>). This package also includes a copy of the Tomcat Web server (so you can host your own service) and sample applications.<br />
<br />
<br />
</p>
<p><a name="struct"><span class="atitle">The structure of a SOAP message</span></a></p>
<p>I'll start by showing you the structure of the message itself. A basic SOAP message consists of an envelope with two main parts: the header and the body. The application determines how these parts are used, but the overall message must follow a specific XML structure, such as:</p>
<p><br />
<a name="c1"><strong>Listing 1. A sample SOAP message</strong></a><br />
<table cellspacing="0" cellpadding="0" width="100%" border="0">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">				<span class="boldcode">&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
            xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/1999/XMLSchema"&gt;
            &lt;SOAP-ENV:Header /&gt;
            &lt;SOAP-ENV:Body&gt; </span>
            &lt;ns1:getPrice xmlns:ns1="urn:xmethods-BNPriceCheck"
            SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"&gt;
            &lt;isbn xsi:type="xsd:string"&gt;0672324229&lt;/isbn&gt;
            &lt;/ns1:getPrice&gt;
            <span class="boldcode">    &lt;/SOAP-ENV:Body&gt;
            &lt;/SOAP-ENV:Envelope&gt; </span>
            </pre>
            </td>
        </tr>
    </tbody>
</table>
<br />
</p>
<p>Here, the header is empty and the body contains the payload, or the message to be delivered. In this case, it's a message requesting the price of a book.</p>
<p>Notice the structure of the message. The <code>Envelope</code> contains the <code>Header</code> and <code>Body</code> elements, and all three are part of the <code>http://schemas.xmlsoap.org/soap/envelope/</code> namespace. The application sends the message using a <code>SOAPConnection</code>.</p>
<p><br />
<table cellspacing="0" cellpadding="0" width="100%" border="0">
    <tbody>
        <tr>
            <td><img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" /></td>
        </tr>
    </tbody>
</table>
<br />
<br />
</p>
<p><a name="create"><span class="atitle">Creating the connection and the message</span></a></p>
<p>The first step is to create the overall class and the connection:</p>
<p><br />
<a name="c2"><strong>Listing 2. Create the connection</strong></a><br />
<table cellspacing="0" cellpadding="0" width="100%" border="0">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">import javax.xml.soap.SOAPConnectionFactory;
            import javax.xml.soap.SOAPConnection;
            public class SOAPTip {
            public static void main(String args[]) {
            try {
            <span class="boldcode">         //First create the connection
            SOAPConnectionFactory soapConnFactory =
            SOAPConnectionFactory.newInstance();
            SOAPConnection connection =
            soapConnFactory.createConnection();
            //Close the connection
            connection.close();</span>
            } catch(Exception e) {
            System.out.println(e.getMessage());
            }
            }
            }</pre>
            </td>
        </tr>
    </tbody>
</table>
<br />
</p>
<p>The application can send SOAP messages directly using a <code>SOAPConnection</code>, which is now part of the SAAJ package, or indirectly using a messaging provider, which remains in the JAXM package. In this case, the application creates the <code>SOAPConnection</code> object using a factory.</p>
<p>A factory also creates the message itself:</p>
<p><br />
<a name="c3"><strong>Listing 3. Creating the message object</strong></a><br />
<table cellspacing="0" cellpadding="0" width="100%" border="0">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">import javax.xml.soap.SOAPConnectionFactory;
            import javax.xml.soap.SOAPConnection;
            <span class="boldcode">import javax.xml.soap.MessageFactory;
            import javax.xml.soap.SOAPMessage;
            import javax.xml.soap.SOAPPart;
            import javax.xml.soap.SOAPEnvelope;
            import javax.xml.soap.SOAPBody;</span>
            public class SOAPTip {
            public static void main(String args[]) {
            try {
            //First create the connection
            SOAPConnectionFactory soapConnFactory =
            SOAPConnectionFactory.newInstance();
            SOAPConnection connection =
            soapConnFactory.createConnection();
            <span class="boldcode">        //Next, create the actual message
            MessageFactory messageFactory = MessageFactory.newInstance();
            SOAPMessage message = messageFactory.createMessage();
            //Create objects for the message parts
            SOAPPart soapPart =     message.getSOAPPart();
            SOAPEnvelope envelope = soapPart.getEnvelope();
            SOAPBody body =         envelope.getBody();</span>
            //Close the connection
            connection.close();
            } catch(Exception e) {
            System.out.println(e.getMessage());
            }
            }
            }</pre>
            </td>
        </tr>
    </tbody>
</table>
<br />
<table cellspacing="0" cellpadding="0" width="40%" align="right" border="0">
    <tbody>
        <tr>
            <td width="10"><img height="1" alt="" src="http://www.ibm.com/i/c.gif" width="10" /></td>
            <td>
            <table cellspacing="0" cellpadding="5" width="100%" border="1">
                <tbody>
                    <tr>
                        <td bgcolor="#eeeeee"><a name="versions"><strong>Version differences</strong></a><br />
                        If you've using another version of SAAJ, such as the Axis 1.2 beta SAAJ library, you may need to use <code>addBodyElement</code> instead of <code>addChildElement</code>. </td>
                    </tr>
                </tbody>
            </table>
            </td>
        </tr>
    </tbody>
</table>
</p>
<p>First, you create the message itself by using the <code>MessageFactory</code>. This message already contains empty versions of the basic parts, such as the <code>envelope</code> and <code>header</code>. The <code>SOAPPart</code> contains the <code>envelope</code>, and the <code>envelope</code> contains the body. Create references to the needed objects, such as the <code>SOAPBody</code>. </p>
<p>Next, populate the <code>SOAPBody</code>:</p>
<p><br />
<a name="c4"><strong>Listing 4. Populating the body</strong></a><br />
<table cellspacing="0" cellpadding="0" width="100%" border="0">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">...
            import javax.xml.soap.SOAPBody;
            <span class="boldcode">import javax.xml.soap.SOAPElement;</span>
            public class SOAPTip {
            public static void main(String args[]) {
            try {
            ...
            //Create objects for the message parts
            SOAPPart soapPart =     message.getSOAPPart();
            SOAPEnvelope envelope = soapPart.getEnvelope();
            SOAPBody body =         envelope.getBody();
            <span class="boldcode">        //Populate the body
            //Create the main element and namespace
            SOAPElement bodyElement =
            body.addChildElement(envelope.createName("getPrice" ,
            "ns1",
            "urn:xmethods-BNPriceCheck"));
            //Add content
            bodyElement.addChildElement("isbn").addTextNode("0672324229");
            //Save the message
            message.saveChanges();
            //Check the input
            System.out.println("\nREQUEST:\n");
            message.writeTo(System.out);
            System.out.println();</span>
            //Close the connection
            connection.close();
            } catch(Exception e) {
            System.out.println(e.getMessage());
            }
            }
            }</pre>
            </td>
        </tr>
    </tbody>
</table>
<br />
</p>
<p>The body of the SOAP message is just like any other XML element in that you can add a child element, such as <code>getPrice</code>. You can then add the <code>isbn</code> element and its text node just as you might with a typical DOM element.</p>
<p>With SAAJ you also have the opportunity to directly create the <code>SOAPPart</code> of the message using an external file. For example, the file <code>prepped.msg</code> contains the XML structure in the first listing, and can be called in lieu of building the document manually:</p>
<p><br />
<a name="c5"><strong>Listing 5. Creating the message from an external file</strong></a><br />
<table cellspacing="0" cellpadding="0" width="100%" border="0">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">...
            import javax.xml.soap.SOAPElement;
            <span class="boldcode">import java.io.FileInputStream;
            import javax.xml.transform.stream.StreamSource;</span>
            public class SOAPTip {
            public static void main(String args[]) {
            ...
            //Create objects for the message parts
            SOAPPart soapPart =     message.getSOAPPart();
            SOAPEnvelope envelope = soapPart.getEnvelope();
            SOAPBody body =         envelope.getBody();
            <span class="boldcode">//Populate the Message
            StreamSource preppedMsgSrc = new StreamSource(
            new FileInputStream("prepped.msg"));
            soapPart.setContent(preppedMsgSrc);</span>
            //Save the message
            message.saveChanges();
            ...
            }
            }</pre>
            </td>
        </tr>
    </tbody>
</table>
<br />
</p>
<p>The <code>StreamSource</code> class is typically used as part of an XSL Transformation, but here you can use it simply to obtain the <code>FileInputStream</code>. The result is a SOAP message that's ready to send.</p>
<p><br />
<table cellspacing="0" cellpadding="0" width="100%" border="0">
    <tbody>
        <tr>
            <td><img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" /></td>
        </tr>
    </tbody>
</table>
<table class="no-print" cellspacing="0" cellpadding="0" align="right">
    <tbody>
        <tr align="right">
            <td></td>
        </tr>
    </tbody>
</table>
<br />
<br />
</p>
<p><a name="sendmsg"><span class="atitle">Sending the message</span></a></p>
<p>With a synchronous message, sending the SOAP message and receiving a reply take place in a single step:</p>
<p><br />
<a name="c6"><strong>Listing 6. Sending the message</strong></a><br />
<table cellspacing="0" cellpadding="0" width="100%" border="0">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">...
            public class SOAPTip {
            public static void main(String args[]) {
            ...
            //Check the input
            System.out.println("\nREQUEST:\n");
            message.writeTo(System.out);
            System.out.println();
            <span class="boldcode">        //Send the message and get a reply
            //Set the destination
            String destination =
            "http://services.xmethods.net:80/soap/servlet/rpcrouter";
            //Send the message
            SOAPMessage reply = connection.call(message, destination);</span>
            //Close the connection
            connection.close();
            ...
            }
            }</pre>
            </td>
        </tr>
    </tbody>
</table>
<br />
</p>
<p>The actual message is sent using the <code>call()</code> method, which takes the message itself and a destination as arguments and returns a second <code>SOAPMessage</code> as a reply. In earlier versions of JAXM, the destination had to be an <code>Endpoint</code> object or a <code>URLEndpoint</code>, but now it simply has to be an object. This example uses the "Book price checker" Web service hosted by XMethods, which returns the price of the book whose ISBN is listed in the request.</p>
<p>The <code>call()</code> method blocks until it receives the returned <code>SOAPMessage</code>.</p>
<p><br />
<table cellspacing="0" cellpadding="0" width="100%" border="0">
    <tbody>
        <tr>
            <td><img height="1" alt="" src="http://www.ibm.com/i/v14/rules/blue_rule.gif" width="100%" /></td>
        </tr>
    </tbody>
</table>
<br />
<br />
</p>
<p><a name="response"><span class="atitle">The response</span></a></p>
<p>The returned <code>SOAPMessage</code>, <code>reply</code>, is a SOAP message in the same form as the message sent, and as such can be manipulated just like any other XML message. SOAP allows you to transform the reply directly using XSLT:</p>
<p><br />
<a name="c7"><strong>Listing 7. Reading the response</strong></a><br />
<table cellspacing="0" cellpadding="0" width="100%" border="0">
    <tbody>
        <tr>
            <td class="code-outline">
            <pre class="displaycode">...
            <span class="boldcode">import javax.xml.transform.TransformerFactory;
            import javax.xml.transform.Transformer;
            import javax.xml.transform.Source;
            import javax.xml.transform.stream.StreamResult;</span>
            public class SOAPTip {
            public static void main(String args[]) {
            try {
            ...
            //Send the message
            SOAPMessage reply = connection.call(message, destination);
            <span class="boldcode">        //Check the output
            System.out.println("\nRESPONSE:\n");
            //Create the transformer
            TransformerFactory transformerFactory =
            TransformerFactory.newInstance();
            Transformer transformer =
            transformerFactory.newTransformer();
            //Extract the content of the reply
            Source sourceContent = reply.getSOAPPart().getContent();
            //Set the output for the transformation
            StreamResult result = new StreamResult(System.out);
            transformer.transform(sourceContent, result);
            System.out.println();</span>
            //Close the connection
            connection.close();
            ...
            }
            }</pre>
            </td>
        </tr>
    </tbody>
</table>
<br />
</p>
<p>Create the <code>Transformer</code> object as you would in any XSLT application. In this case, you just want to output the content, so there's no stylesheet. Here, the content itself is the entire SOAP part of the message (as opposed to the SOAP message itself, which might include attachments). You could also extract the envelope and body before processing. The result in this case is simply <code>System.out</code>, but can be any choice normally available to a transformation. Transform as usual.</p>
<img src ="http://www.blogjava.net/liuzheng/aggbug/168276.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/liuzheng/" target="_blank">刘铮 </a> 2007-12-17 17:27 <a href="http://www.blogjava.net/liuzheng/articles/168276.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>