用eclipse+Axis2开发的webservice
- 格式:docx
- 大小:287.09 KB
- 文档页数:13
Axis2发布webservice总结详细例子demo本人测试用的了tomcat 下面能够正常使用在was和WebLogic下面应该是版本不兼容的问题,一直启动失败在was直接部署axis2.war包错误信息用到的jar包axis2-1.5.4-war.zip axis2-1.5.4-bin.zip编写webservice首先下载jar包上面已经有了解压缩bin包目录如下写接口的时候可以一个jar包不需要客户端调用的时候需要用的lib目录下面的所有jar包解压缩war包将axis2.war导入到Eclipse里面找到axis2.xml并修改下面配置修改<parameter name="userName">wangxz</parameter><parameter name="password">123456</parameter>这两个配置是axis2后台管理员的账号和密码用于部署和更新webservice <parameter name="hotdeployment">true</parameter><parameter name="hotupdate">true</parameter>这里个配置是热部署和热更新的意思设置为true<!--~ Licensed to the Apache Software Foundation (ASF) under one ~ or more contributor license agreements. See the NOTICE file ~ distributed with this work for additional information~ regarding copyright ownership. The ASF licenses this file~ to you under the Apache License, Version 2.0 (the~ "License"); you may not use this file except in compliance ~ with the License. You may obtain a copy of the License at~~ /licenses/LICENSE-2.0~~ Unless required by applicable law or agreed to in writing,~ software distributed under the License is distributed on an~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY~ KIND, either express or implied. See the License for the~ specific language governing permissions and limitations~ under the License.--><axisconfig name="AxisJava2.0"><!-- ================================================= --><!-- Parameters --><!-- ================================================= --><parameter name="hotdeployment">true</parameter><parameter name="hotupdate">true</parameter><parameter name="enableMTOM">false</parameter><parameter name="enableSwA">false</parameter><parameter name="EnableChildFirstClassLoading">false</parameter><!--Uncomment if you want to enable file caching for attachments --> <!--parameter name="cacheAttachments">true</parameter><parameter name="attachmentDIR"></parameter><parameter name="sizeThreshold">4000</parameter--><!--Uncomment if you want to plugin your own attachments lifecycle implementation --><!--<attachmentsLifecycleManagerclass="org.apache.axiom.attachments.lifecycle.impl.LifecycleManagerIm pl"/>--><!--Uncomment if you want to enable the reduction of the in-memory cache of WSDL definitions --><!--In some server environments, the available memory heap is limited and can fill up under load --><!--Since in-memory copies of WSDL definitions can be large, some steps can be taken--><!--to reduce the memory needed for the cached WSDL definitions. --> <!--parameter name="reduceWSDLMemoryCache">true</parameter--><!--This will give out the timout of the configuration contexts, inmilliseconds--><parameter name="ConfigContextTimeoutInterval">30000</parameter><!--During a fault, stack trace can be sent with the fault message. The following flag will control --><!--that behavior.--><parametername="sendStacktraceDetailsWithFaults">false</parameter><!--If there aren't any information available to find out the fault reason, we set the message of the exception--><!--as the faultreason/Reason. But when a fault is thrown from a service or some where, it will be --><!--wrapped by different levels. Due to this the initial exception message can be lost. If this flag--><!--is set, then Axis2 tries to get the first exception and set its message as the faultreason/Reason.--><parametername="DrillDownToRootCauseForFaultReason">false</parameter><parameter name="userName">wangxz</parameter><parameter name="password">123456</parameter><!--To override repository/services you need to uncomment following parameter and value SHOULD be absolute file path.--><!--ServicesDirectory only works on the following cases--><!---File based configurator and in that case the value should be a file URL (http:// not allowed)--><!---When creating URL Based configurator with URL file:// --><!--- War based configurator with expanded case , --><!--All the other scenarios it will be ignored.--><!--<parameter name="ServicesDirectory">service</parameter>--><!--To override repository/modules you need to uncomment following parameter and value SHOULD be absolute file path--><!--<parameter name="ModulesDirectory">modules</parameter>--><!--Following params will set the proper context paths for invocations. All the endpoints will have a commons context--><!--root which can configured using the following contextRoot parameter--><!--<parameter name="contextRoot">axis2</parameter>--><!--Our HTTP endpoints can handle both REST and SOAP. Following parameters can be used to distinguiush those endpoints--> <!--In case of a servlet, if you change this you have to manually change the settings of your servlet container to map this --><!--context path to proper Axis2 servlets--><!--<parameter name="servicePath">services</parameter>--><!--<parameter name="restPath">rest</parameter>--><!-- Following parameter will completely disable REST handling in Axis2--><parameter name="disableREST"locked="false">false</parameter><!-- Following parameter will suppress generation of SOAP 1.2 bindings in auto-generated WSDL files --><parameter name="disableSOAP12"locked="true">false</parameter><!--POJO deployer , this will alow users to drop .class file and make that into a service--><deployer extension=".class"directory="pojo" class="org.apache.axis2.deployment.POJODeployer"/><deployer extension=".jar"directory="servicejars"class="org.apache.axis2.jaxws.framework.JAXWSDeployer"/> <deployer extension=".jar"directory="transports"class="org.apache.axis2.deployment.TransportDeployer"/><!--CORBA deployer , this will alow users to invoke remote CORBA services through Axis2--><!--<deployer extension=".xml" directory="corba" class="org.apache.axis2.corba.deployer.CorbaDeployer"/>--><!--<deployer extension=".jsa" directory="rmiservices" class="org.apache.axis2.rmi.deploy.RMIServiceDeployer"/>--><!-- Following parameter will set the host name for the epr--><!--<parameter name="hostname" locked="true"></parameter>--><!-- If you have a front end host which exposes this webservice using a different public URL --><!-- use this parameter to override autodetected url --><!--<parametername="httpFrontendHostUrl">https://someotherhost/context</parameter>--><!--By default, JAXWS services are created by reading annotations. WSDL and schema are generated--><!--using a separate WSDL generator only when ?wsdl is called. Therefore, even if you engage--><!--policies etc.. to AxisService, it doesn't appear in the WSDL. By setting the following property--><!--to true, you can create the AxisService using the generated WSDL and remove the need for a--><!--WSDL generator. When ?wsdl is called, WSDL is generated in the normal way.--><parameter name="useGeneratedWSDLinJAXWS">false</parameter><!-- The way of adding listener to the system--><!-- <listener class="org.apache.axis2.ObserverIMPL">--><!-- <parameter name="RSS_URL">http://127.0.0.1/rss</parameter>--><!-- </listener>--><threadContextMigrators><threadContextMigratorlistId="JAXWS-ThreadContextMigrator-List"class="org.apache.axis2.jaxws.addressing.migrator.EndpointContextMapM igrator"/></threadContextMigrators><!-- ================================================= --><!-- Message Receivers --><!-- ================================================= --><!--This is the default MessageReceiver for the system , if you want to have MessageReceivers for --><!--all the other MEP implement it and add the correct entry to here , so that you can refer from--><!--any operation --><!--Note : You can override this for a particular service by adding the same element with your requirement--><messageReceivers><messageReceiver mep="/2004/08/wsdl/in-only"class="org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver"/> <messageReceiver mep="/2004/08/wsdl/in-out"class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/><messageReceiver mep="/2006/01/wsdl/in-only"class="org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver"/> <messageReceiver mep="/2006/01/wsdl/in-out"class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/> <messageReceiver mep="/ns/wsdl/in-only"class="org.apache.axis2.receivers.RawXMLINOnlyMessageReceiver"/> <messageReceiver mep="/ns/wsdl/in-out"class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/> </messageReceivers><!-- ================================================= --><!-- Message Formatter --><!-- ================================================= --><!--Following content type to message formatter mapping can be used to implement support for different message --><!--format serialization in Axis2. These message formats are expected to be resolved based on the content type. --><messageFormatters><messageFormattercontentType="application/x-www-form-urlencoded"class="org.apache.axis2.transport.http.XFormURLEncodedFormatter"/> <messageFormatter contentType="multipart/form-data"class="org.apache.axis2.transport.http.MultipartFormDataFormatter"/> <messageFormatter contentType="application/xml"class="org.apache.axis2.transport.http.ApplicationXMLFormatter"/> <messageFormatter contentType="text/xml"class="org.apache.axis2.transport.http.SOAPMessageFormatter"/> <messageFormatter contentType="application/soap+xml"class="org.apache.axis2.transport.http.SOAPMessageFormatter"/> </messageFormatters><!-- ================================================= --><!-- Message Builders --><!-- ================================================= --><!--Following content type to builder mapping can be used to implementsupport for different message --><!--formats in Axis2. These message formats are expected to be resolved based on the content type. --><messageBuilders><messageBuilder contentType="application/xml"class="org.apache.axis2.builder.ApplicationXMLBuilder"/><messageBuilder contentType="application/x-www-form-urlencoded"class="org.apache.axis2.builder.XFormURLEncodedBuilder"/><messageBuilder contentType="multipart/form-data"class="org.apache.axis2.builder.MultipartFormDataBuilder"/> </messageBuilders><!-- ================================================= --><!-- Transport Ins --><!-- ================================================= --><!-- The default configuration assumes that AxisServlet only receives requeststhrough HTTP. To allow HTTPS as well, configure a second AxisServletListenerwith name="https" and specify the port parameter on both receivers.For more information, please have a look at the servlet transport documentation:/axis2/java/core/docs/servlet-transport.html--><transportReceiver name="http"class="org.apache.axis2.transport.http.AxisServletListener"/><!--Uncomment if you want to have TCP transport support--><!--transportReceiver name="tcp"class="org.apache.axis2.transport.tcp.TCPServer"><parameter name="port">6060</parameter-->><!--If you want to give your own host address for EPR generation--> <!--uncomment the following paramter , and set it as you required.--> <!--<parameter name="hostname">tcp:///ws</parameter>--> <!-- /transportReceiver --><!-- ================================================= --><!-- Transport Outs --><!-- ================================================= --><!--Uncomment if you want to have TCP transport support--><!--<transportSender name="tcp"class="org.apache.axis2.transport.tcp.TCPTransportSender"/>--><transportSender name="local"class="org.apache.axis2.transport.local.LocalTransportSender"/> <transportSender name="http"class="monsHTTPTransportSender"> <parameter name="PROTOCOL">HTTP/1.1</parameter><parameter name="Transfer-Encoding">chunked</parameter><!-- If following is set to 'true', optional action part of the Content-Type will not be added to the SOAP 1.2 messages --><!-- <parameter name="OmitSOAP12Action">true</parameter> --> </transportSender><transportSender name="https"class="monsHTTPTransportSender"> <parameter name="PROTOCOL">HTTP/1.1</parameter><parameter name="Transfer-Encoding">chunked</parameter> </transportSender><!-- Please enable this if you need the java transport --><!-- <transportSender name="java"class="org.apache.axis2.transport.java.JavaTransportSender"/> --><!-- ================================================= --><!-- Global Modules --><!-- ================================================= --><!-- Comment this to disable Addressing --><module ref="addressing"/><!--Configuring module , providing parameters for modules whether they refer or not--><!--<moduleConfig name="addressing">--><!--<parameter name="addressingPara">N/A</parameter>--><!--</moduleConfig>--><!-- ================================================= --><!-- Clustering --><!-- ================================================= --><!--To enable clustering for this node, set the value of "enable" attribute of the "clustering"element to "true". The initialization of a node in the cluster is handled by the classcorresponding to the "class" attribute of the "clustering" element. It is also responsible forgetting this node to join the cluster.--><clusteringclass="org.apache.axis2.clustering.tribes.TribesClusteringAgent"enable="false"><!--This parameter indicates whether the cluster has to be automatically initalizedwhen the AxisConfiguration is built. If set to "true" the initialization will not bedone at that stage, and some other party will have to explictly initialize the cluster.--><parameter name="AvoidInitiation">true</parameter><!--The membership scheme used in this setup. The only values supported at the moment are"multicast" and "wka"1. multicast - membership is automatically discovered using multicasting2. wka - Well-Known Address based multicasting. Membership is discovered with the helpof one or more nodes running at a Well-Known Address. New members joining acluster will first connect to a well-known node, register with the well-known nodeand get the membership list from it. When new members join, one of the well-knownnodes will notify the others in the group. When a member leaves the cluster oris deemed to have left the cluster, it will be detected by the Group MembershipService (GMS) using a TCP ping mechanism.--><parameter name="membershipScheme">multicast</parameter><!--The clustering domain/group. Nodes in the same group will belong to the same multicastdomain. There will not be interference between nodes in different groups.--><parameter name="domain">wso2.carbon.domain</parameter><!--When a Web service request is received, and processed, before the response is sent to theclient, should we update the states of all members in the cluster? If the value ofthis parameter is set to "true", the response to the client will be sent only afterall the members have been updated. Obviously, this can be time consuming. In some cases,such this overhead may not be acceptable, in which case the value of this parametershould be set to "false"--><parameter name="synchronizeAll">true</parameter><!--The maximum number of times we need to retry to send a message to a particular nodebefore giving up and considering that node to be faulty--><parameter name="maxRetries">10</parameter><!-- The multicast address to be used --><parameter name="mcastAddress">228.0.0.4</parameter><!-- The multicast port to be used --><parameter name="mcastPort">45564</parameter><!-- The frequency of sending membership multicast messages (in ms) --><parameter name="mcastFrequency">500</parameter><!-- The time interval within which if a member does not respond, the member will bedeemed to have left the group (in ms)--><parameter name="memberDropTime">3000</parameter><!--The IP address of the network interface to which the multicasting has to be bound to.Multicasting would be done using this interface.--><parameter name="mcastBindAddress">127.0.0.1</parameter><!-- The host name or IP address of this member --><parameter name="localMemberHost">127.0.0.1</parameter><!--The TCP port used by this member. This is the port through which other nodes willcontact this member--><parameter name="localMemberPort">4000</parameter><!--Preserve message ordering. This will be done according to sender order.--><parameter name="preserveMessageOrder">true</parameter><!--Maintain atmost-once message processing semantics--><parameter name="atmostOnceMessageSemantics">true</parameter><!--Properties specific to this member--><parameter name="properties"><property name="backendServerURL" value="https://${hostName}:${httpsPort}/services/"/><property name="mgtConsoleURL" value="https://${hostName}:${httpsPort}/"/></parameter><!--The list of static or well-known members. These entries will only be valid if the"membershipScheme" above is set to "wka"--><members><member><hostName>127.0.0.1</hostName><port>4000</port></member><member><hostName>127.0.0.1</hostName><port>4001</port></member></members><!--Enable the groupManagement entry if you need to run this node as a cluster manager.Multiple application domains with different GroupManagementAgent implementationscan be defined in this section.--><groupManagement enable="false"><applicationDomain name="apache.axis2.application.domain"description="Axis2 group"agent="org.apache.axis2.clustering.management.DefaultGroupManagementA gent"/></groupManagement><!--This interface is responsible for handling management of a specific node in the clusterThe "enable" attribute indicates whether Node management has been enabled--><nodeManagerclass="org.apache.axis2.clustering.management.DefaultNodeManager"enable="true"/><!--This interface is responsible for handling state replication. The property changes inthe Axis2 context hierarchy in this node, are propagated to all other nodes in the cluster.The "excludes" patterns can be used to specify the prefixes (e.g. local_*) orsuffixes (e.g. *_local) of the properties to be excluded from replication. The pattern"*" indicates that all properties in a particular context should not be replicated.The "enable" attribute indicates whether context replication has been enabled--><stateManagerclass="org.apache.axis2.clustering.state.DefaultStateManager"enable="true"><replication><defaults><exclude name="local_*"/><exclude name="LOCAL_*"/></defaults><contextclass="org.apache.axis2.context.ConfigurationContext"><exclude name="local_*"/></context><contextclass="org.apache.axis2.context.ServiceGroupContext"><exclude name="local_*"/></context><contextclass="org.apache.axis2.context.ServiceContext"><exclude name="local_*"/></context></replication></stateManager></clustering><!-- ================================================= --><!-- Phases --><!-- ================================================= --><phaseOrder type="InFlow"><!-- System predefined phases --><phase name="Transport"><handler name="RequestURIBasedDispatcher"class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"><order phase="Transport"/></handler><handler name="SOAPActionBasedDispatcher"class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"><order phase="Transport"/></handler></phase><phase name="Addressing"><handler name="AddressingBasedDispatcher"class="org.apache.axis2.dispatchers.AddressingBasedDispatcher"><order phase="Addressing"/></handler></phase><phase name="Security"/><phase name="PreDispatch"/><phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase"><handler name="RequestURIBasedDispatcher"class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/> <handler name="SOAPActionBasedDispatcher"class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/> <handler name="RequestURIOperationDispatcher"class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/> <handler name="SOAPMessageBodyBasedDispatcher"class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/> <handler name="HTTPLocationBasedDispatcher"class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/> <handler name="GenericProviderDispatcher"class="org.apache.axis2.jaxws.dispatchers.GenericProviderDispatcher"/ ><handler name="MustUnderstandValidationDispatcher"class="org.apache.axis2.jaxws.dispatchers.MustUnderstandValidationDis patcher"/></phase><phase name="RMPhase"/><!-- System predefined phases --><!-- After Postdispatch phase module author or service author can add any phase he want --><phase name="OperationInPhase"><handler name="MustUnderstandChecker"class="org.apache.axis2.jaxws.dispatchers.MustUnderstandChecker"><order phase="OperationInPhase"/></handler></phase><phase name="soapmonitorPhase"/></phaseOrder><phaseOrder type="OutFlow"><!-- user can add his own phases to this area --><phase name="soapmonitorPhase"/><phase name="OperationOutPhase"/><!--system predefined phase--><!--these phase will run irrespective of the service--><phase name="RMPhase"/><phase name="PolicyDetermination"/><phase name="MessageOut"/><phase name="Security"/></phaseOrder><phaseOrder type="InFaultFlow"><phase name="Addressing"><handler name="AddressingBasedDispatcher"class="org.apache.axis2.dispatchers.AddressingBasedDispatcher"><order phase="Addressing"/></handler></phase><phase name="Security"/><phase name="PreDispatch"/><phase name="Dispatch" class="org.apache.axis2.engine.DispatchPhase"><handler name="RequestURIBasedDispatcher"class="org.apache.axis2.dispatchers.RequestURIBasedDispatcher"/><handler name="SOAPActionBasedDispatcher"class="org.apache.axis2.dispatchers.SOAPActionBasedDispatcher"/> <handler name="RequestURIOperationDispatcher"class="org.apache.axis2.dispatchers.RequestURIOperationDispatcher"/> <handler name="SOAPMessageBodyBasedDispatcher"class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher"/> <handler name="HTTPLocationBasedDispatcher"class="org.apache.axis2.dispatchers.HTTPLocationBasedDispatcher"/> <handler name="GenericProviderDispatcher"class="org.apache.axis2.jaxws.dispatchers.GenericProviderDispatcher"/ ><handler name="MustUnderstandValidationDispatcher"class="org.apache.axis2.jaxws.dispatchers.MustUnderstandValidationDis patcher"/></phase><phase name="RMPhase"/><!-- user can add his own phases to this area --><phase name="OperationInFaultPhase"/><phase name="soapmonitorPhase"/></phaseOrder><phaseOrder type="OutFaultFlow"><!-- user can add his own phases to this area --><phase name="soapmonitorPhase"/><phase name="OperationOutFaultPhase"/><phase name="RMPhase"/><phase name="PolicyDetermination"/><phase name="MessageOut"/><phase name="Security"/></phaseOrder></axisconfig>。
如何将基于Axis2的Web Service集成到自己的webapp本文主要描述如何使用Apache开源项目Axis提供的API来实现Web Services并集成到我们的应用程序当中。
本文的读者应有JAVA web 应用开发基础。
应该具有看过WSDL,SOAP,XML等的基本规范。
熟悉Eclipse+MyEclipse开发环境。
一、环境准备使用Axis来开发Web services 需要准备 web 服务器,Axis API。
本文使用的Web container 是Tomcat5.5, Axis API 采用版本2。
1.1软件下载准备Tomcat下载地址:/download-55.cgi#5.5.20Axis标准包:/ws/axis2/1_5_1/axis2-1.5.1-bin.zipAxis War包:/ws/axis2/1_5_1/axis2-1.5.1-war.zip Eclipse+MyEclipse:可以到官方网站下载(本文为3.3+6.5GA)1.2安装A.首先搭建开发环境,需要将下载到的Eclipse解压缩到一个目录。
B.安装MyEclipse6.5GA。
然后启动MyEclipse。
C.下面开始搭建Web Services的部署环境。
将下载的tomcat包解压缩到一个目录。
完成web container的安装。
E.将axis2.war包拷贝到tomcat安装目录下的webapps目录中。
F.启动Tomcat(windows 下为TOMCA_HOME/bin中的startup.bat;Linux,unix环境为startup.sh文件),打开浏览器输入并访问:http://ip:port/axis2来查看。
(如果没有进行配臵文件的修改此地址应该为http://localhost:8080/axis2),如果能看到下面的页面则说明已经安装完成。
二、Quick Start环境准备好后,先从一个简单的例子开始。
Axis2.x WebService上次介绍了axis1.x的用法,这次继续上次的,将叙述axis2的用法。
Axis1.x在线博文:/hoojo/archive/2010/12/20/1911349.html一、准备工作1、开发准备首先需要下载axis2的相关jar包,到axis的官方网站即可获得开发的依赖包。
下载地址:/axis2/java/core/download.cgi现在最高的版本是1.5.4的然后你需要下载官方提供的axis的eclipse插件工具,可以帮助我们打包(aar)及其生产客户端调用代码。
下载页面:/axis2/java/core/tools/index.htmlService Archive Wizard - Eclipse Plug-inCode Generator Wizard - Eclipse Plug-in2、安装eclipse插件如果你的eclipse插件安装成功后,会看到如下效果:3、分析axis2-bin文件目录结构下载下来的axis2的依赖库,其中有一个axis2-1.5.3-bin.zip的库文件,目录结构如下:bin文件夹是axis2的常用工具,其中有将wsdl文件转换成客户端调用的wsdl2java工具及将java转换成wsdl文件的工具conf是axis2的配置文件lib运行所要的依赖库repository是发布过的axis服务和文件sample是示例webapp是web文件和jsp页面等4、我们需要将下载下来的axis2-1.5.3-war.zip中的axis2.war这个文件放在我们的tomcat目录下,启动tomcat就会把war文件转成一个可以跑起来的axis2的项目。
Tomcat启动后,在浏览器中输入:http://localhost:8080/axis2/你可以看到二、Axis2的简单WebService示例注意,上面的HelloWorldService是没有package的。
Axis2与Eclipse整合开发Web Service 系统功能: 开发一个计算器服务CalculateService,这个服务包含加(plus>、减(minus>、乘(multiply>、除(divide>的操作。
开发前准备:1、安装Eclipse-jee;2、下载Axis2的最新版本Axis2 1.4.1 Release,网址/axis2/download/1_4_1/download.cgi ,选择Standard Binary Distribution的.zip包即"axis2-1.4.1-bin.zip"这个文件,解压缩得到的目录名axis2-1.4.1,目录内的文件结构如下:b5E2RGbCAP开发前配置:在Eclipse的菜单栏中,Window --> Preferences --> Web Service --> Axis2Perferences,在Axis2 runtime location中选择Axis2解压缩包的位置,设置好后,点"OK"即行。
<如图)p1EanqFDPw开发Web Service:1、新建一个Java Project,命名为"WS_01";2、新建一个class,命名为"CalculateService",完整代码如下:packagerong.service。
/***//***计算器运算**@authorrongxinhua**/publicclassCalculateService {*加法运算*@paramx被加数*@paramy加数*@returnx与y的和**/publicfloat plus(float x, float y> { return x + y。
}/***//****减法运算*@paramx被减数*@paramy减数*@returnx与y之差**/publicfloat minus(float x, float y> { return x - y。
Axis2 教程文章分类:Java编程Axis2是一套崭新的WebService引擎,该版本是对Axis1.x重新设计的产物。
Axis2不仅支持SOAP1.1和SOAP1.2,还集成了非常流行的REST WebService,同时还支持Spring、JSON等技术。
这些都将在后面的系列教程中讲解。
在本文中主要介绍了如何使用Axis2开发一个不需要任何配置文件的WebService,并在客户端使用Java和C#调用这个WebService。
一、Axis2的下载和安装读者可以从如下的网址下载Axis2的最新版本:/axis2/在本文使用了目前Axis2的最新版本1.4.1。
读者可以下载如下两个zip包:axis2-1.4.1-bin.zipaxis2-1.4.1-war.zip其中axis2-1.4.1-bin.zip文件中包含了Axis2中所有的jar文件,axis2-1.4.1-war.zip文件用于将WebService发布到Web容器中。
将axis2-1.4.1-war.zip文件解压到相应的目录,将目录中的axis2.war文件放到<Tomcat安装目录>\webapps目录中(本文使用的Tomcat的版本是6.x),并启动Tomcat。
在浏览器地址栏中输入如下的URL:http://localhost:8080/axis2/如果在浏览器中显示出如图1所示的页面,则表示Axis2安装成功。
图1二、编写和发布WebService对于用Java实现的服务程序给人的印象就是需要进行大量的配置,不过这一点在Axis2中将被终结。
在Axis2中不需要进行任何的配置,就可以直接将一个简单的POJO发布成WebService。
其中POJO中所有的public方法将被发布成WebService方法。
下面我们来实现一个简单的POJO,代码如下:public class SimpleService{public String getGreeting(String name){return "你好 " + name;}public int getPrice(){return new java.util.Random().nextInt(1000);}}在SimpleService类中有两个方法,由于这两个方法都是public方法,因此,它们都将作为WebService方法被发布。
利用axis2将SSH项目发布成Web Service1. 开发环境eclipse,axis2 war,SSH项目axis2 的eclipse插件:axis2-eclipse-codegen-wizard. 用于生成stub本地代码axis2-eclipse-service-archiver-wizard.zip 用于发布webservice2. 安装过程1.下载完2个插件的文件后,可以挺直把后的文件拷贝到eclipse 的 plugins名目中从axis2 bin 包里找到:backport-util-courrent-3.1.jar 和geronimo-stax-api_1.0_spec-1.0.1.jar 复制到eclipse\plugins\Axis2_Codegen_Wizard_1.3.0\lib 文件夹下。
backport-util-concurrent-3.1.jar 需要在网上downloadsite:/jar/mule/dependencies/maven2/backport -util-concurrent/backport-util-concurrent/3.1/backport-util-c oncurrent-3.1.jar.html 2.修改eclipse\plugins\Axis2_Codegen_Wizard_1.3.0\plugin.xml 文件在 run 內加入下面的字串 libraryname="lib/geronimo-stax-api_1.0_spec-1.0.1.jar" = "appliionContext"class="org.apache.axis2.extensions.spring.receivers.ApplicationCo ntextHolder" / 2.在axis2容器里的web.xml加入如下代码,用于加载spring的配置文件,用于初始化bean listenerlistener-classorg.springframework.web.context.ContextLoaderListener/listener-class /listener context-param param-name contextConfigLocation /param-name param-value/WEB-INF/applicationContext.xml /param-value/context-param 3.名目结构:toat/axis2/WEB-INF 项目的配置文件都放在这里修改配置文件里的一些内容:主要是加载路径相关,eg: bean id="sessionFactory"第1页共2页。
使用axis2构建WebService服务以下文档将介绍是使用Tomcat6.0和Apache Axis2开发、部署和测试一个简单的WebService服务。
本文示例为最简单数据类型。
下一章将介绍复杂数据类型的传输。
WebService让一个程序可以透明地调用互联网程序,不管具体的实现细节。
只要WebService公开了服务接口,远程客户端就可以调用服务。
WebService是基于http协议的组建服务,WebService是分散式应用程序的发展趋势。
1.工作环境MyEclipse6.0.1 + JDK1.6 + Axis2-1.3其中Axis2-1.3需要下载Binary Distribution和WAR这两个文件。
目前Axis2的最高版本已到达1.5.2.安装Axis2将下载的Axis2-1.3 W AR文件解压缩,得到axis2.war文件。
将其拷贝到%Tomcat安装目录%webapps下即可。
3.检验安装启动(或重新启动)Tomcat,在地址栏中输入:http://localhost:8080/axis2点击Validate,显示Axis2 Happiness Page4.WebService中的服务器端(1)新建Java工程(2)新建服务器类,建立Hello.javapackage cn.hxyh.webservice;public class Hello {public String getHello() {System.out.println("Hello Service received");return"Hello world!" ;}}(3)在./bin下建立META-INF目录,新建service.xml文件<service name="Hello"><Description>helloword example description</Description><parameter name="ServiceClass"locked="false">cn.hxyh.webservice.Hello</parameter><operation name="getHello"><messageReceiverclass="org.apache.axis2.rpc.receivers.RPCMessageReceiver" /></operation></service>(4)打包生成aar文件在命令符环境下,将目录转到./bin。
使用axis2进行WebService的开发使用axis2进行WebService的开发Apache Axis2 是Apache Axis SOAP 项目的后继项目。
此项目是Web 服务核心引擎的重要改进,目标是成为Web 服务和面向服务的体系结构(Service-Oriented Architecture,SOA)的下一代平台。
axis2 WebService开发分为服务端开发与客户端开发,服务端开发为对外提供服务,客户端开发为用户调用外部接口进行业务处理。
一、下载与安装1.下载下载地址:/axis2/java/core/download.cgi有以下下载列表:Binary Distribution zip | MD5 | PGPSource Distribution zip | MD5 | PGPWAR Distribution zip | MD5 | PGPDocuments Distribution zip | MD5 | PGP注:axis2-1.6.2-bin.zip里有axis2的jar包。
axis2-1.6.2-docs.zip里有详细的帮助文档。
axis2-1.6.2-src.zip里是源代码。
axis2-1.6.2-war.zip里是axis的管理平台,放到tomcat可直接使用。
注:本文用bin包进行命令行使用axis2,管理平台使用的是war包。
2.安装配置将axis2-1.6.2-bin.zip解压到本地目录D:\axis2-1.6.2设置环境变量。
【注:前提需要配置java环境变量】AXIS2_HOME 设置值D:\axis2-1.6.2Path 添加值%AXIS2_HOME%\bin二、服务端编写1.创建服务端的java项目testAsixServer。
编写类City与类User代码如下:[java] view plain copy package com.hsinghsu.model; public class City { private int cityCode;private String cityName; public int getCityCode() { return cityCode; } public void setCityCode(int cityCode) { this.cityCode = cityCode; } public String getCityName() { return cityName; } public void setCityName(String cityName){ this.cityName = cityName; } } [java] view plain copy package com.hsinghsu.model; public class User { private int id; private String name; private String password;private City city; public int getId(){ return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name){ = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public City getCity(){ return city; } public void setCity(City city) { this.city =city; } }编写服务类UserService。
【wayfoon】最近公司要求实现一个webservice调用,之前也接触过,但只是看看,没有动手试试,于是现在正式开始学习webservice。
之前参照网上的例子写了一个简单的say hello webservice例子。
传递的对象是string,而且只有一个方法;但实际应用中,需要传递一些复制的对象,比如:数组,集合,对象数组。
由于webservice 是通过xml来交互数据的,而且是不分平台的。
因此,java 中的List等集合类的哦是通过数组来实现的。
学习webservice最好不要从一种语言的角度(java、c#)来对待问题,如果非要看成一中语言,那看成是c语言吧。
简单的hello world 例子见/mlzry0612/articles/185209.html?opt=admin里面有详细的axis+myeclipse5.5安装部署,图文并茂。
不同myeclipse版本有所不同。
在演示例子前,你必须已经安装好了Axis,并且已经知道怎样使用axis,知道通过wsdl生成webservice代码和生成aar发布文件。
不会的话,先学习前面的hello 例子。
下面演示一个比较复杂的例子。
例子实现:输入一个string 返回得到一个对象数组(输入里面所有的元素对象),注意是对象数组。
每个对象对应一个bean 实体。
使用axis的好处是可以根据wsdl自动生成大部分代码。
因此,采用axis开发webservice 的实现关键在于生成wsdl文件的编写。
生成wsdl文件可以采用两种方式:第一种:直接新建wsdl再通过wsdl设计器来设计(也就是hello例子里面将的)如果你对wsdl不是很熟悉,而且,输入或输出的参数都非常复杂,不清楚输入输出的组成结构时,你可以采用第二种方法。
这种方式,可以让你使用你最熟悉的语言来表达你的意思。
以java为例,你可以将对个对象放到List里面来表达你要输出的值,这个在 wsdl里面是另外一种表达方式(没有List)。
.一、准备工作。
1、第一下载 eclipse 用于开发 WebService的有关插件。
该插件在 eclipse 站点有下。
我下的是包括该插件的全套eclipse 的 SDK:共 210 兆多。
A、解压该文件;B、安装自己插件,把插件用LINK 目录成立关系。
(如:TOMCAT 等)C、配置好自己的eclipse ,这个不用多说了。
2、下载 TOMCAT 。
我用的是 TOMCAT5.0.16 。
3、下载最新的 AXIS 。
这特别重要。
我从前就是由于使用了旧版的AXIS( AXIS1 。
1 ),最后致使生成的 WEBSERVICE 调用程序编译失败。
此刻我使用AXIS1 。
4A、解压 AXIS ,把 axis-1_4\webapps\axis\WEB-INF\lib中的文件复制到$TOMCATHOME$\common\lib中。
二、开始开发 WEBSERVICE。
1、第一 NEW 一个 PROJECT。
WEB- 》动向 WEB PROJECT。
.2、改变项目的输出路径为:项目名称/WebContent/WEB-INF/classes本来的为:项目名称 /BUILD这样公布 WEB 服务比较方便。
3、成立一个用于公布WEB 服务的 JAVA 类。
. public class HelloBean {public String sayHello(String name){return "hello:" +name;}}4、公布该类为 WEB 服务。
右击 HelloBean.java->web services->create web services将左侧筐拉到最上面( Test service )。
(此后能够立刻测试该web services )其余不用多说。
往下。
直到出现需要启动TOMCAT 的提示。
而后启动TOMCAT ,系统自动把 WEB SERVICE 公布到 TOMCAT 中。
1:准备:JDK:/technetwork/java/javase/downloads/jdk6downloads-1902814. htmleclipse:/downloads/download.php?file=/technology/epp/downloads/ release/juno/SR2/eclipse-jee-juno-SR2-win32.ziptomcat:/download-60.cgiaxis2:/axis2/java/core/download.cgieclipse的官方提供的axis插件工具,可以打包aar文件和生成客户端调用代码:http://axis.apache.o rg/axis2/java/core/tools/index.html其中的Service Archive Wizard - Eclipse Plug-in和Code Generator Wizard - Eclipse Plug-i n下载完成的软件如图1.1图1.12:配置环境:2.1:配置java环境变量(不赘述)。
2.1:eclipse中axis2环境配置:Window->Perferences->Web Services->Axis2 perferences->A xis2 Runtime->Axis2 Runtime location,Browse选择解压axis2-1.6.2-bin.zip得到的axis2-1.6. 2文件目录。
如图2.1。
图2.12.2:安装插件:解压axis2-eclipse-codegen-plugin-1.6.2.zip和axis2-eclipse-service-plugin-1.6.2.zip,把得到的两个jar包放入eclipse目录下的\plugins\中,重启eclipse。
2.3:配置tomcat:解压apache-tomcat-6.0.36-windows-x64.zip(不赘述)。
2.4:eclipse中tomcat配置:Window->Perferences->Server->Runtime Environments添加。
3:发布axis2:3.1:解压axis2-1.6.2-war.zip获得axis2.war并把它放到tomcat解压目录的webapps文件夹下,启动tomcat,浏览器中输入http://localhost:8080/axis2/,出现图3.1,说明配置成功。
图3.13.2:用eclipse的axis2插件发布web服务。
3.2.1 在eclipse中new一个Dynamic Web Project,取名webserviceService。
编写一个简单的w ebService服务器代码1package org.web.service;23publicclass HelloWorldService {4public String sayHello(String name){5return"Hello," + name;6}7}83.2.2 在eclipse的空白workspace处,右键new->Other,在弹出的对话框中,找到Axis2 Service Archiver,双击->选择HelloWorldService所在项目的class路径,如图3.2图3.2next->选中skip WSDL,Next->什么都不填NEXT->选中Generate the service xml automatical ly,NEXT->图3.3如如图3.3填写HelloWorldService类的全路径,点击load,在下面的Method表中出现say Hello说明load成功,点击NEXT->图3.4填写Output file location,点击Finish,如图3.4。
3.2.2 右键点击webServiceService项目,刷新。
出现my_service.aar文件,如图3.5。
图3.5把此aar文件放到%tomcat_home%\webapps\axis2\WEB-INF\services下。
浏览器中输入http:/ /localhost:8080/axis2/services/HelloWorldService?wsdl,出现图3.6,说明发布成功。
图3.64:用eclipse的Web Service Client生成客户端调用代码。
4.1:在eclipse的空白workspace处右键new->Other->Web services->Web Service Client,选中,点击N E X T->出现图4.1图4. 1service definition填发布好的wsdl路径http://localhost:8080/axis2/services/HelloWorldServi ce?wsdl,Client type默认,下面的下滑快拉到最上面,点击Server runtime:Tomcat v6.0 Serv er出现图4.2:图4.2在Server runtime中选择默认,Web service runtime选择Apache Axis2,点击Ok,返回图4.1,点击C l i e n t p r o j e c t:w e b S e r v i c e C l i e n t,出现图4.3图4.3在Client project的下拉列表中选择客户端代码存放的项目,本例选择webServiceClient。
点击OK,返回图4.1,点击NEXT,进入下一个环节,然后点击Finish。
,图4.4如图4.4,在src的source folder下出现org.web.service包,下面有HelloWorldServiceCallBack Handler.java和HelloWorldServiceStub.java文件,Web App Libraries也有更新,在WebConte nt目录下也出现axis2-web文件夹,以及WEB-INF等的更新。
4.2:写webService调用代码。
在webServiceClient项目中新建一个客户端测试文件如下:1package org.web.client;23import java.rmi.RemoteException;45import org.web.service.HelloWorldServiceStub;6import org.web.service.HelloWorldServiceStub.SayHelloResponse;78publicclass HelloWorldClient {910/**11* @param args12* @throws RemoteException13*/14publicstaticvoid main(String[] args) throws RemoteException {15String target = "http://localhost:8080/axis2/services/HelloWorldService";16HelloWorldServiceStub stub = new HelloWorldServiceStub(target);17// sayHello为webService提供参数18HelloWorldServiceStub.SayHellosayHello = new HelloWorldServiceStub.SayHell o();19sayHello.setName("jackii");20SayHelloResponseeur = stub.sayHello(sayHello);21String returnVal = eur.get_return();22System.out.println(returnVal);23}2425}运行上面代码Run As->Java Application,输出:Hello,jackii说明调用成功。
5:参考文档/view/12501ed7195f312b3169a54b.html6:服务端接收的参数为javaBean,返回list样例:6.1:创建服务。
新建User.java1package org.web.service;23publicclass User {4private String id;5private String name;6public String getId() {7return id;8}9publicvoid setId(String id) {10this.id = id;11}12public String getName() {13return name;14}15publicvoid setName(String name) { = name;17}18}19ListService.java1package org.web.service;23import java.util.ArrayList;4import java.util.List;56publicclass ListService {7public List<User>getUserList(User user){8List<User>returnList = new ArrayList<User>(); 9returnList.add(user);10for(int i=0;i<3;i++){11User user1 = new User();12user1.setId("00"+i);13user1.setName("jack00"+i);14returnList.add(user1);15}16return returnList;17}18}文件目录如图6.1:图6.1按照3.2说明重新发布服务(图3.4Output File Name重新起个名字)6.2:创建客户端调用代码,步奏同4。
得到图6.2所示两个文件ListServiceStub.java和ListService CallbackHandler.java图6.2创建ListServiceClient.java1package org.web.client;23import java.rmi.RemoteException;45import org.web.service.ListServiceStub;6import org.web.service.ListServiceStub.GetUserListResponse;7import er;89publicclass ListServiceClient {1011/**12* @param args13* @throws RemoteException14*/15publicstaticvoid main(String[] args) throws RemoteException {16String target = "http://localhost:8080/axis2/services/ListService";17ListServiceStub stub = new ListServiceStub(target);18ListServiceStub.GetUserList getUserList0 = new ListServiceStub.GetUserList(); 19User user = new User();20user.setId("clientTest");21user.setName("ClientName");22getUserList0.setUser(user);23GetUserListResponseeur = stub.getUserList(getUserList0);24User[] userArray = eur.get_return();25for(int i=0;i<userArray.length;i++){26System.out.println("id:"+userArray[i].getId()+"name:"+userArray[i].getName ()+"\n");27}28}29}以java application方式运行,输出:1id:clientTestname:ClientName23id:000name:jack00045id:001name:jack00167id:002name:jack002说明调用成功。