jdk6註解開發WebService

【轉http://www.blogjava.net/dashi99/archive/2012/06/27/381594.html

WebService是SOA的一種較好的實現方式,它將應用程序的不同功能單元通過中立的契約(獨立於硬件平臺、操作系統和編程語言)聯繫起來,使得各種形式的功能單元更好的集成。

W3C對他的定義是:

    A Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface described in a machine-processable format (specifically WSDL). Other systems interact with the Web service in a manner prescribed by its description using SOAP messages......"

    Web service是一個軟件系統,爲了支持跨網絡的機器之間相互操作交互而設計。它有一個機器可識別的描述格式(特別是WSDL)。不同的系統之間可以通過SOAP消息在規定的方式下相互調用。(英文不好,請指正!)

 

    簡單的說,WebService是一種獨立於特定語言、特定平臺,基於網絡的、分佈式的模塊化組件。是一個能夠使用xml消息通過網絡來訪問的Interface,這個Interface描述了一組可訪問的操作。

WebService一般分爲兩種:

    REST式WebService,基於HTTP協議;

    RPC式WebService,基於SOAP協議,不過SOAP也是基於HTTP傳輸的。

  狹義上的WebService是指第二種RPC式的WebService,也就是我們常說的那種。

JAVA中有三種WebService規範,分別是JAX-WS(JAX-RPC)、JAX-RS、JAXM&SAAJ。

    這裏先說JAX-WS(Java API For XML-WebService),JDK1.6 自帶的版本爲JAX-WS2.1,其底層支持爲JAXB。早期的JAVA Web服務規範JAX-RPC(Java API ForXML-Remote Procedure Call)目前已經被JAX-WS 規範取代,JAX-WS 是JAX-RPC 的演進版本,但JAX-WS 並不完全向後兼容JAX-RPC。

    廢話不多說了,先來寫一個最簡單的例子:

服務器端:

    在想要發佈爲WebService的類上加上註解@WebService,這個類的方 法就變爲WebService的方法了,再通過Endpoint的publish方法,發佈這個服務,到此,一個最簡單的WebService搞定。運行 main方法,在瀏覽器裏輸入”http://localhost:8080/Service/Hello?wsdl 會看到你的WSDL信息。

 


    不過需要注意一 下, 有的同學如果不加@SOAPBinding(style = SOAPBinding.Style.RPC)這行代碼會報錯:

com.sun.xml.internal.ws.model.RuntimeModelerException: runtime modeler error: Wrapper class com.why.webservice.jaxws.SayHello is not found. Have you run APT to generate them?

網上資料說只要將JDK升級到1.6u17就可以了,我直接升級到了1.6u25(1.6.0_25-b06),問題解決!

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->package org.duke.jaxws.server;

import javax.jws.WebService;
import javax.xml.ws.Endpoint;

@WebService
public class Hello {

    
public String sayHello(String name) {
        
return "Hello " + name;
    }

    
public static void main(String[] args){
        Endpoint.publish(
"http://localhost:8080/Service/Hello"new Hello());
        System.out.println(
"Success");
    }
}

 

客戶端:

    在命令行輸入命令 wsimport -s[文件夾名] -p [包名] -keep [發佈的服務地址?wsdl] 生成客戶端代碼,如生成本例的客戶端代碼”
wsimport -s src -p org.duke.jaxws.client -keep http://localhost:8080/Service/Hello?wsdl",當然,前提是你已經配好了JAVA環境變量。
利用這些生成的客戶端代碼,就可以調用這個WebService服務了:

<!--<br /><br />Code highlighting produced by Actipro CodeHighlighter (freeware)<br />http://www.CodeHighlighter.com/<br /><br />-->package org.duke.jaxws.test;

import org.duke.jaxws.client.Hello;
import org.duke.jaxws.client.HelloService;

public class HelloClient {
    
public static void main(String[] args) {
        Hello hello 
= new HelloService().getHelloPort();  
        String s 
= hello.sayHello("World!");  
        System.out.println(s); 
    }

}

 

 

執行代碼,輸出:Hello World!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章