---
title: "soap基于契约优先WSDL的简单开发流程"
author: "cdxs2"
date: "2013-11-10T11:36:22Z"
tags: []
categories: ["编程语言"]
slug: "soap-wsdl"
draft: false
lastmod: "2013-11-10T11:36:22Z"
id: 1973518
url: "https://cdxs2.iteye.com/blog/1973518"
---

开发流程：

================================

一.先写schema或者wsdl文件

1.在src下创建META-INF/wsdl文件夹

2.新建wsdl并编写文件

(1)编写type

(2)编写message

(3)编写portType：指定接口和方法

(4)编写binding，指定编码样式

(5)编写service

mywsdl.wsdl

```
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
	xmlns:tns="http://www.example.org/mywsdl/" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
	xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="MyServiceImplService"
	targetNamespace="http://www.example.org/mywsdl/">

	<wsdl:types>
		<xsd:schema targetNamespace="http://www.example.org/mywsdl/">
			<xsd:element name="add" type="tns:add" />
			<xsd:element name="addResponse" type="tns:addResponse" />
			<xsd:element name="divide" type="tns:divide" />
			<xsd:element name="divideResponse" type="tns:divideResponse" />
			<xsd:element name="licenseInfo" type="xsd:string" />

			<xsd:complexType name="add">
				<xsd:sequence>
					<xsd:element name="a" type="xsd:int" />
					<xsd:element name="b" type="xsd:int" />
				</xsd:sequence>
			</xsd:complexType>
			<xsd:complexType name="addResponse">
				<xsd:sequence>
					<xsd:element name="addResult" type="xsd:int" />
				</xsd:sequence>
			</xsd:complexType>

			<xsd:complexType name="divide">
				<xsd:sequence>
					<xsd:element name="c" type="xsd:int" />
					<xsd:element name="d" type="xsd:int" />
				</xsd:sequence>
			</xsd:complexType>
			<xsd:complexType name="divideResponse">
				<xsd:sequence>
					<xsd:element name="divideResult" type="xsd:int" />
				</xsd:sequence>
			</xsd:complexType>
		</xsd:schema>
	</wsdl:types>

	<wsdl:message name="add">
		<wsdl:part name="add" element="tns:add" />
	</wsdl:message>

	<wsdl:message name="addResponse">
		<wsdl:part name="addResponse" element="tns:addResponse" />
	</wsdl:message>

	<wsdl:message name="divide">
		<wsdl:part name="divide" element="tns:divide" />
	</wsdl:message>

	<wsdl:message name="divideResponse">
		<wsdl:part name="divideResponse" element="tns:divideResponse" />
	</wsdl:message>

	<!-- 建立头信息 -->
	<wsdl:message name="licenseInfo">
		<wsdl:part name="licenseInfo" element="tns:licenseInfo" />
	</wsdl:message>

	<wsdl:portType name="IMyService">
		<wsdl:operation name="add">
			<wsdl:input message="tns:add" />
			<wsdl:output message="tns:addResponse" />
		</wsdl:operation>

		<wsdl:operation name="divide">
			<wsdl:input message="tns:divide" />
			<wsdl:output message="tns:divideResponse" />
		</wsdl:operation>
	</wsdl:portType>

	<wsdl:binding name="myServiceSOAP" type="tns:IMyService">
		<soap:binding style="document"
			transport="http://schemas.xmlsoap.org/soap/http" />
		<wsdl:operation name="add">
			<wsdl:input>
				<soap:body use="literal" />
				<!-- 添加头信息 -->
				<soap:header use="literal" part="licenseInfo" message="tns:licenseInfo" />
			</wsdl:input>
			<wsdl:output>
				<soap:body use="literal" />
			</wsdl:output>
		</wsdl:operation>

		<wsdl:operation name="divide">
			<wsdl:input>
				<soap:body use="literal" />
			</wsdl:input>
			<wsdl:output>
				<soap:body use="literal" />
			</wsdl:output>
		</wsdl:operation>
	</wsdl:binding>

	<!-- 这个name必须和本文件的命名空间名称一致 -->
	<wsdl:service name="MyServiceImplService">
		<wsdl:port binding="tns:myServiceSOAP" name="MyServiceImplPort">
			<soap:address location="http://localhost:9999/ms" />
		</wsdl:port>
	</wsdl:service>

</wsdl:definitions>
```

 

二. 使用wsimport，根据这个文件生成接口(IMyService.java)  
![](http://dl2.iteye.com/upload/attachment/0091/0503/366155b8-26d6-30e3-8c12-ac468afd3f31.png)  
 

IMyService.java

```
package org.example.mywsdl;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.6 in JDK 6
 * Generated source version: 2.1
 * 
 */
@WebService(name = "IMyService", targetNamespace = "http://www.example.org/mywsdl/")
public interface IMyService {


    /**
     * 
     * @param b
     * @param a
     * @return
     *     returns int
     */
    @WebMethod
    @WebResult(name = "addResult", targetNamespace = "")
    @RequestWrapper(localName = "add", targetNamespace = "http://www.example.org/mywsdl/", className = "org.example.mywsdl.Add")
    @ResponseWrapper(localName = "addResponse", targetNamespace = "http://www.example.org/mywsdl/", className = "org.example.mywsdl.AddResponse")
    public int add(
        @WebParam(name = "a", targetNamespace = "")
        int a,
        @WebParam(name = "b", targetNamespace = "")
        int b,
        @WebParam(name = "licenseInfo", header = true)
        String licenseInfo);

    /**
     * 
     * @param d
     * @param c
     * @return
     *     returns int
     */
    @WebMethod
    @WebResult(name = "divideResult", targetNamespace = "")
    @RequestWrapper(localName = "divide", targetNamespace = "http://www.example.org/mywsdl/", className = "org.example.mywsdl.Divide")
    @ResponseWrapper(localName = "divideResponse", targetNamespace = "http://www.example.org/mywsdl/", className = "org.example.mywsdl.DivideResponse")
    public int divide(
        @WebParam(name = "c", targetNamespace = "")
        int c,
        @WebParam(name = "d", targetNamespace = "")
        int d);

}
```

 

三.编写实现类实现接口(在实现类上指定wsdlLocation)

MyServiceImpl.java

```
package org.example.mywsdl;

import javax.jws.WebService;

@WebService(endpointInterface = "org.example.mywsdl.IMyService", targetNamespace = "http://www.example.org/mywsdl/", wsdlLocation = "META-INF/wsdl/mywsdl.wsdl")
public class MyServiceImpl implements IMyService {

	@Override
	public int add(int a, int b, String licenseInfo) {
		System.out.println(licenseInfo);
		System.out.println(a + b);
		return a + b;
	}

	@Override
	public int divide(int c, int d) {
		System.out.println(c / d);
		return c / d;
	}

}
```

 

四.添加头信息；

mywsdl.wsdl和IMyService.java文件中已经添加

五.发布服务

MyService.java

```
package org.example.mywsdl;

import javax.xml.ws.Endpoint;

public class MyService {
	public static void main(String[] args) {
		Endpoint.publish("http://localhost:9999/ms", new MyServiceImpl());
	}
}

```

 

六．使用wsimport，根据发布的服务生成客户端代码  
![](http://dl2.iteye.com/upload/attachment/0091/0505/0acd2fef-4dd1-3558-aeda-33d81279d941.png)  
   
![](http://dl2.iteye.com/upload/attachment/0091/0507/66bdf053-65d0-31dc-be30-5743254bf67b.png)  
 

七．创建客户端

新建一个java项目，把生成的所有java文件拷贝到src下面，新建并编写客户端代码

MyClient.java

```
package org.example.mywsdl;

import java.io.IOException;
import java.net.URL;

import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;

import org.w3c.dom.Document;

public class MyClient {
	public static void main(String[] args) {
		try {
			// 创建服务
			String ns = "http://www.example.org/mywsdl/";
			URL url = new URL("http://localhost:9999/ms");
			QName qname = new QName(ns, "MyServiceImplService");
			Service service = Service.create(url, qname);

			// 创建Dispatch
			QName pname = new QName(ns, "MyServiceImplPort");
			Dispatch<SOAPMessage> dispatch = service.createDispatch(pname, SOAPMessage.class, Service.Mode.MESSAGE);

			// 创建SOAP的body消息
			SOAPMessage message = MessageFactory.newInstance().createMessage();
			SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
			SOAPHeader header = envelope.getHeader();
			if (header == null) {
				header = envelope.addHeader();
			}
			SOAPBody body = envelope.getBody();

			QName hname = new QName(ns, "licenseInfo", "ns");
			header.addHeaderElement(hname).setValue("123456789");

			QName bname = new QName(ns, "add", "ns");
			SOAPBodyElement element = body.addBodyElement(bname);
			element.addChildElement("a").setValue("12");
			element.addChildElement("b").setValue("13");

			message.writeTo(System.out);
			System.out.println("\n invoking...");

			// 通过dispatch传递消息，返回响应消息
			SOAPMessage response = dispatch.invoke(message);
			response.writeTo(System.out);
			System.out.println();

			// 将响应的消息转换为dom对象
			Document doc = response.getSOAPPart().getEnvelope().getBody().extractContentAsDocument();
			System.out.println(doc.getElementsByTagName("addResult").item(0).getTextContent());
		} catch (SOAPException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
```

 

运行该程序

客户端打印结果：

&lt;SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;SOAP-ENV:Header&gt;&lt;ns:licenseInfo xmlns:ns="http://www.example.org/mywsdl/"&gt;123456789&lt;/ns:licenseInfo&gt;&lt;/SOAP-ENV:Header&gt;&lt;SOAP-ENV:Body&gt;&lt;ns:add xmlns:ns="http://www.example.org/mywsdl/"&gt;&lt;a&gt;12&lt;/a&gt;&lt;b&gt;13&lt;/b&gt;&lt;/ns:add&gt;&lt;/SOAP-ENV:Body&gt;&lt;/SOAP-ENV:Envelope&gt;

 invoking...

&lt;S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/"&gt;&lt;S:Header/&gt;&lt;S:Body&gt;&lt;ns2:addResponse xmlns:ns2="http://www.example.org/mywsdl/"&gt;&lt;addResult&gt;25&lt;/addResult&gt;&lt;/ns2:addResponse&gt;&lt;/S:Body&gt;&lt;/S:Envelope&gt;

25

服务端打印结果：

123456789

25

 

从打印结果可以看到，发送的消息中包含头信息，并且头信息发送到了服务端