📜  Spring WS-编写客户端

📅  最后修改于: 2020-11-11 06:45:49             🧑  作者: Mango


在本章中,我们将学习如何为在Spring WS-使用Spring WS编写服务器中创建的Web应用程序服务器创建客户端。

Step Description
1 Update the project countryService under the package com.tutorialspoint as explained in the Spring WS – Writing Server chapter.
2 Create CountryServiceClient.java under the package com.tutorialspoint.client and MainApp.java under the package com.tutorialspoint as explained in the following steps.

CountryServiceClient.java

package com.tutorialspoint.client;

import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import com.tutorialspoint.GetCountryRequest;
import com.tutorialspoint.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.tutorialspoint;

import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import com.tutorialspoint.client.CountryServiceClient;

public class MainApp {
   public static void main(String[] args) {
      CountryServiceClient client = new CountryServiceClient();
      Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
      marshaller.setContextPath("com.tutorialspoint");
      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应用程序身份运行”命令。如果应用程序一切正常,它将打印以下消息。

Country : United States
Capital : Washington
Population : 46704314
Currency : USD

在这里,我们为基于SOAP的Web服务创建了一个Client – CountryServiceClient.java 。 MainApp使用CountryServiceClient来命中Web服务,发出发布请求并获取数据。