Apache Axis2 是 Axis 的重寫版本,採用全新 AXIOM (AXIs Object Model) 核心,提供更靈活的 XML 處理與多種訊息交換模式。本文透過 HelloWorld 範例深入解析伺服器端實作、部署描述檔、客戶端呼叫與核心架構特性。
客戶端傳入姓名參數(如 "ZJ"),伺服器端處理後回傳 "ZJHelloWorld!" 字串。
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 {
// 接收客戶端傳入的 OMElement 參數
public OMElement sayHello(OMElement in) {
// 解析輸入參數
String name = in.getText();
String info = name + "HelloWorld!";
// 建立回應 SOAP 訊息
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("https://helloworld.com/", "hw");
OMElement resp = fac.createOMElement("sayHelloResponse", omNs);
resp.setText(info);
return resp;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<service name="HelloWorld">
<description>This is a sample Web Service.</description>
<!-- 指定實作服務的 Java 類別 -->
<parameter name="ServiceClass" locked="false">sample.HelloWorld</parameter>
<operation name="sayHello">
<!-- 使用 Raw XML In-Out 訊息接收器 -->
<messageReceiver class="org.apache.axis2.receivers.RawXMLINOutMessageReceiver"/>
</operation>
</service>
Axis2 支援三種訊息交換模式:
| 模式 | 說明 | 適用場景 |
|---|---|---|
| In-Only | 單向請求,無回應 | 通知、事件發送 |
| Robust-In | 請求僅在錯誤時回應 | 單向但需錯誤處理 |
| In-Out | 請求-回應雙向通訊 | 一般 RPC 風格服務(本範例使用) |
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(
"https://localhost:8080/axis2/services/HelloWorld");
public static OMElement getSayHelloOMElement() {
OMFactory fac = OMAbstractFactory.getOMFactory();
OMNamespace omNs = fac.createOMNamespace("https://helloworld.com/", "hw");
OMElement method = fac.createOMElement("sayHello", omNs);
method.setText("ZJ");
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 = getSayHelloOMElement();
// 同步呼叫並取得回應
OMElement result = sender.sendReceive(sayHello);
System.out.println("回應結果: " + result);
} catch (Exception axisFault) {
axisFault.printStackTrace();
}
}
}
採用延遲建構 (Deferred Building) 技術,僅在必要時解析 XML 節點,大幅降低記憶體消耗與處理延遲。
HTTP、HTTPS、SMTP、JMS、TCP 等多種傳輸層協定
支援 .aar 服務封裝熱部署,模組化設計易於擴展
官方文件:Apache Axis2 專案首頁
本文參考自「子孑」博客:原文連結