Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Getting Started with Java Web Services Programming

In this article we will see a full introduction about Web Services Programming using only Java and its main resources regarding this.

One of the benefits of using Web services is that they're relatively easy to build and deploy. In the process of creating our hello world system I've introduced some fundamental concepts, including SOAP and WSDL.

Note: I assume that the reader of this article has basic knowledge about SOAP and WebServices

Figure 1: Major roles in this type of architecture

Step 1: Create a simple Java program (Service)

First, let us define the API to be exposed.

Listing 1: HelloWorld.java

package com.mrbool.ws;

public interface HelloWorld {
   String getHelloWorldMessage();
}

Implementation of the above interface is as follows:

Listing 2: HelloWorldImpl.java

package com.mrbool.ws;

public class HelloWorldImpl  implements HelloWorld  {
	@Override
	public String getHelloWorldMessage(String myName){
		return("Hello "+myName+" to JAX WS world");
	}
}

Step 2: Modify the Service as Web Service

Modify the service created in the previous section to Web service

The revised interface HelloWorld.java is as follows:

Listing 3: HelloWorld.java

package com.mrbool.ws;

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

//Service Endpoint Interface
@WebService
@SOAPBinding(style = Style.RPC)
public interface HelloWorld{

@WebMethod String getHelloWorldMessage(String name);

}

Now we have service with a single operation getHelloWorldMessage().The @WebService annotation defines the HelloWorld class as a Web Service Endpoint Interface(SEI). The SEI is an interface that has a method declared in it.

For Requirements of a JAX-WS Endpoint please refer: Requirements of a JAX-WS Endpoint

Specify the interface HelloWorld by adding the Endpoint Interface element to the @WebService annotation in the implementation class. You must provide the full package name of the interface.

Revised implementation HelloWorldImpl.java is as follows:

Listing 4: HelloWorldImpl.java

package com.mrbool.ws;

import javax.jws.WebService;

@WebService(endpointInterface="com.mrbool.ws.HelloWorld")
public class HelloWorldImpl  implements HelloWorld  {
	@Override
	public String getHelloWorldMessage(String myName){
		return("Hello "+myName+" to JAX WS world");
	}

}

Step 3: Adding WS exposed code

Publish the web service locally by creating the Endpoint publisher and expose the service on the server.

Endpoint.publish("http://localhost:9000/ws/hello", new HelloWorldImpl());

This line here starts a lightweight http server endpoint that deploys your web service and starts accepting incoming requests.

The publish method takes two parameters:

  • Endpoint URL String
  • Implementor object, in this case the HelloWorld implementation class, which is exposed as a Web service at the endpoint identified by the URL mentioned in the parameter above

The contents of HelloWorldPublisher.java is a follows :

Listing 5: HelloWorldPublisher.java

 package com.mrbool.endpoint;

 import javax.xml.ws.Endpoint;
 import com.mrbool.ws.HelloWorldImpl;

 public class HelloWorldPublisher {

 	public static void main(String[] args){
 		Endpoint.publish(
 		"http://localhost:9000/ws/hello", new HelloWorldImpl());
 		System.out.println(
 		"\nWeb service published @ http://localhost:9000/ws/hello");
		System.out.println("You may call the web service now");
 	}
 }

Step 4: Create a Web Service Client

To create a client we need to:

Specify the URL

	
url = new URL("http://localhost:9000/ws/hello?wsdl");

Specify the qualified namespace

QName qname = new QName(
	"http://ws.mrbool.com/","HelloWorldImplService");

It consists of two parameters (namespaceURI and localPart) :

  • namespaceURI is the @namespace value in the WSDL file
  • The localPart is the value of the service[@name] attribute at the bottom of WSDL

Using the url and qualified name create the service.

Service service = Service.create(url,qname);

Get the port(proxy to the service), and interact with the webservice.

HelloWorld hello = service.getPort(HelloWorld.class);

The contents of Client file is:

Listing 6: Client file

package com.mrbool.client;

import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import com.mrbool.ws.HelloWorld;

public class HelloWorldClient  {
	public static void main(String[] args) throws Exception{

	URL url = new URL("http://localhost:9000/ws/hello?wsdl");
	QName qname = new QName(
	"http://ws.mrbool.com/","HelloWorldImplService");

	Service service = Service.create(url,qname);
	HelloWorld hello = service.getPort(HelloWorld.class);

	System.out.println(hello.getHelloWorldMessage("Manisha"));
	}

}

Step 5: Compile and Run

Compile the service and publisher files and execute them. Lets create a batch file as follows:

The contents of compileandrun.bat are:

Listing 7: compileandrun.bat

dir /b /s *.java >> files.txt
javac @files.txt
java com.mrbool.endpoint.HelloWorldPublisher

Place the batch files directly under the package com.mrbool.

  • The first line in the batch lists all the java files under subfolders and writes the full path of files to files.txt.
  • Second line issues the compile command to all the java files listed in the file files.txt.
  • Third line executes the HelloWorldPublisher class.

Once the batch file is ready execute it on the command prompt. The following output appears on the console:

Web service published @ http://localhost:9000/ws/hello
You may call the web service now

Step 6: Test WS Client

Write a batch file to test the client

Listing 8: executeClient.bat

java com.mrbool.client.HelloWorldClient
PAUSE

Execute the executeClient.bat and the output is follows :

Hello Manisha to JAX WS world

Step 7: Generate the WSDL

Test the deployed web service by accessing the WSDL (Web Service Definition Language) document generator via URL "http://localhost:9000/ws/hello?wsdl". This WSDL describes in detail the exposed APIs of the Web Service. As it is language-neutral, client can be built in any programming language.

Step 8: WS using wsimport

To access the published web service we can use the wsimport tool (bundled with JDK, can be found at "JDK_PATH/bin" folder). This parses the published WSDL file, and generates the necessary client files (stub).

Open the command prompt and issue the following command to generate the files (files will be generated in the current directory where the command prompt is pointing to). Upon execution of this command the source and class files are also generated in the same path.

wsimport -keep http://localhost:9000/ws/hello?wsdl

For the above example this will generate, one interface and one service implementation file as follows:

Listing 9: HelloWorld.java

package com.mrbool.ws;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import javax.xml.ws.Action;


/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.4-b01
 * Generated source version: 2.2
 *
 */
@WebService(
	name = "HelloWorld",
	targetNamespace = "http://ws.mrbool.com/")
@SOAPBinding(style = SOAPBinding.Style.RPC)
public interface HelloWorld {

/**
 *
 * @param arg0
 * @return
 *     returns java.lang.String
 */
@WebMethod
@WebResult(partName = "return")
@Action(
input = "http://ws.mrbool.com/HelloWorld/getHelloWorldMessageRequest",
output="http://ws.mrbool.com/HelloWorld/getHelloWorldMessageResponse")
public String getHelloWorldMessage(
	@WebParam(name = "arg0", partName = "arg0")
	String arg0);

}

Listing 10: HelloWorldImplService.java

package com.mrbool.ws;

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

/**
 * This class was generated by the JAX-WS RI. JAX-WS RI 2.2.4-b01 Generated
 * source version: 2.2
 *
 */
@WebServiceClient(
	name = "HelloWorldImplService",
	targetNamespace = "http://ws.mrbool.com/",
	wsdlLocation = "http://localhost:9000/ws/hello?wsdl")
public class HelloWorldImplService extends Service {

private final static URL HELLOWORLDIMPLSERVICE_WSDL_LOCATION;
private final static WebServiceException HELLOWORLDIMPLSERVICE_EXCEPTION;
private final static QName HELLOWORLDIMPLSERVICE_QNAME = new QName(
		"http://ws.mrbool.com/", "HelloWorldImplService");

static {
	URL url = null;
	WebServiceException e = null;
	try {
		url = new URL("http://localhost:9000/ws/hello?wsdl");
	} catch (MalformedURLException ex) {
		e = new WebServiceException(ex);
	}
	HELLOWORLDIMPLSERVICE_WSDL_LOCATION = url;
	HELLOWORLDIMPLSERVICE_EXCEPTION = e;
}

public HelloWorldImplService() {
	super(__getWsdlLocation(), HELLOWORLDIMPLSERVICE_QNAME);
}

public HelloWorldImplService(WebServiceFeature... features) {
	super(__getWsdlLocation(), HELLOWORLDIMPLSERVICE_QNAME, features);
}

public HelloWorldImplService(URL wsdlLocation) {
	super(wsdlLocation, HELLOWORLDIMPLSERVICE_QNAME);
}

public HelloWorldImplService(URL wsdlLocation,
		WebServiceFeature... features) {
	super(wsdlLocation, HELLOWORLDIMPLSERVICE_QNAME, features);
}

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

public HelloWorldImplService(URL wsdlLocation, QName serviceName,
		WebServiceFeature... features) {
	super(wsdlLocation, serviceName, features);
}

/**
 *
 * @return returns HelloWorld
 */
@WebEndpoint(name = "HelloWorldImplPort")
public HelloWorld getHelloWorldImplPort() {
	return super.getPort(new QName("http://ws.mrbool.com/",
			"HelloWorldImplPort"), HelloWorld.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 HelloWorld
 */
@WebEndpoint(name = "HelloWorldImplPort")
public HelloWorld getHelloWorldImplPort(WebServiceFeature... features) {
	return super.getPort(new QName("http://ws.mrbool.com/",
			"HelloWorldImplPort"), HelloWorld.class, features);
}

private static URL __getWsdlLocation() {
	if (HELLOWORLDIMPLSERVICE_EXCEPTION != null) {
		throw HELLOWORLDIMPLSERVICE_EXCEPTION;
	}
	return HELLOWORLDIMPLSERVICE_WSDL_LOCATION;
}

}

Step 9: Test Stub

To test the stubs (generated files in the previous section), we need to create a client which depends on these files :

The contents of HelloWorldClientForStub.java is as follows:

Listing 11: HelloWorldClientForStub.java

import com.mrbool.ws.HelloWorld;
import com.mrbool.ws.HelloWorldImplService;

public class HelloWorldClientForStub {
	public static void main(String[] args){
		HelloWorldImplService helloService =
			new HelloWorldImplService() ;
		HelloWorld hello = helloService.getHelloWorldImplPort();
		System.out.println(hello.getHelloWorldMessage("Manisha"));
	}
}

Place this file under the same directory where the files (interface and implementation from previous section) were generated. Write batch file which has command to compile and run this client file.

The contents of compileandexecuteclientforstub.bat is as follows:

javac HelloWorldClientForStub.java
java HelloWorldClientForStub
PAUSE

Execute the compileandexecuteclientforstub.bat and the output is:

C:\>java HelloWorldClientForStub
Hello Manisha to world of Jax WS

C:\>PAUSE
Press any key to continue . . .

Conclusion

In this article we saw some things about Web Services in Java, hope you liked, see you next time.



Web developer and passioned for web design, SEO and front end technologies.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login