在本章中,我们将学习如何为在 Spring WS - Writing Server 中创建的Web应用程序服务器创建客户端.使用Spring WS.
Step | 描述 |
---|---|
1 | 按照Spring WS-Writing Server章节中的说明更新com.it1352包下的项目countryService. |
2 | 在com.it1352包下的com.it1352.client和MainApp.java包下创建CountryServiceClient.java,如以下步骤所述. |
CountryServiceClient.java
package com.it1352.client;import org.springframework.ws.client.core.support.WebServiceGatewaySupport;import com.it1352.GetCountryRequest;import com.it1352.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; }}
MainApp.java
package com.it1352;import org.springframework.oxm.jaxb.Jaxb2Marshaller;import com.it1352.client.CountryServiceClient;public class MainApp { public static void main(String[] args) { CountryServiceClient client = new CountryServiceClient(); Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath("com.it1352"); 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服务客户端
右键单击应用程序中的MainApp.java在Eclipse下并使用作为Java Application 命令运行.如果应用程序一切正常,它将打印以下消息.
Country : United StatesCapital : WashingtonPopulation : 46704314Currency : USD
在这里,我们为SOAP创建了一个客户端 - CountryServiceClient.java 基于Web服务. MainApp使用CountryServiceClient对Web服务进行命中,发出post请求并获取数据.