How to create and consume a simple Web Service using JAX WS

25 June 2012 By Praveen Macherla 28,220 views 41 Comments
GD Star Rating
loading...

One of the most exciting new features of the Java Platform, Standard Edition 6 (Java SE 6) is support for the Java API for XML Web Services (JAX-WS), version 2.0. JAX-WS 2.0 is the centre of a redesigned API stack for web services, which also includes Java Architecture for XML Binding (JAXB) 2.0 and SOAP with Attachments API for Java (SAAJ) 1.3. Even though JAX-WS is mainly part of Java EE Platform, we can use many of the functionalities without the need of Java EE Application Server. JAX-WS architecture is an easier-to-understand architecture for web services development.

Project Description

  • In this example, we create a SOAP based web service for a simple Java Calculator class with operations ‘add’ and ‘subtract’.
  • We then create a web service client which then consumes the web service and displays the result of the invoked web service.

Environment Used

  • Java SE 6
  • JAX WS 2.x
  • Eclipse IDE

Creating and Publishing Web Service

  1. Create a Java Project ‘CalcWS’.
  2. Create a package ‘com.theopentutorials.ws.calc’.
  3. Create a Java class ‘Calculator’ and type the following code.

    package com.theopentutorials.ws.calc;
    import javax.jws.WebService;
    
    @WebService
    public class Calculator {
    	public int add(int a, int b) {
    		return (a + b);
    	}
    
    	public int sub(int a, int b) {
    		return (a - b);
    	}
    
    }
  4. @WebService annotation at the beginning of the class definition tells the Java interpreter that we intend to publish ALL the methods of this class as a web service. If we want to publish only particular methods then we can use @WebMethod annotation before the method signature.
  5. In order to publish our class and its methods as web service we need to crate appropriate stub files or artifacts for web service deployment and invocation. Fortunately Java provides a tool called ‘wsgen’ which generates JAX-WS portable artifacts used in JAX-WS web services.
  6. Open command prompt or terminal in Linux and go to the project folder ‘CalcWS’.
  7. Now issue the following command,

    wsgen -cp bin -d bin com.theopentutorials.ws.calc.Calculator

    the –cp option specifies the classpath for our Calculator class which is in ‘bin’ folder, the –d option specifies where to place generated output files which is also the ‘bin’ folder in our case.

  8. We can also have a look at the source of the generated files by using the –s option provided by ‘wsgen’.

    wsgen -s src -cp bin -d bin com.theopentutorials.ws.calc.Calculator


  9. Now we need to publish our class as a web service endpoint. For that we use the static publish() method of the javax.xml.ws.Endpoint class to publish our ‘Calculator’ class as a web service in the specified context root.
  10. Create a package ‘com.theopentutorials.ws.calc.endpoint’.
  11. Create a class ‘CalcEndpointPublisher’ with main method and type the following code.

    package com.theopentutorials.ws.calc.endpoint;
    
    import javax.xml.ws.Endpoint;
    import com.theopentutorials.ws.calc.Calculator;
    
    public class CalcEndpointPublisher {
    
    	public static void main(String[] args) {
    		Endpoint.publish("http://localhost:8080/CalcWS/Calculator",
    						new Calculator());
    	}
    
    }
    
  12. Run this class as ‘Java Application’.
  13. You may not get output in the Console. To check whether our class is published as web service, open a browser and type the URL mentioned in the endpoint with a parameter ?wsdl appended.

    http://localhost:8080/CalcWS/Calculator?wsdl

  14. When you run the application, the Java SE 6 platform has a small web application server that will publish the web service at the address http://localhost:8080/CalcWS/Calculator while the JVM is running.
  15. If you see a large amount of XML that describes the functionality behind the web service, then the deployment is successful.

Creating and consuming a Web Service Client

  1. Having published the web service, we now create a client which communicates with the service and displays the result.
  2. Create a Java project ‘CalcWSClient’.
  3. Just like ‘wsgen’, JAX-WS also provides a tool called ‘wsimport’ for generating the artifacts required for creating and consuming a web service. ‘wsimport’ takes a wsdl file as input.
  4. From the project folder in command prompt or terminal, issue the following command,

    wsimport -s src -d bin http://localhost:8080/CalcWS/Calculator?wsdl

  5. This will generate many files as shown in the below file hierarchy tree.
  6. Let us now create a Java class with main method to run this client. Create a package ‘com.theopentutorials.ws.calc.client’
  7. In that package, create a class ‘CalcClient’ with main method and type the following code.

    package com.theopentutorials.ws.calc.client;
    
    import com.theopentutorials.ws.calc.Calculator;
    import com.theopentutorials.ws.calc.CalculatorService;
    
    public class CalcClient {
    
    	public static void main(String[] args) {
    		int a = 10;
    		int b = 12;
    		CalculatorService calcService = new CalculatorService();
    		Calculator calc = calcService.getCalculatorPort();
    		System.out.println(a + " + " + b + " = " + calc.add(a, b));
    		System.out.println(a + " - " + b + " = " + calc.sub(a, b));
    	}
    }
    
  8. Run this class as Java Application.
  9. You will get the following output in the console.

    10 + 12 = 22
    10 – 12 = -2

  10. Make sure that the ‘CalcEndpointPublisher’ class is run before running this client. Because we need to publish the web service before running the client. Otherwise you may get the following exception on running the client.

    Exception in thread “main” javax.xml.ws.WebServiceException: Failed to access the WSDL at: http://localhost:8080/CalcWS/Calculator?wsdl. It failed with:
    Connection refused: connect.

  11. To stop the ‘CalcEndpointPublisher’ class, select that particular console and use the terminate button (red button) in the eclipse console tab bar.
How to create and consume a simple Web Service using JAX WS, 4.4 out of 5 based on 5 ratings

Tags: , , , , , , , , , , , , ,

41 thoughts on “How to create and consume a simple Web Service using JAX WS

  1. hie Praveen u made the concept clear .but am not able to process the code ..when i try to wsgen in command prompt .am getting an error msg ..
    C:Users$@T!$hworkspaceCalWs>wsgen -cp bin -d bin com.satz.Calculator
    Problem encountered during annotation processing;
    see stacktrace below for more information.
    com.sun.tools.internal.ws.processor.modeler.ModelerException: [failed to localiz
    e] A web service endpoint could not be found()
    at com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceAP.o
    nError(WebServiceAP.java:215)
    at com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceAP.b
    uildModel(WebServiceAP.java:322)
    at com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceAP.p
    rocess(WebServiceAP.java:256)
    at com.sun.mirror.apt.AnnotationProcessors$CompositeAnnotationProcessor.
    process(AnnotationProcessors.java:60)
    at com.sun.tools.apt.comp.Apt.main(Apt.java:454)
    at com.sun.tools.apt.main.JavaCompiler.compile(JavaCompiler.java:258)
    at com.sun.tools.apt.main.Main.compile(Main.java:1102)
    at com.sun.tools.apt.main.Main.compile(Main.java:964)
    at com.sun.tools.apt.Main.processing(Main.java:95)
    at com.sun.tools.apt.Main.process(Main.java:85)
    at com.sun.tools.apt.Main.process(Main.java:67)
    at com.sun.tools.internal.ws.wscompile.WsgenTool.buildModel(WsgenTool.ja
    va:204)
    at com.sun.tools.internal.ws.wscompile.WsgenTool.run(WsgenTool.java:112)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
    java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.sun.tools.internal.ws.Invoker.invoke(Invoker.java:105)
    at com.sun.tools.internal.ws.WsGen.main(WsGen.java:41)
    error: compilation failed, errors should have been reported

    C:Users$@T!$hworkspaceCalWs>

    GD Star Rating
    loading...
  2. Thanks for your quick response .yes i forgot the annotations but after adding the annotations also am getting the same message i guess here is the message

    C:Users$@T!$hworkspaceCalWs>wsgen -cp bin -d bin com.satz.Calculator
    Problem encountered during annotation processing;
    see stacktrace below for more information.
    com.sun.tools.internal.ws.processor.modeler.ModelerException: [failed to localiz
    e] A web service endpoint could not be found()
    at com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceAP.o
    nError(WebServiceAP.java:215)
    at com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceAP.b
    uildModel(WebServiceAP.java:322)
    at com.sun.tools.internal.ws.processor.modeler.annotation.WebServiceAP.p
    rocess(WebServiceAP.java:256)
    at com.sun.mirror.apt.AnnotationProcessors$CompositeAnnotationProcessor.
    process(AnnotationProcessors.java:60)
    at com.sun.tools.apt.comp.Apt.main(Apt.java:454)
    at com.sun.tools.apt.main.JavaCompiler.compile(JavaCompiler.java:258)
    at com.sun.tools.apt.main.Main.compile(Main.java:1102)
    at com.sun.tools.apt.main.Main.compile(Main.java:964)
    at com.sun.tools.apt.Main.processing(Main.java:95)
    at com.sun.tools.apt.Main.process(Main.java:85)
    at com.sun.tools.apt.Main.process(Main.java:67)
    at com.sun.tools.internal.ws.wscompile.WsgenTool.buildModel(WsgenTool.ja
    va:204)
    at com.sun.tools.internal.ws.wscompile.WsgenTool.run(WsgenTool.java:112)

    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.
    java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAcces
    sorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.sun.tools.internal.ws.Invoker.invoke(Invoker.java:105)
    at com.sun.tools.internal.ws.WsGen.main(WsGen.java:41)
    error: compilation failed, errors should have been reported

    GD Star Rating
    loading...
  3. Article is great and concept is clear.
    I am getting the below Error when I am trying to access the client.

    Exception in thread “main” java.lang.IncompatibleClassChangeError: Found interface com.theopentutorials.ws.calc.Calculator, but class was expected
    at com.theopentutorials.ws.calc.client.CalcWSClient.main(CalcWSClient.java:16)

    GD Star Rating
    loading...
  4. This content is really cool for someone to learn how to build & consume a webservice.

    really like this content.

    thanks you very much for posting it.

    Santhosh Raghav

    GD Star Rating
    loading...
  5. Hi Praveen
    what is the prerequisite for running wsgen command?
    i have my jdk bin path as “C:\\Program Files\\Java\\jdk1.7.0\\bin”
    and my class file at C:\\CalcWS\\bin\\com\\theopentutorials\\ws\\calc\\
    and my destination folder as C:\\CalcWS\\src\\com\\theopentutorials\\ws\\calc\\stub\\

    I tried
    “C:\\Program Files\\Java\\jdk1.7.0\\bin>wsgen -cp C:\\CalcWS\\bin\\com\\theopentutorials\\ws\\calc -d C:\\CalcWS\\src\\com\\theopentutorials\\ws\\calc\\jaxws com.theopentutorials.ws.calc.Calculator”…….but dint work

    O/P was “Class not found: com.theopentutorials.ws.calc.Calculator”

    pls help

    Thanks,
    Venkat

    GD Star Rating
    loading...
  6. Thank you very much for your instructions.

    I followed them step by step and the client successfully called the web service first time.

    Well done.

    One small suggestion would be just to say that with the creation of each of the two java projects, all the default values can be taken, i.e. the “Finish” button can be clicked. :-)

    GD Star Rating
    loading...
  7. this is working fine .

    Could u pls tell how to generate java files using JAXB
    (as we will get .xsd file)

    GD Star Rating
    loading...
  8. hey the tutorial is nice but am getting an error because of my mistake but in CalcClient.java when i am importing Calculator and CalculatorService, its not able to import it .. and hence showing error :CalculatorService cannot be resolved to a type Calculator cannot be resolved to a type..
    my package hierarchy is comp.trial
    and there are two projects that is CalcWS and CalcWSClient
    it might be a silly mistake but am a beginner so plz help. Thanks.

    GD Star Rating
    loading...
    • hey i got it!! it got executed ..Thanks for the tutorial .. can u suggest me any tutorial for creating a web service that can pass xml file ?

      GD Star Rating
      loading...
  9. Thanks,

    Very nice.
    I have one problem at the end of step 3. When I type the url, I get this message
    HTTP Status 404 – /calcService

    type Status report

    message /calcService

    description The requested resource is not available.

    Apache Tomcat/7.0.37

    GD Star Rating
    loading...
  10. Well explained and to the point.Great post
    Does anybody know how to achieve the same result using JDK 1.5 and lower?

    GD Star Rating
    loading...
  11. Praveen,

    GREAT article! First Java web service tutorial I have found that actually works! Wonderful job explaining each step and the pictures of Eclipse were a BIG help!

    Can’t thank you enough for this tutorial!

    /dave

    GD Star Rating
    loading...
  12. Hi

    Really good example for beginners…simple and descriptive and very used to understand the jaxws concepts..good job

    Thanks
    Lavanya

    GD Star Rating
    loading...
  13. Hi,

    who ever is going to start the web services, its good example to understand….

    thanks…………

    GD Star Rating
    loading...
  14. step 6:
    Open command prompt or terminal in Linux and go to the project folder ‘CalcWS’.
    step 7:
    Now issue the following command,
    wsgen -cp bin -d bin com.theopentutorials.ws.calc.Calculator

    The above steps are written by you. I wonder how can you run wsgen from your project folder as it is present in jdk/bin folder.
    Plz help.

    GD Star Rating
    loading...
  15. Thank’s a lot.I am confuse with many concept but now all get clear and successfully implement service on my application.Again Thank’s

    Can you please tell me step to create service from existing servlet.

    GD Star Rating
    loading...
  16. Well explained and to the point information provided… Thanks for sharing valueable information…

    GD Star Rating
    loading...
  17. I am geting this err when i wqas giving wsgen -s src -cp bin -d bin com.theopentutorials.ws.calc.Calculator command.

    ‘wsgen’ is not recognised as an internal or external command,
    operable program or batch file.

    Can anyone help me out creating a webservice and invoking it through a stub.

    GD Star Rating
    loading...

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>