Spring WS - Writing Client


Advertisements

In this chapter, we will learn how to create a client for the web application server created in the Spring WS - Writing Server using Spring WS.

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

CountryServiceClient.java

package com.howcodex.client;

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

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

public class MainApp {
   public static void main(String[] args) {
      CountryServiceClient client = new CountryServiceClient();
      Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
      marshaller.setContextPath("com.howcodex");
      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());
   }
}

Start the Web Service

Start the Tomcat server and ensure that we can access other webpages from the webapps folder using a standard browser.

Test Web Service Client

Right click on the MainApp.java in your application under Eclipse and use run as Java Application command. If everything is ok with the application, it will print the following message.

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

Here, we have created a Client – CountryServiceClient.java for the SOAP based web service. MainApp uses CountryServiceClient to make a hit to the web service, makes a post request and gets the data.

Advertisements