Soap and AXIS2 Introductory tutorial (with instance)

Source: Internet
Author: User
Tags gettext soap mkdir web services tomcat
Recent projects need to use soap and AXIS2 knowledge, in addition to learning, the first day to learn the content of a bit, as a note to do a record, and secondly if there is a need, can be used as a reference, today is mainly completed a bit of function, Through a SOAP request message (which can be constructed by itself or by specifying an XML file), the SOAP request message (a Omelement object) is obtained in the Web service, the object is parsed, the information is obtained, and the information is then processed for business. Finally, a SOAP response message is returned. Get AXIS2 1.1, because doing projects generally use a stable release version, so this article does not use the latest version of AXIS2 1.1.1, which can be downloaded from the official Apache website. The download address is as follows: http://ws.apache.org/axis2/download/1_1/download.cgi in the above connection, there are three versions of the axis2 available for download, respectively: Standard BinaryDistribution,source Distribution,war (Web Archive) distribution, where the Standard Edition can be used directly (stand-alone), the source code version needs to be built using MAVEN, While allowing developers to modify the source code themselves, this article uses the war version, which can be published directly in the Web container (this article uses Tomcat5.5.17). There is also a download of docs in the link above, preferably in a downloadable document containing user manuals, quick-start guides, and other related documentation, which is helpful for understanding and familiarizing with AXIS2. For less gossip, publish (copy + paste) The already downloaded war package to the%tomcat_home%/webapps/directory, where%tomcat_home% is replaced with the TOMCAT installation directory. To start Tomcat, type: Http://localhost:8080/axis2 in the IE Address bar, you can see the Welcome page if the deployment is successful, and there is generally no error. After you enter the home page, you can manage the Web service by entering the administration link, where the user name and password are initialized to Admin/axis2 respectively. Under normal circumstances, it is convenient to operate under the management console, but this article will do the operating system directory-level operations directly (do not use uploadservices for publishing services, but directly copy the *.aar to%tomcat_home%/webapps/axis2/ Web-inf/services directory). Here we build a custom Web service: We want to convert a SOAP request like the following XML format into a SOAP response and get the key elements in the SOAP request for business operations, this example simply copies the values and does not perform the actual business operations, but is instructed in the code: SOAP request: <?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 response: <?xml version= "1.0" encoding= "Utf-8"?> <soap:Envelope>  <soap:header/>  <soap:Body>     <RevokeCertResponse>       <RevokeDate> ghi</revokedate>      </RevokeCertResponse>  </soap:Body> </soap:Envelope>     in real-world applications, we may want to get ABC, Def,ghi for business processing and finally returns an additional message, but in the example we just get Abc,def,ghi, print it out, and return to GHI.   STEP1. Building a project and creating a file Create a Java project as shown in the following figure (the source code path of the project is different from the post-compilation path, and it is project/src and compiled to Project/bin): First, set up some classes, Then create the Serives.xml, and finally build the Build.xml file (ant's Build file, in order to facilitate testing and build, so using ant)   The following are the contents of these files:   Revokeservice.java ( This is the Web service Class): 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 fi Le.        *        * @param res         *            the resource of that forms the XML File.        * @param filePath        *             the Path wherE The XML file is 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;      //Main Web service methods       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 doing 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; The service class primarily implements parsing of incoming parameter omelement, obtaining the value of issuer,serial and revocationdate elements in it, and then doing business processing (blue part, omitting). The response is then returned based on the result of the business operation.   (This is simply writing the content into an XML file.) Services.xml (Web service configuration file, placed in the Meta-inf directory): < 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 > </servic Egroup > where servicegroup can contain multiple service, if there is only one, you can omit the outer servicegroup element. Service name is Certrevokeservice 。 The main business operation is revokecertrequest. The red section marks the main class for WEB services.   STEP2: Packaging First write the Build.xml file, for the sake of simplicity (just an example, so the task is relatively simple, just the contents of the Project/bin directory for Jar Packaging, the file name is Sdes_ Enhance.aar, where. AAR is the suffix of the AXIS2 application. ) <project name= "sdes_enhance" default= "Deploy" basedir= "." >       <description >             Deploy sdes_enhance Services      </description>       <property name= "dist" value= "${basedir}/dist"/> & nbsp;     <property name= "service" value= "c:/tomcat5.5/webapps/axis2/web-inf/services"/ >       <target name= "Init" >             <echo> Initializing the environment! </echo>            <delete dir= "${dist}"/>             <delete dir= "${basedir}/data "/>            <mkdir dir=" ${dist} "/>             <mkdir dir= "${basedir}/data"/>        </target>       <target name= "jar" depends= "init" >    & nbsp;       <echo> compressing files to. AAR file! </echo>            <jar basedir= "${basedir}/bin" destfile= "${dist}/sdes_enhance.aar"/>       </target>        <target name= "deploy" depends= "jar" >            < Echo> Deploying service! </echo>            <copy todir= "${service}" >                   <fileset dir= "${dist}" >                        <include name= "Sdes_enhance.aar"/>                   </fileset>             </copy>       </target > </project>   After packaging is complete, deploy Sdes_enhance.aar directly to the%tomcat_home%/webapps/axis2/web-inf/services directory, In the case of Tomcat boot, the Hot-deploy is performed, the direct deployment is complete, the http://localhost:8080/axis2/axis2-admin/listService is refreshed, and you can see the deployed services: Certrevokeservice。 As shown in the following illustration: Step3: Writing the client Test code: Building the Test class: Testcertrevokeservice (by constructing a SOAP request object, passing it to the service to implement an XML file that returns a SOAP response):   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");

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.