DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Build a Java Backend That Connects With Salesforce
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • Consuming SOAP Service With Apache CXF and Spring
  • User-Friendly API Publishing and Testing With Retrofit

Trending

  • Enhancing Security With ZTNA in Hybrid and Multi-Cloud Deployments
  • Understanding and Mitigating IP Spoofing Attacks
  • Beyond Microservices: The Emerging Post-Monolith Architecture for 2025
  • Medallion Architecture: Efficient Batch and Stream Processing Data Pipelines With Azure Databricks and Delta Lake
  1. DZone
  2. Coding
  3. Java
  4. Simple Java SOAP Web Service Using JDK Tools

Simple Java SOAP Web Service Using JDK Tools

A tutorial on how to use JDK tools to publish and consume a simple SOAP web service.

By 
Hany Ahmed user avatar
Hany Ahmed
·
Jan. 07, 16 · Tutorial
Likes (36)
Comment
Save
Tweet
Share
119.3K Views

Join the DZone community and get the full member experience.

Join For Free

The JDK allows us to both publish and consume a web service using some of its tools. The sample service “Hello world” will be responsible for saying hello to the name that I’ll send it to that service. This example also includes creating a client for this service (you can follow the same steps in client to communicate with any service you like).

A. Creating the Service

1. Construct Simple Hello Class

Suppose you have a simple class that receives a string and return another string

package wsserver;

public class Hello {
	public String sayHello(String name) {
		return "Hello " + name;
	}
}


2. Convert Hello Class to a Web Service

Simply we can convert this class to be a web service using some annotations

  • @WebService — This identifies the class as being a web service.

  • @SOAPBinding(style=SOAPBinding.Style.RPC) — This specifies the type of the communication, in this case RPC.

package wsserver;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService
@SOAPBinding(style=SOAPBinding.Style.RPC)
public class Hello {
	public String sayHello(String name) {
		return "Hello " + name;
	}
}

3. Publish Hello Service

To publish this service, we can use the Endpoint class. We will provide the publish method with any URL and an instance of our service class

package wsserver;

import javax.xml.ws.Endpoint;

public class ServiceStarter {
	public static void main(String[] args) {
		String url = "http://localhost:1212/hello";
		Endpoint.publish(url, new Hello());
		System.out.println("Service started @ " + url);
	}
}

4. Compile Code

We can compile our two classes using the simple Javac command:

javac -d . *.java

5. Start Service

We can start our service by running ServiceStarter class using the following Java command:

java wsserver/ServiceStarter

6. Check Running Service

Now the service has been started, you can check your service by seeing its WSDL file by getting the url in setp 3. We can get the Service WSDL file by appending “?wsdl” to the URL: http://localhost:1212/hello?wsdl

The result of the WSDL file will look like the following XML file:

<?xml version="1.0" encoding="UTF-8"?><!-- Published by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.6 in JDK 6. --><!-- Generated by JAX-WS RI at http://jax-ws.dev.java.net. RI's version is JAX-WS RI 2.1.6 in JDK 6. -->
<definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" xmlns:tns="http://wsserver/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://schemas.xmlsoap.org/wsdl/" targetNamespace="http://wsserver/" name="HelloService">
    <types></types>
    <message name="sayHello">
        <part name="arg0" type="xsd:string"></part>
    </message>
    <message name="sayHelloResponse">
        <part name="return" type="xsd:string"></part>
    </message>
    <portType name="Hello">
        <operation name="sayHello">
            <input message="tns:sayHello"></input>
            <output message="tns:sayHelloResponse"></output>
        </operation>
    </portType>
    <binding name="HelloPortBinding" type="tns:Hello">
        <soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="rpc"></soap:binding>
        <operation name="sayHello">

            <soap:operation soapAction=""></soap:operation>
            <input>
                <soap:body use="literal" namespace="http://wsserver/"></soap:body>
            </input>
            <output>
                <soap:body use="literal" namespace="http://wsserver/"></soap:body>
            </output>
        </operation>
    </binding>
    <service name="HelloService">
        <port name="HelloPort" binding="tns:HelloPortBinding">
            <soap:address location="http://localhost:1212/hello"></soap:address>
        </port>
    </service>
</definitions>

B. Creating the client

The first thing we should have is an interface of that service class to be able to call its methods using java code. After that we'll write some code to connect to that service. Fortunately there is a tool in JDK called wsimport that can do all of that if you just provided it with a valid WSDL URL.

1. Import Service Interface and Service Client Creator Class

Using wsimport tool we will write the following command:

wsimport -d . -p wsclient -keep http://localhost:1212/hello?wsdl

The -p arg tells the tool to put the generated classes into a specific package. Executing this command will result in generating two classes. The first class, called Hello.java and its interface that contains our method sayHello.

The code should be something like this:

package wsclient;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.6 in JDK 6
 * Generated source version: 2.1
 *
 */
@WebService(name = "Hello", targetNamespace = "http://wsserver/")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface Hello {

    /**
     *
     * @param arg0
     * @return
     *     returns java.lang.String
     */
    @WebMethod
    @WebResult(partName = "return")
    public String sayHello(
        @WebParam(name = "arg0", partName = "arg0")
        String arg0);

}

The second file would be called HelloService.java, and it will contain the methods that would help us to connect to our service we are only concerned with the no-arg constructor and the getHelloPort() method:

package wsclient;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.1.6 in JDK 6
 * Generated source version: 2.1
 *
 */
@WebServiceClient(name = "HelloService", targetNamespace = "http://wsserver/", wsdlLocation = "http://localhost:1212/hello?wsdl")
public class HelloService
    extends Service
{

    private final static URL HELLOSERVICE_WSDL_LOCATION;
    private final static Logger logger = Logger.getLogger(wsclient.HelloService.class.getName());

    static {
        URL url = null;
        try {
            URL baseUrl;
            baseUrl = wsclient.HelloService.class.getResource(".");
            url = new URL(baseUrl, "http://localhost:1212/hello?wsdl");
        } catch (MalformedURLException e) {
            logger.warning("Failed to create URL for the wsdl Location: 'http://localhost:1212/hello?wsdl', retrying as a local file");
            logger.warning(e.getMessage());
        }
        HELLOSERVICE_WSDL_LOCATION = url;
    }

    public HelloService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public HelloService() {
        super(HELLOSERVICE_WSDL_LOCATION, new QName("http://wsserver/", "HelloService"));
    }

    /**
     *
     * @return
     *     returns Hello
     */
    @WebEndpoint(name = "HelloPort")
    public Hello getHelloPort() {
        return super.getPort(new QName("http://wsserver/", "HelloPort"), Hello.class);
    }

    /**
     *
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the <code>features</code> parameter will have their default values.
     * @return
     *     returns Hello
     */
    @WebEndpoint(name = "HelloPort")
    public Hello getHelloPort(WebServiceFeature... features) {
        return super.getPort(new QName("http://wsserver/", "HelloPort"), Hello.class, features);
    }

}

2. Invoke the Web Service

We are now ready to write the code responsible for invoking the web service by making a new instance of the HelloService class, we are ready to get Hello interface by calling the method getHelloPort() from the HelloService instance. After that we can call the method and get the response as a simple Java method:

package wsclient;

public class HelloClient {
	public static void main(String[] args) {
		HelloService service = new HelloService();
		Hello hello = service.getHelloPort();
		String text = hello.sayHello("hany");
		System.out.println(text);
	}
}

3. Compile Classes and Run

javac -d . *.java
java wsclient/HelloClient
Web Service Java (programming language) Java Development Kit SOAP Web Protocols

Published at DZone with permission of Hany Ahmed. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Build a Java Backend That Connects With Salesforce
  • How to Consume REST Web Service (GET/POST) in Java 11 or Above
  • Consuming SOAP Service With Apache CXF and Spring
  • User-Friendly API Publishing and Testing With Retrofit

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!