View RSS Feed

Web Service

How to create a Java web service

Rating: 28 votes, 4.32 average.
by , 04-04-2012 at 05:57 AM (109896 Views)
Web service is a XML-based standard that allows interoperability between different applications on different platforms, for example, a .NET based application on Windows can communicate with a Java based one on Linux. The communication can be done through a set of XML messages over HTTP protocol.

Throughout this article, you will learn how to create and publish a web service, and consume the web service by a command line client. This article supposes you are familiar with basic Java programming using Eclipse IDE, as well as Ant build script at fundamental level.


Java web service API

Java API for XML Web Services (JAX-WS) has been included in the Java SE platform since version 6. That means, prior to Java SE 6, JAX-WS is only available for the Java EE platform, so developers could not write web services aware applications without Java EE runtime. However, JAX-WS is now a part of the Java SE platform.
The API comprises two main packages:

  • javax.xml.ws: contains the core JAX-WS APIs.
  • javax.jws: contains annotation classes that describe web service metadata. Annotations help writing web services based applications easily.



In addition, the Java SE platform provides some useful tools for generating web services artifacts: wgen, wsimport, schemagen and xjc. In this article, you will use the wsimport tool for generating Java classes for web services client.


Create a web service class

  • Create a new Java project in Eclipse by selecting File -> New Project, name the project as MyWebService.
  • Create a source package called com.mycompany.service.
  • Create a new, empty Java class in the above package, name it as HelloWeb.java. You should end up with a screen like this:


Name:  create project.png
Views: 65519
Size:  43.9 KB
Figure: Create a web service class

The class is empty now. We will mark it as a web service by adding @WebService annotation to the class and implement a web service method by using @WebMethod annotation. Update source code of the class like the following:

Java Code: Web service class
package com.mycompany.service;

import javax.jws.WebMethod;

import javax.jws.WebService;

@WebService

public class HelloWeb {

   

    @WebMethod

    public String sayGreeting(String name) {

        return "Greeting " + name + "!";

    }

}
Both the annotation types are from package javax.jws. The @WebService annotation marks a class as implementing a web service, and the @WebMethod annotation is used to expose a method as web service method.

And we are done creating a web service class, pretty simple!


Create a server class

Instead of deploying the web service on a heavy weight Java EE application server such as Tomcat or Glassfish, we can deploy it on a built-in, lightweight server with the help of javax.xml.ws.Endpoint class.

In Eclipse, create a new class called Server.java under the package com.mycompany.service with a main() method, and just add two lines of code to the main() method:

Java Code: Server class
package com.mycompany.service;

import javax.xml.ws.Endpoint;

public class Server {

    public static void main(String[] args) {

        Endpoint.publish("http://localhost:9898/HelloWeb", new HelloWeb());

        System.out.println("HelloWeb service is ready");

    }

}

The static method publish(String address, Object implementor) creates and publishes a web service at a specified URL. In the code above:

  • A local server is created to listen at the port 9898.
  • A new instance of HelloWeb is created and bind to the URL /HelloWeb



The server code is done, and we are ready to test the web service now.


Publish the web service

Run the Server class as a standalone Java application by selecting Run -> Run As -> Java Application from Eclipse’s main menu. Once the server is started, you should see the following message in Console view:

Name:  server started.png
Views: 64872
Size:  12.0 KB
Figure: the web service is published on a built in server
  • We now try to access the server. Select Window -> Show View -> Other, select General – Internal Web Browser, to open an internal browser in Eclipse.
  • Type the following line into address bar of the internal browser:

  • The server should return an XML document as in the following screen-shot:


blogs/web-service/attachments/3404-how-create-java-web-service-wsdl-xml.png
Figure: The WSDL document returned from the server

The WSDL document describes a web service in XML format, allows other applications to discover and consume web service methods as per described by the WSDL.


Invoke the web service method

Now we are trying to invoke the sayGreeting() method from web interface in Eclipse.

Make sure you have the Java EE perspective is active in Eclipse. Select Run -> Run the Web Services Explorer. The Web Services Explorer view is opened:

Name:  web services epxplorer.png
Views: 64941
Size:  27.1 KB
Figure: Open Web Services Explorer View

In this view, click on the icon “WSDL Page” at the top right corner:

Name:  click wsdl page icon.png
Views: 64694
Size:  3.5 KB
Figure: Add a WSDL page

Select WSDL Main in the Navigator left pane. In the Actions pane on the right, type the URL: http://localhost:9898/HelloWeb?wsdl into the field WSDL URL, click Go.

The WSDL Binding Details page is displayed, which shows the sayGreeting() method as a web service method:

Name:  wsdl binding details.png
Views: 64953
Size:  36.4 KB
Figure: WSDL Binding Details

Click on the sayGreeting name, the page Invoke a WSDL Operation is displayed, which shows details of the method sayGreeting:

Name:  say greeting method details.png
Views: 64834
Size:  35.2 KB
Figure: Invoke a WSDL Operation

The sayGreeting() method has one String argument, click on Add link to add value for the argument. Type “The President” into the text box:

Name:  type argument.png
Views: 64583
Size:  4.1 KB
Figure: Set argument for web service method

Click Go, the web service method is invoked and return a response is returned in the Status bottom pane:

Name:  method return.png
Views: 64752
Size:  38.5 KB
Figure: Invoke the web service method

That means the web service method is invoked successfully.


Create a web service client

So far we have been able to access the web service via a web interface inside Eclipse. It would be more interesting if the web service can be accessed via a standalone program. Such program is called a web service client, which we will write now. The steps to create a web service client are as follows:
  • First, we need to generate web service client Java sources file based on the WSDL page returned by the server. To do so, we should use the wsimport tool which comes with JDK. Syntax of the wsimport command line tool is:

    wsimport [options] <WSDL_URI>

    • <WSDL_URI>: specifies URI of the web service’s WSDL page, it should be http://localhost:9898/HelloWeb?wsdl for our sample program.
    • [options]: specifies some options such as where to read web service source files and where to put generated source files. We will use these three options:

    • -s: specifies the directory where to place generated source files.
    • -p: specifies a package to place generated source files.
    • -keep: keep the generated files.

    So the command would be:

    wsimport -keep -s ./src -p com.mycompany.service.client http://localhost:9898/HelloWeb?wsdl

    We put the generated files into package com.mycompany.service.client
  • Next, we create an Ant build file to execute the wsimport command within Eclipse IDE.

    • Create a new XML file, say wsbuild.xml, save it into project directory.
    • Write content for the wsbuild.xml as follow:


    XML Code: Ant build script to generate web service client classes
    <project name="My Web Service Build" default="wsimport">
    
        <target name="wsimport">
    
            <exec executable="wsimport">
    
                <arg line="-keep -s ./src -p com.mycompany.service.client http://localhost:9898/HelloWeb?wsdl"/>
    
            </exec>           
    
        </target>
    
       
    
    </project>
  • Open Ant View by selecting Window -> Show View -> Ant.

    • Click on Add Buildfiles icon to add wsbuild.xml to the view.
    • Make sure the server program is still running, if not, start it. Click on Run icon to execute the default target of the Ant script.

    Name:  ant view.png
Views: 64485
Size:  7.8 KB
    Figure: Ant View

    The wsimport command will connect to the server and parse the WSDL page from the given URL to generate Java source files for web service client. And you should see a BUILD SUCCESSFUL message in the Console view.
  • Refresh the project in Project Explorer view, you will see there are 6 Java source files are generated under the package com.mycompany.service.client:

    Name:  generated source files.png
Views: 64469
Size:  12.2 KB
    Figure: Generated Java source files
  • The generated Java files are necessary for writing a web service client. We are interested in the class HelloWebService.java because it wraps all the details and exposes some methods ready for implementing a client.
  • Create a new Java class, say Client.java under the package com.mycompany.service, with a main() method. Update the source code of the class looks like this:


Java Code: The web service client code
package com.mycompany.service;

import com.mycompany.service.client.HelloWebService;

public class Client {

    public static void main(String[] args) {

        HelloWebService service = new HelloWebService();

        com.mycompany.service.client.HelloWeb helloWeb = service.getHelloWebPort();

        String response = helloWeb.sayGreeting("The President");

        System.out.println("Web service response: " + response);

    }

}
And we are done writing a web service client. Be ready to test it now!


Test the web service

So far we have done both the server and the client for a sample web service. Both are standalone command line java programs and can be launched by selecting Run -> Run As -> Java Application from Eclipse’s main menu.

  • Start the server, and make sure you got the message “HelloWeb service is ready” in the console. The server is now waiting for request.
  • Start the client, it will connect to the server, invoke the web service method and receive a response back. And finally you should see the message “Web service response: Greeting The President!”



In this article we only run the server and the client on a same computer. It is also possible to deploy the client and the server on two different machines.

  • The server part contains only two Java files: HelloWeb.java and Server.java
  • The client part contains all generated files under package com.mycompany.service.client and the Client.java file.



And remember to update the server address, port number and web service URI correctly.

Submit "How to create a Java web service" to Facebook Submit "How to create a Java web service" to Digg Submit "How to create a Java web service" to del.icio.us Submit "How to create a Java web service" to StumbleUpon Submit "How to create a Java web service" to Google

Comments

  1. jon80's Avatar
    • |
    • permalink
    Eclipse cannot quite import javax.xml.ws.Endpoint; as outlined for the Server class.

    I tried checking the documentation at Java(TM) EE 7 Specification APIs (v7), and, at Java EE 6 (v6), but no joy either, any suggestions, please?