axis 2 웹 서비스 입문 학식 (JS, Java, PHP 호출 인 스 턴 스 소스)

17894 단어
원본:http://www.myexception.cn/web/952419.html
 
axis 2 웹 서비스 입문 지식 (JS, Java, PHP 호출 인 스 턴 스 소스)
배경 프로필
최근 에 은행 인 터 페 이 스 를 접 한 사건 은 axis 2 웹 서 비 스 를 임시로 사용 해 야 한다.자신 이 지금 배우 고 정리 한 것들 을 초보 자 에 게 남 겨 두다.시행 착오.
Axis 2 소개
① AXIOM (AXIS Object Model) 이라는 새로운 핵심 XML 처리 모델 을 적용 하고, 새로운 XML 해석 기 가 제공 하 는 유연성 을 필요 에 따라 대상 모델 을 구축한다.
② 서로 다른 메시지 교환 모드 를 지원 합 니 다.현재 Axis 2 는 In - Only, Robust - In, In - Out 세 가지 모드 를 지원 합 니 다.In - Only 메시지 교환 모드 는 응답 이 필요 없 이 SOAP 요청 만 있 습 니 다.Robust - In 메시지 교환 모드 에서 SOAP 요청 을 보 내 고 오류 가 발생 한 경우 에 만 응답 을 되 돌려 줍 니 다.In - Out 메시지 교환 모드 에는 항상 SOAP 요청 과 응답 이 존재 합 니 다.
③ 차단 과 비 차단 클 라 이언 트 API 를 제공 합 니 다.
④ 내 장 된 웹 서비스 주소 지정 (WS - Addressing) 을 지원 합 니 다.
⑤ 유연 한 데이터 바 인 딩 은 AXIOM 을 직접 사용 하고 기 존의 Axis 와 비슷 한 간단 한 데이터 바 인 딩 방법 을 사용 하거나 XMLbean, JiBX 또는 JAXB 2.0 등 전용 데이터 바 인 딩 프레임 워 크 를 사용 할 수 있다.
⑥ 새로운 배치 모델 로 열 배 치 를 지원 합 니 다.
⑦ HTTP, SMTP, JMS, TCP 전송 프로 토 콜 을 지원 합 니 다.
⑨ REST (Representational State Transfer) 를 지원 합 니 다.
테스트 환경
【jdk1.6.0】 +【tomcat-6.0.18】 + 【axis2-1.6.1】+【PHP Version 5.3.5】
최소 지원 설정 을 테스트 하지 않 았 습 니 다.
환경 준비
1. Axis 2 환경 배치.
1. 다운로드 설치
apache 홈 페이지 다운로드 주소:http://ws.apache.org/axis2/  Standard Binary Distribution 과 WAR Distribution 을 선택 하 십시오.
2. 시스템 환경 변수 설정:
① AXIS 2 추가HOME 변 수 는 Standard Binary Distribution 의 압축 해제 대상 디 렉 터 리 를 가리 키 고 있 습 니 다.예 를 들 어 $AXIS 2HOME$ =D:\axis2-1.6.1;
② axis 2. bat 가 있 는 디 렉 터 리 를 시스템 환경 변수 path 에 추가 합 니 다.예 를 들 어 D: \ axis 2 - 1.6.1 \ \ bin 을 path 기 존 값 의 맨 뒤에 추가 합 니 다.
③ $AXIS2HOME $\ lib 를 시스템 환경 변수 classpath 에 추가 합 니 다.예 를 들 어 D: \ axis 2 - 1.6.1 \ \ lib 를 classpath 기 존 값 의 맨 뒤에 추가 합 니 다.
3. WAR Distribution 을 $tomcat 로 압축 해제홈 $\ webapps \ \ axis 2 아래 (새 axis 2 폴 더), 물론 axis 2 문서 에 열 거 된 절 차 를 참조 하여 ant 를 사용 하여 axis 2. war 를 만 들 고 $tomcat 에 넣 을 수 있 습 니 다.홈 $\ 웹 앱 에서 tomcat 를 시작 하면 tomcat 는 웹 앱 에서 자동 으로 axis 2 폴 더 를 만 듭 니 다.
2. Axis 2 환경 테스트.
1. 방문http://localhost:[port] / axis 2 ([port] 를 Tomcat 대응 포트 로 변경 하 십시오. 기본 값 은 8080 입 니 다).axis 2 환영 인터페이스 에 들 어 갔 습 니 다."Validate" 를 클릭 합 니 다.
만약 잘못 보고 한 것 이 있다 면, 잘못된 정보 에 따라 상술 한 절 차 를 검사 해 야 한다.잘못된 정보 가 없다 면 Axis 2 의 환경 테스트 는 통과 한 셈 이다.
2. "Administration" 을 클릭 하고 초기 사용자 이름과 비밀 번 호 를 사용 할 수 있 습 니 다: admin;axis 2 로그 인, System Components 및 Upload Service Tools 를 사용 할 수 있 습 니 다.새 arr 파일 을 배 치 했 습 니 다.별도로 $tomcat홈 $\ webapps \ \ axis 2 \ \ WEB - INF \ conf \ \ axis 2. xml 에서 사용자 이름과 비밀 번 호 를 수정 합 니 다.
데모 HelloWorld 만 들 기
1. 서비스 개발
1. 자바 프로젝트 만 들 기
2. 새로운 클래스 HelloWorld. java
참조 코드:
package sample;
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 HelloWorld {
public OMElement sayHello(OMElement in){
String name=in.getText();
String info="  "+name+",    http://www.sietoo.com";
OMFactory fac=OMAbstractFactory.getOMFactory();
OMNamespace omNs=fac.createOMNamespace("http://www.sietoo.com/","hw");
OMElement resp=fac.createOMElement("sayHelloResponse",omNs);
resp.setText(info);
return resp;
}
}

3. 새 파일 META - INF \ services. xml 참조 코드:
<?xml version="1.0" encoding="UTF-8"?>
<service name="HelloWorld">
<description>
This is a sample Web Service.
</description>
<parameter name="ServiceClass" locked="false">sample.HelloWorld</parameter>
<operation name="sayHello">
<messageReceiver class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
</operation>
</service>

2. 프로젝트 를 포장 하고 발표 합 니 다. 1. 익숙 한 IDE 를 사용 하여 HelloWorld. aar 로 포장 할 수 있 습 니 다. 직접 포장 방식 을 참고 하 십시오. 명령 줄 에서 현재 디 렉 터 리 를 이 프로젝트 패키지 로 전환 합 니 다.블 로 거들 의 예 를 들 어 Sample 이 있 는 폴 더 로 전환 해 야 합 니 다. Sample 으로 전환 하 는 것 이 아 닙 니 다.다음 명령 을 사용 하 십시오: jar cvf HelloWorld. aar. 현재 디 렉 터 리 에 HelloWorld. aar 를 생 성 합 니 다.명령 의 끝 점 에 주의 하 세 요. "2. 앞서 언급 한 로그 인 axis 2 를 사용 한 후 보 이 는 Upload Service 도 구 를 사용 하여 Hello World. arr 를 Tomc 에 배치 합 니 다.3. 블 로 거 사례 방문 등 테스트 발표http://localhost:8088/axis2/services/HelloWorld?wsdl2 단계 에 배 치 된 HelloWrold 의 설명 파일 을 봅 니 다.만약 잘못 보고 한 것 이 있다 면, 잘못된 정보 에 따라 상술 한 절 차 를 검사 해 야 한다.잘못된 정보 가 없다 면 Hello World 의 서비스 단 은 완 료 된 셈 입 니 다.3. 간단 한 클 라 이언 트 호출 1. 간단 한 자바 호출 클 라 이언 트.참조 코드:
package example.client;
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.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
public class TestClient {
       private static EndpointReference targetEPR=new EndpointReference
         ("http://localhost:8080/axis2/services/HelloWorld");
       public static OMElement getSayHelloOMElement(){
              OMFactory fac=OMAbstractFactory.getOMFactory();
              OMNamespace omNs=fac.createOMNamespace("http://www.sietoo.com/","hw");
              OMElement method=fac.createOMElement("sayHello",omNs);
              method.setText("andy");
              return method;
       }
       public static void main(String[] args){
              try{
                     Options options=new Options();
                     options.setTo(targetEPR);
                     ServiceClient sender=new ServiceClient();
                     sender.setOptions(options);
                     OMElement sayHello=TestClient.getSayHelloOMElement();
                     OMElement result=sender.sendReceive(sayHello);
                     System.out.println(result);
              }
              catch(Exception axisFault){
                     axisFault.printStackTrace();
              }
       }
}

이 파일 을 컴 파일 하고 실행 합 니 다.만약 잘못 보고 한 것 이 있다 면, 잘못된 정보 에 따라 상술 한 절 차 를 검사 해 야 한다.잘못된 정보 가 없 으 면 데모 헬 로 월 드 는 완 성 됩 니 다.각종 클 라 이언 트 호출 실례 1, java 호출 axis 2 웹 서비스 (단일 매개 변수 와 여러 매개 변수 방법의 호출 포함) 참조 코드:
package example.client;

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.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
public class s2 {
private static EndpointReference targetEPR=new EndpointReference("http://www.sietoo.com/axis2/services/SVAMobileWebService");
public static OMElement getSayHelloOMElement(){
OMFactory fac=OMAbstractFactory.getOMFactory();
OMNamespace omNs=fac.createOMNamespace("http://www.sietoo.com","andy");

//    bandMobileNo (     )
OMElement bandMobileNo=fac.createOMElement("bandMobileNo",omNs);
OMElement UserId=fac.createOMElement("UserId",omNs);
OMElement password=fac.createOMElement("password",omNs);
OMElement bindingBank=fac.createOMElement("bindingBank",omNs);
UserId.addChild(fac.createOMText(UserId, "18629078140"));
password.addChild(fac.createOMText(password, "mynewpassword"));
bindingBank.addChild(fac.createOMText(bindingBank, "622260062001991159"));
bandMobileNo.addChild(UserId);
bandMobileNo.addChild(password);
bandMobileNo.addChild(bindingBank);
return bandMobileNo;

//    getAccountInfo (     )
//OMElement getAccountInfo=fac.createOMElement("getAccountInfo",omNs);
//OMElement accountNum=fac.createOMElement("accountNum",omNs);
//accountNum.addChild(fac.createOMText(accountNum, "18629078140"));
//getAccountInfo.addChild(accountNum);
//return getAccountInfo;
}
public static void main(String args[]){
try{
Options options=new Options();
options.setTo(targetEPR);
ServiceClient sender=new ServiceClient();
sender.setOptions(options);
OMElement sayHello=s2.getSayHelloOMElement();
OMElement result=sender.sendReceive(sayHello);
System.out.println(result);
}
catch(Exception axisFault){
axisFault.printStackTrace();
}}}

2. PHP 는 axis 2 웹 서 비 스 를 호출 합 니 다 (다 중 매개 변 수 를 호출 하지만 매개 변수 방법 포함) 1. Soap 호출 을 사용 합 니 다 (PHP 버 전 지원 이 필요 합 니 다)
<?php
$wsdl='http://www.sietoo.com/axis2/services/SVAMobileWebService?wsdl';
$soap=new SoapClient($wsdl,array( 'trace'=>false,'cache_wsdl'=>WSDL_CACHE_NONE ) );
$soap=new SoapClient($wsdl);
$method="bandMobileNo";
if(isset($_POST['passwd'])&&isset($_POST['UserId'])&&isset($_POST['bindingBank'])){
$params=array( 'UserId'=>$_POST['UserId'],'password'=>$_POST['passwd'],'bindingBank'=>$_POST['bindingBank']);
try{
$result=$soap->$method($params);
echo$result->return;
echo'<br>';
}catch(SoapFault $e){echo $e->getMessage();}
}
?>
<html>
<head>
  <title>bandMobileNo</title>
</head>
<body>
  <form method="Post" action="">
   tel.
   <input type="text" name="UserId" value="18629078888"/>
   

  pwd.
   <input type="password" name="passwd" value="admin" />
   

    cardno.
   <input type="text" name="bindingBank" value="622260062001991159"/>
   

   
    <input type="submit" name="submit" value="Submit"/>
   

  </form>
</body>
</html>

2 Nusoap 호출 사용 (nusoap. php 첨부 다운로드 주소 다운로드 필요:http://download.csdn.net/detail/mr_z_andy/3845711) 다음 과 같은 두 가지 방식 으로 나 뉜 다. ① 직접 호출
<?
/*************************************************************/
/*      : soapclient.php
/*       : WebService       
/*       :www.sietoo.com
/*************************************************************/
include ('NuSoap.php');
//     soapclient  ,   server WSDL
$client = new soapclient ( 'http://localhost/Webservices/Service.asmx?WSDL', 'wsdl' );
//           
$aryPara = array ('strUsername' => 'username', 'strPassword' => MD5 ( 'password' ) );
//       
$aryResult = $client->call ( 'login', $aryPara );
//echo $client->debug_str;
/*
if (!$err=$client->getError()) {
  print_r($aryResult);
} else {
  print "ERROR: $err";
}
*/
$document = $client->document;
echo <<<SoapDocument
<?xml version="1.0" encoding="GB2312"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:si="http://soapinterop.org/xsd">
   <SOAP-ENV:Body>
   $document
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
SoapDocument;
?>

② 대리 호출
<?
/*************************************************************/
/*      : soapclient.php
/*       : WebService       
/*       :www.sietoo.com
/*************************************************************/
require ('NuSoap.php');
//    soapclient  ,   server WSDL
$client = new soapclient ( 'http://localhost/Webservices/Service.asmx?WSDL', 'wsdl' );
//  proxy 
$proxy = $client->getProxy ();
//      
$aryResult = $proxy->login ( 'username', MD5 ( 'password' ) );
//echo $client->debug_str;
/*
if (!$err=$proxy->getError()) {
  print_r($aryResult);
} else {
  print "ERROR: $err";
}
*/
$document = $proxy->document;
echo <<<SoapDocument
<?xml version="1.0" encoding="GB2312"?>
<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:si="http://soapinterop.org/xsd">
   <SOAP-ENV:Body>
   $document
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
SoapDocument;
?>

3. JS 클 라 이언 트 가 axis 2 웹 서 비 스 를 호출 합 니 다 (다 중 매개 변 수 를 호출 하지만 매개 변수 방법 포함) 1 인 스 턴 스 ①
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function RequestWebService() {
            //            Web     
            var URL = "http://localhost/YBWS/WebService.asmx";
            //       
            var data;
            data = '<?xml version="1.0" encoding="utf-8"?>';
            data = data + '<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">';
            data = data + '<soap12:Body>';
            data = data + '<HelloWorld xmlns="http://tempuri.org/" />';
            data = data + '</soap12:Body>';
            data = data + '</soap12:Envelope>';
            //      
            var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            xmlhttp.Open("POST", URL, false);
            xmlhttp.SetRequestHeader("Content-Type", "application/soap+xml");
            xmlhttp.Send(data);
            document.getElementById("data").innerHTML = xmlhttp.responseText;
        }        
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input id="One" type="button" value="JsCallWebService" onclick="RequestWebService()" />
    </div>
    <div id="data">
    </div>
    </form>
</body>
</html>

2. 인 스 턴 스 ② Ajax 를 직접 호출 합 니 다. 아래 에 JS 세그먼트 코드 만 붙 이 는 것 을 추천 하지 않 습 니 다. 참고 하 시기 바 랍 니 다.
var xmlHttp = null;
var bankno=null;
var telno=null;
var checkid=false;
function createXMLHttpRequest() {
   if(window.XMLHttpRequest){
      //Firefox ,Mozillar ,Opera ,Safari ,IE7 ,IE8
       xmlHttp = new XMLHttpRequest();
        //Mozillar    BUG     
       if(xmlHttp.overrideMimeType){
           xmlHttp.overrideMimeType("text/html");
       }
    }else if(window.ActiveXObject){
        //  IE     
        var versions = [ 'Microsoft.XMLHTTP', 'MSXML.XMLHTTP',
     'Microsoft.XMLHTTP', 'Msxml2.XMLHTTP.7.0',
     'Msxml2.XMLHTTP.6.0', 'Msxml2.XMLHTTP.5.0',
     'Msxml2.XMLHTTP.4.0', 'MSXML2.XMLHTTP.3.0',
     'MSXML2.XMLHTTP' ];
        //    XMLHttpRequest  
   for ( var i = 0; i < versions.length; i++) {
    try {
      xmlHttp = new ActiveXObject(versions[i]);
     break;
    } catch (e) {
    }
   }
    }

}

function AsynRequest() {
  createXMLHttpRequest();
  if (xmlHttp == null) 
{
alert("     XmlHttpRequest   ");
return  ;
}
  xmlHttp.open("GET", "http://www.sietoo.com/axis2/services/demoService/doTest?UserId="+telno+"&bindingBank="+"&bindingBank="+bankno, false);
  xmlHttp.setRequestHeader("Connection", "close");
  xmlHttp.onreadystatechange = function () 
{
  if (xmlHttp.readyState == 4) 
{
  if (xmlHttp.status == 200) 
{
if(xmlHttp.responseXML==null)
{
return  ;
}
var res2=xmlHttp.responseXML.getElementsByTagName("ns:return")[0].firstChild.nodeValue;
//res2     。
return  ;
}
}
}
}
xmlHttp.send();
return  ;
}

좋은 웹페이지 즐겨찾기