GVKun编程网logo

在 Axis2 Web 服务初始化/启动上执行一些代码(axis2开发webservice服务端)

4

本文将介绍在Axis2Web服务初始化/启动上执行一些代码的详细情况,特别是关于axis2开发webservice服务端的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,

本文将介绍在 Axis2 Web 服务初始化/启动上执行一些代码的详细情况,特别是关于axis2开发webservice服务端的相关信息。我们将通过案例分析、数据研究等多种方式,帮助您更全面地了解这个主题,同时也将涉及一些关于Android 调用 Axis、Axis2、Cxf 发布的 web service、Apache Axis2 1.6.3 发布,Web 服务框架、Apache Axis2 实现 WebService 动态调用、Axis2 + Eclipse 第一个webservice的知识。

本文目录一览:

在 Axis2 Web 服务初始化/启动上执行一些代码(axis2开发webservice服务端)

在 Axis2 Web 服务初始化/启动上执行一些代码(axis2开发webservice服务端)

如何解决在 Axis2 Web 服务初始化/启动上执行一些代码

我使用 Axis2 1.6.2 和 Eclipse Axis2 插件创建了具有两个 Web 服务功能的 Axis2 Web 服务。 现在我需要在访问任何 Web 服务之前执行一些业务逻辑,在 Axis2 应用程序的初始化以缓存一些对象并在 Web 服务方法调用中使用它们。

实际上我想初始化休眠实体和一些其他业务逻辑代码,以便我可以在我的 Web 服务方法中使用它,例如在 Web 服务方法中执行 CRUD 操作等。

在使用 Eclipse 插件创建的 Axis2 Web 服务应用程序中,有没有办法做到这一点?

Android 调用 Axis、Axis2、Cxf 发布的 web service

Android 调用 Axis、Axis2、Cxf 发布的 web service

在 Android 中调用 axis2 发布 web service 过程中一直报 http500 错误,axis2 web service 是用 eclipse 插件生成的,发现直接打包成 war 包或直接在 eclipse 运行,Android 调用的时候会报错,一定要打包成 aar 包。如果不用 eclipse 生成,而是手动添加则可以打包成 war 包使用(参考博文:使用 axis2 构建 webservice),至于为什么还没有在网上找到答案,并且调用的 url 还不一样。

下面时 Android 调用 web service 的代码:

//调用axis开发的web service
private String callAxisWebService(String name) {
        String result = "";
        String namespace = "http://service.axisdemo.demo.com";
        String url = "http://192.168.1.8:8080/axisdemo/services/HelloService?wsdl";
        String methodName = "sayHello";
        SoapObject soapObject = new SoapObject(namespace, methodName);
        soapObject.addProperty("name", name);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut = soapObject;
        HttpTransportSE ht = new HttpTransportSE(url);
        ht.debug = true;
        try {
            ht.call(null, envelope, null);
            SoapObject s1 = (SoapObject) envelope.bodyIn;
            result = s1.getProperty("sayHelloReturn").toString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage());
        }
        return result;
    }

    //调用eclipse插件生成的axis2 web service
    private String callAxis2WebService(String name) {
        String result = "";
        String namespace = "http://service.axis2demo.demo.com";
        //这里的url后面没有?wsdl
        String url = "http://192.168.1.8:8080/axis2/services/helloService";
        String methodName = "sayHello";
        SoapObject soapObject = new SoapObject(namespace, methodName);
        soapObject.addProperty("name", name);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut = soapObject;
        HttpTransportSE ht = new HttpTransportSE(url);
        ht.debug = true;
        try {
            ht.call(null, envelope);
            SoapObject s1 = (SoapObject) envelope.bodyIn;
            result = s1.getProperty("return").toString();
        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage());
        }
        return result;
    }

    //调用手动配置的axis2 web service
    private String callAxis2WebService2(String name) {
        String result = "";
        String namespace = "http://service.axis2demo2.demo.com";
         //这里的url后面有?wsdl
        String url = "http://192.168.1.8:8080/axis2demo2/services/HelloService?wsdl";
        String methodName = "sayHello";
        SoapObject soapObject = new SoapObject(namespace, methodName);
        soapObject.addProperty("name", name);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut = soapObject;
        HttpTransportSE ht = new HttpTransportSE(url);
        ht.debug = true;
        try {
            ht.call(null, envelope);
            SoapObject s1 = (SoapObject) envelope.bodyIn;
            result = s1.getProperty("return").toString();
        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage());
        }
        return result;
    }

    //调用cxf开发的web service
    private String callCxfWebService(String name) {
        String result = "";
        String namespace = "http://service.cxfdemo.demo.com/";
        //在开发中使用了接口,所以?wsdl后面要跟IHelloService.wsdl
        String url = "http://192.168.1.8:8080/cxfdemo/services/HelloServicePort?wsdl=IHelloService.wsdl";
        String methodName = "sayHello";
        SoapObject soapObject = new SoapObject(namespace, methodName);
        soapObject.addProperty("name", name);
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.bodyOut = soapObject;
        //envelope.dotNet = true;
        HttpTransportSE ht = new HttpTransportSE(url);
        ht.debug = true;
        try {
            ht.call(null, envelope, null);
            SoapObject s1 = (SoapObject) envelope.bodyIn;
            result = s1.getProperty("return").toString();
        } catch (IOException e) {
            Log.e(TAG, e.getLocalizedMessage());
        } catch (XmlPullParserException e) {
            Log.e(TAG, e.getLocalizedMessage());
        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage());
        }
        return result;
    }

Apache Axis2 1.6.3 发布,Web 服务框架

Apache Axis2 1.6.3 发布,Web 服务框架

Apache Axis2 1.6.3 发布,此版本是个维护版本,总共修复了 50 个 issues

下载:http://axis.apache.org/axis2/java/core/download.cgi。

对 Axis1 进行了重新设计,支持 SOAP1.2/REST 以及更多

在线 API doc:http://tool.oschina.net/apidocs/apidoc?api=axis-1.6.2

Apache Axis2 实现 WebService 动态调用

Apache Axis2 实现 WebService 动态调用

前言

一直在使用 Apache CXF 框架,最近一个项目中使用的是 Apache Axis2 客户端聚合调用 Apache CXF 的服务,Apache Axis2 的服务和一些公共的 Webservice 服务(比如中国天气),由于改动可能牵涉很多问题,客户端索性使用 Apache Axis2 吧。虽然说如今 restful 风华正茂,WebService 已经式微了,但是某些行业却还在使用,最典型的是企业市场。

 

一。构建 Axis2 客户端

由于 Apache Axis2 自带的 RPCServiceClient 具有一定的缺陷,另外也不太好用,不符合程序调用方式,所以需要重写一个 Axis2 客户端

客户端代码

package cn.lantp.ws.client;

import java.lang.reflect.Type;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.xml.bind.JAXBException;
import javax.xml.namespace.QName;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMXMLBuilderFactory;
import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.axis2.AxisFault;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.databinding.typemapping.SimpleTypeMapper;
import org.apache.axis2.databinding.utils.BeanUtil;
import org.apache.axis2.description.AxisService;
import org.apache.axis2.engine.DefaultObjectSupplier;
import org.apache.axis2.rpc.client.RPCServiceClient;
import org.apache.axis2.util.StreamWrapper;
import org.apache.xmlbeans.impl.soap.SOAPFactory;


public class AxisRPCServiceClient extends RPCServiceClient {

	public AxisRPCServiceClient(ConfigurationContext configContext, AxisService service) throws AxisFault {
		super(configContext, service);
	}
	public AxisRPCServiceClient() throws AxisFault {
		super();
	}
	public AxisRPCServiceClient(ConfigurationContext configContext, URL wsdlURL, QName wsdlServiceName, String portName)
			throws AxisFault {
		super(configContext, wsdlURL, wsdlServiceName, portName);
	}

	
	/**
	 * 阻塞方式调用webservice
	 * @param opAddEntry  方法QName
	 * @param opQNameAndArgs 参数Map<QName,Value>
	 * @param returnTypes 返回值类型
	 * @return
	 * @throws AxisFault
	 */
	public Object[] invokeBlocking(QName opAddEntry, Map<QName, Object> opQNameAndArgs, Class[] returnTypes) throws AxisFault {
		  
		  OMElement argsToXmlOMElement = AxisSoapUtils.ArgsToXmlOMElement(opAddEntry, opQNameAndArgs);
	      OMElement response = super.sendReceive(argsToXmlOMElement);
	     
	      if(response==null || !response.getChildren().hasNext())
	      {
	    	  return new Object[]{};
	      }
	      Object[] deserialize = handleSoapResult(returnTypes, response);
	      return deserialize;
	}
	
	/**
	 * 返回值处理
	 * @param returnTypes 返回值类型
	 * @param response 服务器返回的数据
	 * @return
	 * @throws AxisFault
	 */
	private Object[] handleSoapResult(Class[] returnTypes, OMElement response) throws AxisFault {
		  Class srcType = null;
	      Object[] deserialize = new Object[]{};
	      if(returnTypes!=null && returnTypes.length>0)
	      {
	    	  	  DefaultObjectSupplier defaultObjectSupplier = new DefaultObjectSupplier();
	    		  Class returnObjectType = returnTypes[0];
	    		  if(returnObjectType.isArray() )
	    		  {	
	    			  returnTypes[0] = List.class;
	    			  srcType = returnObjectType.getComponentType();
	    			  if(SimpleTypeMapper.isSimpleType(srcType))
	    			  {
		    			  deserialize = BeanUtil.deserialize(response, returnTypes, defaultObjectSupplier);
		    		      if( deserialize!=null && deserialize.length>0)
		    		      {
		    		    	  AxisSoapUtils.listOMElementToArrayBean(srcType, deserialize);
		    		      }
	    			  }else{
	    				  if(OMElement.class.isInstance(response))
	    				  {
	    					  Iterator children = response.getChildren();
	    					  List<OMElement> omeList = new ArrayList();
	    					  while ( children.hasNext()) {
	    						  omeList.add((OMElement) children.next());
							  }
	    					  deserialize = new Object[]{omeList};
	    					  AxisSoapUtils.listOMElementToArrayBean(srcType, deserialize);
	    				  }
	    			  }
	    		  }else if(java.util.Collection.class.isAssignableFrom(returnObjectType)){
	    			  
	    			  if(OMElement.class.isInstance(response))
    				  {
    					  Iterator children = response.getChildren();
    					  List<OMElement> omeList = new ArrayList();
    					  while ( children.hasNext()) {
    						  omeList.add((OMElement) children.next());
						  }
    					  deserialize = new Object[]{omeList};
    				  }
	    		  }else if(java.util.Map.class.isAssignableFrom(returnObjectType)){
	    			  Map<Object,Object> retMap = new HashMap<Object, Object>();
	    			  if(OMElement.class.isInstance(response))
    				  {
	    				  Iterator<OMElement> children = response.getChildren();
    					  List<OMElement> omeList = new ArrayList();
    					  if( children.hasNext()) {
    						  OMElement nextMap = children.next();
    						  Iterator<OMElement> entryChildren = null;
    						  if(nextMap!=null && nextMap.getChildren()!=null)
    						  {
    							  entryChildren  = nextMap.getChildren();
    						  }
    						  
    						  while(entryChildren!=null && entryChildren.hasNext())
    						  {
    							  omeList.add(entryChildren.next());
    						  }
						  }
    					  Iterator<OMElement> iterator = omeList.iterator();
    					  while (iterator!=null && iterator.hasNext()) {
    						  OMElement next = iterator.next();
    						  if(!"entry".equalsIgnoreCase(next.getLocalName()))
    						  {
    							 continue;
    						  }
    						  Iterator<OMElement> subChildren = next.getChildren();
    						  Object key = null;
    						  Object value = null;
    						  while (subChildren!=null && subChildren.hasNext()) {
    							  
    							  OMElement element = subChildren.next();
    							  String keyName = element.getLocalName();
    							  if("key".equals(keyName))
    							  {
    								  key = element;
    								  
    							  }
    							  else if("value".equals(keyName))
    							  {
    									  value = element;
    							  }
    						  }
    						  retMap.put(key, value);
    					  }
    					  deserialize = new Object[]{retMap};
    				  }
	    		  }else{
	    			 deserialize = BeanUtil.deserialize(response, returnTypes, defaultObjectSupplier);
	    		  }
	      }
		return deserialize;
	}
	
}

 

工具类代码

package cn.lanpt.ws.client;

import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.wsdl.Binding;
import javax.wsdl.BindingOperation;
import javax.wsdl.Definition;
import javax.wsdl.WSDLException;
import javax.wsdl.extensions.ExtensibilityElement;
import javax.wsdl.extensions.http.HTTPOperation;
import javax.wsdl.extensions.soap.SOAPOperation;
import javax.wsdl.extensions.soap12.SOAP12Operation;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.namespace.QName;
import javax.xml.ws.soap.SOAPBinding;

import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.om.OMXMLBuilderFactory;
import org.apache.axiom.om.OMXMLParserWrapper;
import org.apache.axis2.AxisFault;
import org.apache.axis2.databinding.typemapping.SimpleTypeMapper;
import org.apache.axis2.databinding.utils.BeanUtil;
import org.apache.axis2.util.StreamWrapper;
import org.codehaus.xfire.soap.Soap11;
import org.codehaus.xfire.soap.Soap12;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;

import com.sun.xml.messaging.saaj.util.ByteInputStream;

public class AxisSoapUtils {

	public static final String QNAME_KEY = "WS.opration.QName";
	public static final String OPRATION_KEY = "WS.opration.Opration";

	public static Definition getDefinition(String url) throws WSDLException {
		WSDLFactory factory = WSDLFactory.newInstance();
		WSDLReader reader = factory.newWSDLReader();
		reader.setFeature("javax.wsdl.verbose", false);
		reader.setFeature("javax.wsdl.importDocuments", true);
		Definition def = reader.readWSDL(url + "?wsdl");

		return def;
	}

	/**
	 * 获取method所在的SOAPBinding信息
	 * 
	 * @param def
	 *            文档解析数据
	 * @param method
	 *            方法名称
	 * @return
	 */
	public static Map<String, Object> getSoapOperation(Definition def, String method) {
		if (def == null)
			return null;
		Map<Object, Binding> allBindings = def.getAllBindings();
		for (Map.Entry<Object, Binding> entry : allBindings.entrySet()) {
			Binding binds = entry.getValue();
			List<BindingOperation> operations = binds.getBindingOperations();
			for (BindingOperation operation : operations) {
				if (method.equals(operation.getName())) {
					List<ExtensibilityElement> extensibilityElements = operation.getExtensibilityElements();
					if (extensibilityElements != null && extensibilityElements.size() > 0) {
						for (ExtensibilityElement elem : extensibilityElements) {
							if (SOAP12Operation.class.isInstance(elem) || SOAPOperation.class.isInstance(elem)) {
								Map<String, Object> retOpt = new HashMap<String, Object>();
								QName qName = binds.getPortType().getQName();
								retOpt.put(QNAME_KEY, qName);
								retOpt.put(OPRATION_KEY, operation);
								return retOpt;
							}

						}
					}
				}
			}
		}
		return null;
	}

	/**
	 * 获取Soap:Action
	 * 
	 * @param operation
	 *            参数BindingOperation
	 * @return
	 */
	public static String getSoapActionURI(BindingOperation operation) {
		if (operation == null)
			return "";

		List<ExtensibilityElement> extensibilityElements = operation.getExtensibilityElements();

		if (extensibilityElements != null && extensibilityElements.size() > 0) {
			for (ExtensibilityElement elem : extensibilityElements) {
				if (SOAP12Operation.class.isInstance(elem)) {
					SOAP12Operation soap12Elem = (SOAP12Operation) elem;

					String url = soap12Elem.getSoapActionURI();
					if (url != null && url.length() > 0) {
						return url;
					}
				} else if (SOAPOperation.class.isInstance(elem)) {
					SOAPOperation soapElem = (SOAPOperation) elem;
					String url = soapElem.getSoapActionURI();
					if (url != null && url.length() > 0) {
						return url;
					}
				}
			}
		}

		return "";
	}

	/**
	 * 获取Soap版本信息
	 * 
	 * @param operation
	 *            参数BindingOperation
	 * @return
	 */
	public static String getSoapVersionURI(BindingOperation operation) {
		if (operation == null)
			return Soap11.getInstance().getNamespace();

		List<ExtensibilityElement> extensibilityElements = operation.getExtensibilityElements();

		if (extensibilityElements != null && extensibilityElements.size() > 0) {
			for (ExtensibilityElement elem : extensibilityElements) {
				if (SOAP12Operation.class.isInstance(elem)) {
					return Soap12.getInstance().getNamespace();
				} else if (SOAPOperation.class.isInstance(elem)) {
					return Soap11.getInstance().getNamespace();
				}
			}
		}
		return Soap11.getInstance().getNamespace();
	}

	/**
	 * 将对象转为OMElement对象
	 * 
	 * @param complexTypeObject
	 * @return
	 */
	public static OMElement castComplexToOMElment(Object complexTypeObject) {
		if (complexTypeObject == null) {
			return null;
		}
		javax.xml.stream.XMLStreamReader reader = BeanUtil.getPullParser(complexTypeObject);
		StreamWrapper parser = new StreamWrapper(reader);
		OMXMLParserWrapper stAXOMBuilder = OMXMLBuilderFactory.createStAXOMBuilder(OMAbstractFactory.getOMFactory(),
				parser);
		OMElement element = stAXOMBuilder.getDocumentElement();
		return element;
	}

	/**
	 * xml转为java bean
	 * 
	 * @param ome
	 *            OMElement对象
	 * @param srcType
	 *            数组元类型
	 * @return
	 */
	public static Object xmlToBean(OMElement ome, Class<?> srcType) {
		try {
			XmlRootElement annotation = (XmlRootElement) srcType.getAnnotation(XmlRootElement.class);
			String localName = srcType.getSimpleName();
			if (annotation != null) {
				localName = annotation.name();
			}
			ome.setLocalName(localName);

			JAXBContext context = JAXBContext.newInstance(srcType);
			Unmarshaller unmarshaller = context.createUnmarshaller();
			byte[] buf = ome.toString().getBytes();
			Object object = unmarshaller.unmarshal(new ByteInputStream(buf, 0, buf.length));
			return object;
		} catch (JAXBException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 封装请求
	 * 
	 * @param opAddEntry
	 *            方法
	 * @param opQNameAndArgs
	 *            参数
	 * @return
	 * @throws AxisFault
	 */
	public static OMElement ArgsToXmlOMElement(QName opAddEntry, Map<QName, Object> opQNameAndArgs) throws AxisFault {
		OMFactory fac = OMAbstractFactory.getOMFactory();
		String tns = opAddEntry.getNamespaceURI();
		OMNamespace namespace = fac.createOMNamespace(tns, "");
		OMElement methodElement = fac.createOMElement(opAddEntry.getLocalPart(), namespace);

		if (opQNameAndArgs != null && !opQNameAndArgs.isEmpty()) {
			for (Map.Entry<QName, Object> entry : opQNameAndArgs.entrySet()) {

				QName key = entry.getKey();
				Object value = entry.getValue();
				OMNamespace paramNamespace = fac.createOMNamespace(key.getNamespaceURI(), "");
				OMElement paramElement = null;
				if (value == null) {
					paramElement = fac.createOMElement(key.getLocalPart(), paramNamespace);
				} else if (SimpleTypeMapper.isSimpleType(value)) {
					paramElement = fac.createOMElement(key.getLocalPart(), paramNamespace);
					fac.createOMText(paramElement, SimpleTypeMapper.getStringValue(value));
				} else if (value.getClass().isArray()) {
					Class<?> componentType = value.getClass().getComponentType();

					int length = Array.getLength(value);
					for (int i = 0; i < length; i++) {
						if (SimpleTypeMapper.isSimpleType(componentType)) {
							paramElement = fac.createOMElement(key.getLocalPart(), paramNamespace);
							paramElement.setText(String.valueOf(Array.get(value, i)));
						} else {
							paramElement = AxisSoapUtils.castComplexToOMElment(String.valueOf(Array.get(value, i)));
						}
						if (paramElement != null) {
							methodElement.addChild(paramElement);
						}
					}

					paramElement = null;
				} else {
					paramElement = AxisSoapUtils.castComplexToOMElment(value);
					if (paramElement != null) {
						paramElement.setLocalName(key.getLocalPart());
						paramElement.declareNamespace(paramNamespace);
					} else {
						throw new AxisFault("参数:" + key.getLocalPart() + "的值无法被序列化,类型是" + value.getClass().getName());
					}
				}

				if (paramElement != null) {
					methodElement.addChild(paramElement);
				}
			}
		}

		return methodElement;

	}

	/**
	 * 将List数据转为数组数据
	 * 
	 * @param srcType
	 * @param deserialize
	 */
	public static void listOMElementToArrayBean(Class srcType, Object[] deserialize) {
		Object arrobj = deserialize[0];
		List arrList = null;
		if (arrobj != null && List.class.isInstance(arrobj)) {
			arrList = (List) arrobj;
		}
		if (arrList != null && arrList.size() > 0) {
			List lst = new ArrayList();
			for (int i = 0; i < arrList.size(); i++) {
				Object xmlObj = arrList.get(i);
				if (xmlObj != null && OMElement.class.isInstance(xmlObj)) {
					OMElement ome = (OMElement) xmlObj;
					String text = ome.getText();
					if (text == null || text.length() == 0) {
						Object xmlToBean = AxisSoapUtils.xmlToBean(ome, srcType);
						lst.add(xmlToBean);
					} else {
						lst.add(text);
					}
				}
			}
			deserialize[0] = changeListToArray(lst, srcType);
		}
	}

	/**
	 * 将List<T>转为T数组
	 * 
	 * @param lst
	 * @param srcType
	 * @return
	 */
	public static Object changeListToArray(List lst, Class srcType) {
		if (lst == null || srcType == null)
			return null;

		Object arrayObject = Array.newInstance(srcType, lst.size());
		for (int i = 0; i < lst.size(); i++) {
			Array.set(arrayObject, i, lst.get(i));
		}
		return arrayObject;
	}

	/**
	 * 获取目标命名空间
	 * 
	 * @param def
	 * @return
	 */
	public static String getTargetNamespace(Definition def) {
		return def.getTargetNamespace();
	}

	public static Map<EntryKey, List<Class>> parseGenericType(Class superClass) {
		Map<EntryKey, List<Class>> lstTreeClass = new HashMap<EntryKey, List<Class>>();
		Type superclass = superClass.getGenericSuperclass();
		Type[] actualTypeArguments = null;
		if (ParameterizedType.class.isInstance(superclass)) {
			ParameterizedType ptype = (ParameterizedType) superclass;
			actualTypeArguments = ptype.getActualTypeArguments();
			dispatchActualTypeArguments(superClass, lstTreeClass, 0, actualTypeArguments);
		}

		return lstTreeClass;
	}

	/**
	 * 递归方式解析泛型类
	 * 
	 * @param superClass
	 * @param lstTreeClass
	 * @param deep
	 * @param actualTypeArguments
	 */
	private static void dispatchActualTypeArguments(Class superClass, Map<EntryKey, List<Class>> lstTreeClass, int deep,
			Type[] actualTypeArguments) {

		EntryKey ek = new EntryKey();
		ek.setKey(deep);
		ek.setTypeClass(superClass);

		deep++;

		if (actualTypeArguments != null && actualTypeArguments.length > 0) {
			List<Class> lstClz = new ArrayList<Class>();
			for (int i = 0; i < actualTypeArguments.length; i++) {
				Type type = actualTypeArguments[i];
				if (ParameterizedType.class.isInstance(type)) {
					ParameterizedType pt = (ParameterizedType) type;
					Class crawtype = (Class) pt.getRawType();
					lstClz.add(crawtype);
					Type[] subActualTypeArguments = pt.getActualTypeArguments();
					dispatchActualTypeArguments(crawtype, lstTreeClass, deep, subActualTypeArguments);

				} else {
					Class clz = loadClass(((Class) type).getName());
					if (clz != null) {
						lstClz.add(clz);
					}
				}
			}
			List<Class> list = lstTreeClass.get(ek);
			if (list != null) {
				list.addAll(lstClz);
			} else {
				list = lstClz;
			}
			lstTreeClass.put(ek, list);
		}
	}

	public static Class loadClass(String name) {
		try {
			Class<?> loadClass = AxisSoapUtils.class.getClassLoader().loadClass(name);
			return loadClass;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}

}

 

二。测试代码

package cn.lantp.ws.client;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.wsdl.BindingOperation;
import javax.wsdl.Definition;
import javax.wsdl.Service;
import javax.wsdl.WSDLException;
import javax.wsdl.factory.WSDLFactory;
import javax.wsdl.xml.WSDLReader;
import javax.xml.namespace.QName;

import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;

import com.bj.haiguan.domain.User;

public class WebServiceTestMain {
	
	public static void main(String[] args) {
		
		test_createMapUser();
	}
	
	
	private static void test_createWeatherWS() {
		String urlStr = "http://ws.webxml.com.cn/WebServices/WeatherWS.asmx";
		String method = "getSupportCityString";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			QName uidQName = new QName(soapNamespace,"theRegionCode");
			opQNameAndArgs.put(uidQName,31115);
			
			Class[] returnTypes = new Class[]{String[].class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	private static void test_createMapUser() {
		String urlStr = "http://10.11.65.21:8080/SpringCFXServer/WS/haiguanService";
		String method = "createMapUser";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			QName userQName = new QName(soapNamespace,"userNames");
			opQNameAndArgs.put(userQName,new String[]{"张三","李四"});
			
			Class[] returnTypes = new Class[]{Map.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	private static void test_createUserList() {
		String urlStr = "http://10.11.65.21:8080/SpringCFXServer/WS/haiguanService";
		String method = "createUserArray";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));			
			QName qName = new QName(soapNamespace,method);
			
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
		/**	QName userQName = new QName(soapNamespace,"user");
			opQNameAndArgs.put(userQName,new User(1000,"张三","123456","北京"));
			QName uidQName = new QName(soapNamespace,"uid");
			opQNameAndArgs.put(uidQName,10086);
			**/
			Class[] returnTypes = new Class[]{User[].class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	
	private static void test_createUser() {
		String urlStr = "http://192.168.65.21:8080/SpringCXFServer/WS/TestCXFService";
		String method = "createUser";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			QName userQName = new QName(soapNamespace,"user");
			opQNameAndArgs.put(userQName,new User(1000,"张三","123456","北京"));
			QName uidQName = new QName(soapNamespace,"uid");
			opQNameAndArgs.put(uidQName,10086);
			
			Class[] returnTypes = new Class[]{User.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	private static void test_search() {
		String urlStr = "http://192.168.65.21:8080/SpringCXFServer/WS/TestCXFService";
		String method = "search";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			QName keywordQName = new QName(soapNamespace,"keyword");
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			opQNameAndArgs.put(keywordQName,"");
			Class[] returnTypes = new Class[]{String.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	private static void test_detail() {
		String urlStr = "http://192.168.65.21:8080/SpringCXFServer/WS/TestCXFService";
		String method = "detail";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			QName gidQName = new QName(soapNamespace,"gid");
			opQNameAndArgs.put(gidQName,"NnEgVlYP-43748-TeRWAfUxRF9OUT61-58529");
			
			Class[] returnTypes = new Class[]{String.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	private static void test_esbTest() {
		String urlStr = "http://192.168.15.155:8081/soap11/TestService";
		String method = "Test";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			
			QName arg0QName = new QName(soapNamespace,"arg0");
			QName arg1QName = new QName(soapNamespace,"arg1");
			QName arg2QName = new QName(soapNamespace,"arg2");
			
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			opQNameAndArgs.put(arg0QName," I ");
			opQNameAndArgs.put(arg1QName," am ");
			opQNameAndArgs.put(arg2QName," okay ");
			
			Class[] returnTypes = new Class[]{String.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
	private static void test_Axis2Service() {
		String urlStr = "http://192.168.9.206:8101/webService/services/Axis2TestService.jws";
		String method = "listGoods";
		try {
			AxisRPCServiceClient serviceClient = new AxisRPCServiceClient();
			EndpointReference targetEPR = new EndpointReference(urlStr);
			
			Definition definition = AxisSoapUtils.getDefinition(urlStr);
			Map<String, Object> soapOperation = AxisSoapUtils.getSoapOperation(definition, method);
			BindingOperation soapBindOperation = (BindingOperation) soapOperation.get(AxisSoapUtils.OPRATION_KEY);
			QName operationQName = (QName) soapOperation.get(AxisSoapUtils.QNAME_KEY);

			String soapActionURI = AxisSoapUtils.getSoapActionURI(soapBindOperation);
			String soapVersionURI = AxisSoapUtils.getSoapVersionURI(soapBindOperation);
			String soapNamespace = operationQName.getNamespaceURI();
			
			Options options = serviceClient.getOptions();
			options.setTimeOutInMilliSeconds(4*10000);
			options.setSoapVersionURI(soapVersionURI);
			options.setAction(soapActionURI);
			options.setCallTransportCleanup(true);
			options.setTo(targetEPR);
			options.setManageSession(true);
			options.setProperty("REUSE_HTTP_CLIENT", Boolean.valueOf(true));
			
			QName qName = new QName(soapNamespace,method);
			Map<QName, Object> opQNameAndArgs = new HashMap<QName, Object>();
			
			QName args1QName = new QName(soapNamespace,"goodsName");
			QName args2QName = new QName(soapNamespace,"goodsAttr");
			
			opQNameAndArgs.put(args1QName, "");
			opQNameAndArgs.put(args2QName, "");
			
			Class[] returnTypes = new Class[]{String.class};
			
			Object[] result = serviceClient.invokeBlocking(qName, opQNameAndArgs, returnTypes);
			serviceClient.cleanupTransport();
			
			if(result!=null)
			{
				for (Object obj : result)
				{
				
					String strObj = (String) obj;
					byte[] bytes = strObj.getBytes();
					
					System.out.println(new String(bytes,"UTF-8"));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getLocalizedMessage());
		}
	}
	
}

 

三.CXF Webservice 发布规范

1.@WebService 中 endpointInterface 和 targetNamespace 属性不能为空

@WebService(endpointInterface="cn.lanpt.ws.server.TestCXFService",targetNamespace="http://cxfws.ws.lanpt.cn/",serviceName="TestCXFService")

2.@WebMethod 中 action 属性不能为空,并且最好保持唯一性,以下任意一种方式都行

@WebMethod(action="search")  //发布到外面的公开
@WebMethod(action="http://ws.lantp.cn/TestCXFService/search")  //发布到外面的公开

3.@WebParam 中 targetNamespace 属性不能为空,且必须和 @WebService 中的 targetNamespace 的值保持一致

@WebParam(name="user" ,targetNamespace="http://cxfws.ws.lanpt.cn/")

4. 远程 JavaBean 的传送时,客户端 JavaBean 的注解 @XmlRootElement 中 name 的属性值不能为空

@XmlRootElement(name="User")

 

来个例子:

@WebService(endpointInterface="cn.lanpt.ws.server.TestCXFService",targetNamespace="http://cxfws.ws.lanpt.cn/",serviceName="TestCXFService")
public interface TestCXFService {
	
	@WebResult(name="list") //返回值名称
	@WebMethod(action="search")  //发布到外面的公开
	@POST
	public String search(@WebParam(name="keyword",targetNamespace="http://cxfws.ws.lanpt.cn/")String keyword);
	
	@WebResult(name="info") //返回值名称
	@WebMethod(action="detail")  //发布到外面的公开
	@POST
	public String detail(@WebParam(name="gid" ,targetNamespace="http://cxfws.ws.lanpt.cn/")String gid);
	
	@WebResult(name="user") //返回值名称
	@WebMethod(action="createUser")  //发布到外面的公开
	@POST
	public User createUser(@WebParam(name="user" ,targetNamespace="http://cxfws.ws.lanpt.cn/")User u,@WebParam(name="uid" ,targetNamespace="http://cxfws.ws.lanpt.cn/")int id);

	@WebResult(name="userOfList") //返回值名称
	@WebMethod(action="createUserList")  //发布到外面的公开
	@POST
	public List<User> createUserList();
	
	@WebResult(name="userOfArray") //返回值名称
	@WebMethod(action="createUserArray")  //发布到外面的公开
	@POST
	public User[] createUserArray();
	
	@WebResult(name="userOfArray") //返回值名称
	@WebMethod(action="createList")  //发布到外面的公开
	@POST
	public String[] createList();
	
	@WebResult(name="userOfMap") //返回值名称
	@WebMethod(action="createMapUser")  //发布到外面的公开
	@POST
	public Map<String, User> createMapUser(@WebParam(name="userNames" ,targetNamespace="http://cxfws.ws.lanpt.cn/")String[] s); 
}

JavaBean

@XmlType(name = "user", propOrder = { "id", "name", "address", "pass", "card" })
@XmlRootElement(name="User")
public class User {

	private Integer id;
	private String name;
	private String pass;
	private String address;
	private Card card;

	@XmlEnum(String.class)
	public enum Card { 	// 声明枚举
		CLUBS, DIAMONDS, HEARTS, SPADES
	};

	public User() {
	}

	public Card getCard() {
		return card;
	}

	public void setCard(Card card) {
		this.card = card;
	}

	public User(Integer id, String name, String pass, String address) {
		super();
		this.id = id;
		this.name = name;
		this.pass = pass;
		this.address = address;
		this.card = Card.CLUBS;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	// 即认为只要name和address相同,就是同一个对象

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((address == null) ? 0 : address.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		User other = (User) obj;
		if (address == null) {
			if (other.address != null)
				return false;
		} else if (!address.equals(other.address))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

}

 

 

Axis2 + Eclipse 第一个webservice

Axis2 + Eclipse 第一个webservice

1.编写服务代码

首先创建一个web项目Axis2Service,我是用maven创建的,

创建完项目后,编写服务代码,创建Service,起名Axis2ServiceTest.java

代码如下


package com.lei.axis2;

public class Axis2ServiceTest {
	
	/** 
     * 提供了一个说Hello的服务 
     * @return 
     */  
    public String sayHello(String name){  
        return "Hello "+name;  
    }  
      
    /** 
     * 提供了一个做加法的服务 
     * @param a 
     * @param b 
     * @return 
     */  
    public int add(int a,int b){  
        return a + b;  
    }  
}



2.将服务代码打包成arr文件

Eclipse菜单- New - File - Other -Axis2 Service Archiver,见下图

填写刚才的class的路径后,这个路径为刚才写的Service的bin目录,next,见下图

选择跳过 WSDL文件,见下图

如果你的Service有引用jar包,则在这里选择。我写的没有,所以next,见下图

由于我们没有编写service.xml,所以勾选让它自动生成,next

输入Service name(随意)、Class name、点击Load后,会加载Service中的Method,勾选要发布的Method后、next

最后一步,设置aar文件输出目录Output file location为E:\Axis2,和输出的文件名Output File Name为lei_service,然后点Finish:

完成后,找到E:\Axis2目录下的lei_service.aar文件,可以用rar打开后,看到目录结构如下,


进入META-INF目录后,可以看到插件给我们生成的一个service.xml,你可以自己研究下这个自动生成的service.xml了。

3.发布webservice

首先要部署一个axis2服务,将之前下载的axis2-1.6.3-war.zip文件解压后,得到一个axis2.war文件,将这个文件放到tomcat下的webapps文件夹下,然后启动tomcat,

会生自动部署一个axis2项目,可以访问http://localhost:8080/axis2/,看到以下欢迎界面后,证明axis2部署成功,

然后将上一步生成的lei_service.aar文件放到axis2项目下的 WEB-INF\services目录下,然后点击上图中的Services后,进入webservice列表,

在列表中即可找到你要发布的webservice,见下图


从上图中,可以看到刚才的两个方法add和sayHello,证明webservice发布成功。

4.客户端测试

测试代码如下,需要引用axis2-1.6.3-bin\lib下的相应jar包。

package client;

import javax.xml.namespace.QName;

import org.apache.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.rpc.client.RPCServiceClient;

public class Test {

	public static void main(String[] args) throws AxisFault {
		// TODO Auto-generated method stub
		
	//  使用RPC方式调用WebService          
	    RPCServiceClient serviceClient = new RPCServiceClient(); 
	    Options options = serviceClient.getOptions();
	    
	    //指定调用WebService的URL
	    EndpointReference targetEPR = new EndpointReference(  
	            "http://localhost:8080/axis2/services/LeiService");
	    options.setTo(targetEPR);
	    
	    //指定sayHello方法的参数值
	    Object[] opAddEntryArgs = new Object[] {"第一个Axis2"};
	    //指定sayHello方法返回值的数据类型的Class对象
	    Class[] classes = new Class[]{String.class};
	    //指定要调用的sayHello方法及WSDL文件的命名空间,其中命名空间为wsdl中的targetNamespace值
	    QName opAddEntry = new QName("http://axis2.lei.com", "sayHello");
	    
	    
	    System.out.println(serviceClient.invokeBlocking(opAddEntry, opAddEntryArgs, classes)[0]);
		
	}

}



输出结果:

测试另一个方法,只要改一下方法名以及传入的参数即可,类似于如下,

            //指定sayHello方法的参数值
	    Object[] opAddEntryArgs = new Object[] {100,201};
	    //指定sayHello方法返回值的数据类型的Class对象
	    Class[] classes = new Class[]{int.class,int.class};
	    //指定要调用的sayHello方法及WSDL文件的命名空间,其中命名空间为wsdl中的targetNamespace值
	    QName opAddEntry = new QName("http://axis2.lei.com", "add");
	    
	    
	    System.out.println(serviceClient.invokeBlocking(opAddEntry, opAddEntryArgs, classes)[0]);



运行结果显示301

关于在 Axis2 Web 服务初始化/启动上执行一些代码axis2开发webservice服务端的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Android 调用 Axis、Axis2、Cxf 发布的 web service、Apache Axis2 1.6.3 发布,Web 服务框架、Apache Axis2 实现 WebService 动态调用、Axis2 + Eclipse 第一个webservice的相关知识,请在本站寻找。

本文标签: