开发手册 欢迎您!
软件开发者资料库

Spring WS - 编写客户端

Spring Web Services编写客户端 - 通过简单简单的步骤学习Java Spring Framework 4.1.6版,从基本概念到高级概念,包括示例环境设置,控制反转(IoC),依赖注入,bean范围,bean生命周期,内部bean,自动装配,不同模块,面向方面编程(AOP),数据库访问(JDBC),事务管理,Web MVC框架,Web流,异常处理,EJB集成和发送电子邮件等。

在本章中,我们将学习如何为在 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请求并获取数据.