2010/02/06

Web Service(4)

編寫Service Endpoint Implmentation類別

在這個範例,這個Implementation類別Hello,被annotated為一個web service endpoint使用@WebService
annotation. Hello宣告一個方法叫做sayHello, 使用@WebMethod的annontation,@WebMethod暴露annotated
方法給web service clients. sayHello回傳一個greeting給client,使用傳給sayHello的名字組合greeting.
implementation類也必須定義一個default, public, no-argument的建構子。
package helloservice.endpoint;
import javax.jws.WebService;
@WebService
public class Hello {
 
 private String message = new String( " Hello, " );
 
 public void Hello() {}
 
 @WebMethod
 public String sayHello(String name) {
  return message + name + " . " ;
 }
}
建立,包裝和發布Service

你可以build, package以及deployhelloservice應用程式使用NetBeans IDE或是ant

使用Ant:

移到tut-install/examples/jaxws/helloservice/資料夾下輸入ant
要deploy的話先確認Enterprise Server已經執行,輸入ant deploy

你可以瀏覽佈署的WSDL檔案,http://localhost:8080/helloservice/hello?WSDL

使用all

為了方便,直接下ant all指令就能做完上述工作。

不使用Client來測試Service

http://localhost:8080/helloservice/HelloService?Tester

一個簡單的JAX-WS Client

編寫Client

當在一個port上引發遠端方法時,client會完成下列步驟:

  1. 使用已產生的helloService.endpoint.HelloService類別,這個類代表被紀錄在WSDL檔案內的URI的服務
  2. HelloService service = new HelloService();
  3. 藉由引發getHelloPort方法從Service取得一個proxy,也被認知為一個port,
  4. Hello port = service.getHelloPort();
  5. 引發port's的sayHello方法,傳給service一個name
  6. String response = port.sayHello(name);
下面是HelloClient的全部source code
package simpleclient;
import javax.xml.ws.WebServiceRef;
import helloservice.endpoint.HelloService;
import helloservice.endpoint.Hello;
public class HelloClient {
 public static void main(String[] args) {
  try {
  HelloClient client = new HelloClient();
  client.doTest(args);
  } catch(Exception e) {
  e.printStackTrace();
  }
 }
 public void doTest(String[] args) {
  try {
   System.out.println( " Retrieving the port from
   the following service: " + service);
   HelloService service = new HelloService();
   Hello port = service.getHelloPort();
   System.out.println( " Invoking the sayHello operation
   on the port. " );
   String name;
   if (args.length > 0) {
   name = args[0];
   } else {
    name = " No Name " ;
   }
   String response = port.sayHello(name);
   System.out.println(response);
  } catch(Exception e) {
   e.printStackTrace();
  }
 }
}

No comments:

Post a Comment