在本章中,我們將學習如何使用Spring WS為Spring WS編寫伺服器中創建的Web應用程式伺服器創建客戶端。
第1步: 按照Spring WS編寫服務章節中的說明,更新專案countryService 下的com.zaixian
包。
第2步: 按照以下步驟中的說明在com.zaixian.client
包創建一個檔:CountryServiceClient.java,以及在com.zaixian
包下創建一個檔:MainApp.java
。
檔:CountryServiceClient.java 的代碼如下 -
package com.zaixian.client;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import com.zaixian.GetCountryRequest;
import com.zaixian.GetCountryResponse;
public class CountryServiceClient extends WebServiceGatewaySupport {
public GetCountryResponse getCountryDetails(String country){
String uri = "http://localhost:8080/countryService/";
GetCountryRequest request = new GetCountryRequest();
request.setName(country);
GetCountryResponse response =(GetCountryResponse) getWebServiceTemplate()
.marshalSendAndReceive(uri, request);
return response;
}
}
檔:CountryServiceClient.java 的代碼如下 -
package com.zaixian;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import com.zaixian.client.CountryServiceClient;
public class MainApp {
public static void main(String[] args) {
CountryServiceClient client = new CountryServiceClient();
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.zaixian");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
GetCountryResponse response = client.getCountryDetails("United States");
System.out.println("Country : " + response.getCountry().getName());
System.out.println("Capital : " + response.getCountry().getCapital());
System.out.println("Population : " + response.getCountry().getPopulation());
System.out.println("Currency : " + response.getCountry().getCurrency());
}
}
啟動Web服務
啟動Tomcat伺服器,並確保可以使用標準流覽器從webapps檔夾訪問其他網頁。
測試Web服務客戶端
在Eclipse下的應用程式中右鍵單擊MainApp.java
並使用作為Java Application命令運行。 如果應用程式一切正常,它將列印以下消息。
Country : United States
Capital : Washington
Population : 46704314
Currency : USD
在這裏,我們基於SOAP的Web服務創建了一個Client - CountryServiceClient.java
。 MainApp使用CountryServiceClient
命中Web服務,發出POST請求並獲取數據。
上一篇:
Spring伺服器(單元測試)
下一篇:
Spring客戶端(單元測試)