首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> C++ 入門

從零開始學 WebService(一):JAX-WS 入門示例

     編輯:C++ 入門

核心概念

  • WebService 目的:異構平台間交互(Java/.NET/Python 等互調)。
  • JAX-WS:Java API for XML Web Services,標準實現方式。
  • SEI:Service Endpoint Interface(服務端點接口),定義服務契約。
  • SIB:Service Implementation Bean(服務實現類),實現 SEI。

服務端開發步驟

1. 定義接口 (SEI)

package com.lul.service;
import javax.jws.WebService;
@WebService
public interface IMyService {
    int add(int a, int b);
    int minus(int a, int b);
}

2. 實現類 (SIB)

package com.lul.service;
import javax.jws.WebService;
@WebService(endpointInterface="com.lul.service.IMyService")
public class MyServiceImpl implements IMyService {
    public int add(int a, int b) {
        System.out.println(a + "+" + b + "=" + (a+b));
        return a+b;
    }
    public int minus(int a, int b) {
        System.out.println(a + "-" + b + "=" + (a-b));
        return a-b;
    }
}

3. 發布服務

package com.lul.service;
import javax.xml.ws.Endpoint;
public class MyService {
    public static void main(String[] args) {
        String address = "https://localhost:8888/ns";
        Endpoint.publish(address, new MyServiceImpl());
        System.out.println("Service published at " + address);
    }
}

運行後訪問 https://localhost:8888/ns?wsdl 可見 WSDL 文檔。

客戶端調用

package com.lul.service;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class TestClient {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://localhost:8888/ns?wsdl");
        QName qname = new QName("https://service.lul.com/", "MyServiceImplService");
        Service service = Service.create(url, qname);
        IMyService proxy = service.getPort(IMyService.class);
        System.out.println("10+9=" + proxy.add(10, 9));
    }
}

關鍵點

  • @WebService 註解標識服務類/接口。
  • Endpoint.publish 一鍵發布,內置輕量級 HTTP 服務器(適合測試,生產用 Tomcat/CXF/Axis2)。
  • 客戶端通過 WSDL 動態生成存根,無需預編譯客戶端代碼。
  • QName 的命名空間需與服務端 WSDL 中 targetNamespace 一致。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved