Simple SOAP Web Service in Java

In this tutorial, I am writing about, How to Publish and Test Simple SOAP Web Service in Java. The code has been tested and shared in the post.

WelcomeMessage.java

package com.dineshkrish.soap;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService
@SOAPBinding(style=Style.RPC)
public interface WelcomeMessage {
public String greet(String name);
}

WelcomeMessageImpl.java

package com.dineshkrish.soap;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;
@WebService(endpointInterface = "com.dineshkrish.soap.WelcomeMessage")
@SOAPBinding(style = Style.RPC)
public class WelcomeMessageImpl implements WelcomeMessage {
@Override
public String greet(String name) {
if (name != null && !name.isEmpty()) {
return "Hello, " + name;
}
return "";
}
}

Server.java

package com.dineshkrish.soap;
import javax.xml.ws.Endpoint;
public class Server {
public static void main(String[] args) {
final String SERVER_ADDRESS = "http://localhost:9393/welcome";
WelcomeMessage message = new WelcomeMessageImpl();
Endpoint endpoint = Endpoint.publish(SERVER_ADDRESS, message);
if (endpoint.isPublished()) {
System.out.println("Service is running at " + SERVER_ADDRESS);
} else {
System.out.println("Service not published...");
}
}
}

Output for Server.java

——————————-

Service is running at http://localhost:9393/welcome

Client.java

package com.dineshkrish.soap;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
public class Client {
public static void main(String[] args) {
final String SERVICE_ADDRESS = "http://localhost:9393/welcome?WSDL";
final String NAMESPACE = "http://soap.dineshkrish.com/";
final String SERVICE_NAME = "WelcomeMessageImplService";
try {
URL url = new URL(SERVICE_ADDRESS);
QName qName = new QName(NAMESPACE, SERVICE_NAME);
Service service = Service.create(url, qName);
WelcomeMessage welcomeMessage = service.getPort(WelcomeMessage.class);
String greetingMessage = welcomeMessage.greet("Dinesh Krishnan");
System.out.println("The received message from services : "+greetingMessage);
} catch (MalformedURLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}

Output for Client.java

——————————-

The received message from services : Hello, Dinesh Krishnan

No responses yet

Leave a Reply

Your email address will not be published. Required fields are marked *