在本章中,我们将学习如何使用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客户端(单元测试)