SOAP与AXIS2入门教程(附带实例)

来源:互联网 发布:网络英语教学哪家好 编辑:程序博客网 时间:2024/05/19 16:51
最近项目需要用到SOAP以及AXIS2的知识,在学习之余,将第一天学到的内容整理了一下,一来做为笔记做个记录,二来如果有需要的,可以做为参考,今天主要是完成了一下功能,通过一个SOAP请求消息(可以自己构造也可以通过指定一个xml文件),然后在Web Service中获取这个SOAP请求消息(一个OMElement对象),通过解析这个对象,获取需要的信息,然后对这些信息进行业务处理,最后返回一个SOAP响应消息。
获取AXIS2 1.1,由于做项目一般使用稳定的发布版本,所以本文没有使用最新的AXIS2 1.1.1版本,该版本可以从Apache官方网站下载。下载地址如下:
http://ws.apache.org/axis2/download/1_1/download.cgi
在上面连接中,有三个版本的axis2可以供下载,分别是:Standard Binary Distribution,Source Distribution,WAR (Web Archive) Distribution,其中标准版可以直接独立使用(Stand-alone),源代码版本需要使用maven进行构建,同时允许开发人员自己修改源代码,本文使用的是WAR版本,可以直接发布在WEB容器中(本文使用的是Tomcat5.5.17)。在上面的链接中还有一个是DOCS的下载,最好一并下载,docs中包含用户手册,快速上手指南,以及其他相关文档,对了解并熟悉AXIS2很有帮助。
闲话少说,将已经下载的WAR包发布(拷贝+粘贴)到%TOMCAT_HOME%/webapps/目录下,其中%TOMCAT_HOME%以Tomcat安装目录进行替换。启动Tomcat,在IE地址栏中键入:http://localhost:8080/axis2,如果部署成功,即可看到欢迎页面,一般情况下不会出现什么错误。
进入主页之后,可以通过进入Administration链接来管理WEB服务,其中初始化用户名和密码分别为admin/axis2。一般情况下,在管理控制台下进行操作比较方便,但是本文将直接进行操作系统目录级的操作(不会使用UploadServices进行发布服务,而是直接将*.aar拷贝到%TOMCAT_HOME%/webapps/axis2/WEB-INF/services目录下)。
下面我们建立自定义的WEB服务:
我们要将类似以下XML格式的SOAP请求转换为SOAP响应,并获取SOAP请求中的关键元素,进行业务操作,本例子中只是简单的将数值拷贝,没有进行实际的业务操作,但是在代码中进行了指示:
SOAP请求:
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope>
 <soap:Header />
 <soap:Body>
    <RevokeCertRequest>
      <Issuer>ABC</Issuer>
      <Serial>DEF</Serial>
      <RevocationDate>GHI</RevocationDate>
    </RevokeCertRequest>
 </soap:Body>
</soap:Envelope>
 
SOAP响应:
<?xml version="1.0" encoding="utf-8" ?>
<soap:Envelope>
 <soap:Header />
 <soap:Body>
    <RevokeCertResponse>
      <RevokeDate>GHI</RevokeDate>
    </RevokeCertResponse>
 </soap:Body>
</soap:Envelope>
 
 
在实际应用中,我们可能要获取ABC,DEF,GHI来进行业务处理,最后返回一个其他的消息,但是在示例中,我们仅仅获取ABC,DEF,GHI,然后打印出来,并返回GHI。
 
Step1.建立工程并创建文件
建立如下图所示的JAVA工程(工程的源代码路径与编译后路径不同,源代码为project/src,编译后为project/bin):首先建立一些类,然后创建serives.xml,最后建立build.xml文件(ANT的构建文件,为了方便测试与构建,所以使用了ANT)
 
下面是这些文件的内容:
 
RevokeService.java(这个是进行WEB服务的类):
package newsdes.support.service;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
 
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;
 
public class RevokeService {
 
      /**
       * The request soap message object.
       */
      public static OMElement requestSoap = null;
 
      /**
       * Write the soap response message to xml file.
       *
       * @param res
       *            The resource of that forms the xml file.
       * @param filePath
       *            The path where the xml file be stored.
       */
      private static void writeResponse(String res, String filePath) {
           try {
                 FileOutputStream fos = new FileOutputStream(filePath);
                 byte[] bytes = res.getBytes();
                 fos.write(bytes);
                 fos.close();
           } catch (FileNotFoundException e) {
                 e.printStackTrace();
           } catch (IOException e) {
                 e.printStackTrace();
           }
      }
 
      /**
       * Generate the path where the xml file is stored.
       *
       * @param fileName
       * @return
       */
      private static String makePath(String fileName) {
           String path =
"C:/eclipse/workspace/SDES_Enhance/data/" + fileName;
           return path;
      }
//主要的WEB服务方法
      public OMElement RevokeCertRequest(OMElement soapBody) {
           requestSoap = soapBody;
           QName issuerName = new QName("Issuer");
           QName serialName = new QName("Serial");
           QName revocationDateName = new QName("RevocationDate");
           OMElement issuerElement =
requestSoap.getFirstChildWithName(issuerName);
           OMElement serialElement =
requestSoap.getFirstChildWithName(serialName);
           OMElement revocationDateElement = requestSoap
                      .getFirstChildWithName(revocationDateName);
           String issuer = issuerElement.getText();
           String serial = serialElement.getText();
           String revocationDate = revocationDateElement.getText();
           // print out the value
           System.out.println(issuer);
           System.out.println(serial);
           System.out.println(revocationDate);
 
           // TODO use "issuer,serial,revocationDate" to do business
 
           // Generate the soap response message
           OMFactory soapFactory = OMAbstractFactory.getOMFactory();
           OMNamespace omNs = soapFactory.createOMNamespace(
                      "http://www.sdes.net/", "");
           OMElement soapResponse = soapFactory.createOMElement(
                      "RevokeCertResponse", omNs);
           OMElement soapMain = soapFactory.createOMElement("RevokeDate", omNs);
           soapMain.setText(revocationDate);
           soapResponse.addChild(soapMain);
           soapResponse.build();
           String path = makePath("resMsg.xml");
           writeResponse(soapResponse.toString(), path);
           return soapResponse;
      }
}
 
该Service类主要实现了将传入的参数OMElement进行解析,获取其中的Issuer,Serial以及RevocationDate元素的值,然后进行业务处理(蓝色部分,省略)。然后根据业务操作结果,将响应返回。(这里仅仅是将内容写入到一个XML文件中)。
 
services.xml(WEB服务的配置文件,放置在META-INF目录下):
<serviceGroup>
      <service name="CertRevokeService">
           <description>
                 This is the service for revoking certificate.
           </description>
           <parameter name="ServiceClass" locked="false">
                  newsdes.support.service.RevokeService
           </parameter>
           <operation name="RevokeCertRequest">
                 <messageReceiver
                      class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver" />
                 <actionMapping>urn:RevokeCertRequest</actionMapping>
           </operation>
      </service>
</serviceGroup>
其中serviceGroup中可以包含多个service,如果只有一个的时候,可以省略外层的serviceGroup元素。服务名为CertRevokeService。主要业务操作为RevokeCertRequest
红色部分标志了进行WEB服务的主要类。
 
Step2:进行打包
首先编写build.xml文件,为了简便(只是个例子,所以任务也比较简单,只是将project/bin目录下的内容进行JAR打包,文件名为SDES_Enhance.aar,其中.aar为AXIS2的应用的后缀名。)
<projectname="SDES_Enhance"default="deploy"basedir=".">
      <description>
            Deploy SDES_Enhance Services
    </description>
      <propertyname="dist"value="${basedir}/dist"/>
      <propertyname="service"value="C:/Tomcat5.5/webapps/axis2/WEB-INF/services"/>
      <targetname="init">
           <echo>Initializing the environment!</echo>
           <deletedir="${dist}"/>
           <deletedir="${basedir}/data"/>
           <mkdirdir="${dist}"/>
           <mkdirdir="${basedir}/data"/>
      </target>
      <targetname="jar"depends="init">
           <echo>Compressing files to .aar file!</echo>
           <jarbasedir="${basedir}/bin"destfile="${dist}/SDES_Enhance.aar"/>
      </target>
      <targetname="deploy"depends="jar">
           <echo>Deploying service!</echo>
           <copytodir="${service}">
                 <filesetdir="${dist}">
                      <includename="SDES_Enhance.aar"/>
                 </fileset>
           </copy>
      </target>
</project>
 
打包完成后,直接将SDES_Enhance.aar部署到
%TOMCAT_HOME%/webapps/axis2/WEB-INF/services目录下,在TOMCAT启动情况下,会进行HOT-DEPLOY,直接部署完成,在http://localhost:8080/axis2/axis2-admin/listService下刷新,可以看到部署的服务:CertRevokeService。如下图所示:
 
Step3:编写客户端测试代码:
建立测试类:TestCertRevokeService(通过构造一个SOAP请求对象,传入给服务,来实现返回一个SOAP响应的XML文件):
TestCertRevokeService.java
package com.neusoft.service.test;
 
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.axis2.AxisFault;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
 
public class TestCertRevokeService {
      private static EndpointReference targetEPR = new EndpointReference(
                 "http://localhost/axis2/services/CertRevokeService");
 
      public static OMElement getSoapRequestMessage() {
           OMFactory factory = OMAbstractFactory.getOMFactory();
           OMNamespace omNs =
factory.createOMNamespace("http://www.sdes.net", "");
           OMElement issuer = factory.createOMElement("Issuer", omNs);
           OMElement serial = factory.createOMElement("Serial", omNs);
           OMElement revocationDate =
factory.createOMElement("RevocationDate",
                      omNs);
           issuer.setText("C=JP,O=FX,CN=SDES CA");
           serial.setText("1234567890");
           revocationDate.setText("2007-01-01T00:00:00.000Z");
 
           OMElement requestSoapMessage = factory.createOMElement(
                      "RevokeCertRequest", omNs);
           requestSoapMessage.addChild(issuer);
           requestSoapMessage.addChild(serial);
           requestSoapMessage.addChild(revocationDate);
           requestSoapMessage.build();
           return requestSoapMessage;
      }
 
      /**
       * @param args
       */
      public static void main(String[] args) {
           OMElement requestSoapMessage = getSoapRequestMessage();
           Options options = new Options();
           options.setTo(targetEPR);
           ServiceClient sender = null;
           try {
                 sender = new ServiceClient();
                 sender.setOptions(options);
                 sender.sendReceive(requestSoapMessage);
           } catch (AxisFault e) {
                 System.out.println(e.getFaultElements().toString());
           }
      }
}
 
其中,Options对象的setTo方法一定要写正确,这是将SOAP请求发送的终点,如果书写不对,将不能通过WEB服务来处理请求。
 
执行TestCertRevokeService类,可以看到在控制台(Tomcat)的控制台打印出了在CertRevokeService中要打印的消息。
 

 
原创粉丝点击