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

25 June 2012 By Praveen Macherla 102,839 views 70 Comments
34 Flares Twitter 4 Facebook 18 Google+ 12 34 Flares ×

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.

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

  • Frantisek

    Thank you for the great article

  • Laxmi

    Very good explanation and useful article

  • satish

    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>

    • Manish

      I am getting the error while putting the calcClient…i followed step successfully till wsimport statement in cmd…please suggest

      Exception in thread “main” java.lang.Error: Unresolved compilation problems:
      CalculatorService cannot be resolved to a type
      CalculatorService cannot be resolved to a type
      Calculator cannot be resolved to a type

      at com.theopentutorials.ws.calc.client.CalcClient.main(CalcClient.java:9)

  • satish

    well i created project name as CalWs and package name as com.satz class name as Calculator ..

    • http://theopentutorials.com Praveen Macherla

      Check the annotations.

      • satish

        Praveen here is error .. wsgen -s src -cp bin -d bin com.theopentutorials.ws.calc.Calculator after this command am not able to generate the JAXWS files as u shown

  • satish

    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

  • vijitha

    This is an owsem article. Short and weet. Thanks a lot for sharing it ..

  • Azahrudhin

    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)

    • http://theopentutorials.com Praveen Macherla

      In the tutorial, Calculator is a class not an interface. Check whether the web service is running by browsing the wsdl.

      • Azahrudhin

        Thanks for the quick reply Praveen wsdl is working fine able to run the client also. If I wanted to access through URL what is the URL.
        http://localhost:8080/CalcWS/Calculator/add?arg0=1&arg1=1

        It is giving below error

        Web Services
        No JAX-WS context information available.

        • http://theopentutorials.com Praveen Macherla

          You cannot access through URL. For that you need Restful web service. Refer this link.

    • Azahrudhin

      Issue got resolved, It was because of improper compilation/build, now it is working.
      If we wanted to access through URL what would be the URL
      http://localhost:8080/CalcWS/Calculator/add?arg0=1&arg1=1
      It is giving below error

      Web Services
      No JAX-WS context information available.

  • Kuladeep Patil

    It’s an incredible document … thank you very much

    with kind regards,

    Kuladeep Patil

  • Santhosh Raghav

    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

  • Vaibhav Kulkarni

    very nice article :)

  • Venkat

    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

    • http://theopentutorials.com Praveen Macherla

      Carefully go through the screenshot posted under heading 3 “Creating and Publishing Web Service” step 7.

  • Keith

    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. :-)

  • Naman

    this is working fine .

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

  • praveen goyal

    awsmeeeeeeee and working tutorial…………………..

  • Dhwaj

    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.

    • Dhwaj

      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 ?

      • Arun Vad

        Hi Dhwaj,
        How could you fix the error, I am getting the same error.
        Please help.
        Arun

  • praveen d

    superb tutorial…..to learn quickly..

  • http://www.javaexperience.com Java

    this tutorial is excellent in terms of code, screenshot and concept. One can also publish soap web service using java se

  • Alexander Podkutin

    Thanks, very helpfull!

  • Emmanuel Kayembe Ilunga

    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

  • Prashu

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

  • http://theopentutorials.com/examples/java-ee/jax-ws/create-and-consume-web-service-using-jax-ws/ dave

    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

  • lavanya

    Hi

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

    Thanks
    Lavanya

  • vijay

    Hi,

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

    thanks…………

  • Sunil

    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.

    • http://theopentutorials.com Praveen Macherla

      The jdk/bin should be added to the path. See Java installation tutorial.

  • Sarabjeet Singh

    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.

  • Babak

    Great article. Well done.

  • ms

    Nice and Simple. Well done!

  • avinash

    thanks a lot for a working example. It helped me a lot

  • nakul_dev

    Well explained and to the point information provided… Thanks for sharing valueable information…

  • Shailesh

    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.

    • http://theopentutorials.com Praveen Macherla

      Add jdk bin folder to the PATH environment variable. Check java installation post. See this link.

    • Don

      wsgen & wsimport is a tool of jdk (jdk/bin)

  • prabakaran

    please give me a example for multipart file upload using webservice

  • Pingback: Criando Web Service e Web Service-Client com JAX-WS passo a passo | carledwin & Java

  • Pingback: Tao webservice su dung eclipse « Lập trình quán

  • vijay Kashav

    Dear Sir,
    While i am generating client code through wsimport Illegal Argument Execption occurred like
    parsing WSDL…
    Exception in thread “main” java.lang.IllegalArgumentException: http://www.w3.org
    /2001/XMLSchema
    at javax.xml.validation.SchemaFactory.newInstance(SchemaFactory.java:181
    )
    at com.sun.tools.internal.xjc.api.impl.s2j.SchemaCompilerImpl.bind(Schem
    aCompilerImpl.java:214)
    at com.sun.tools.internal.xjc.api.impl.s2j.SchemaCompilerImpl.bind(Schem
    aCompilerImpl.java:74)
    at com.sun.tools.internal.ws.processor.modeler.wsdl.JAXBModelBuilder.bin
    d(JAXBModelBuilder.java:123)
    at com.sun.tools.internal.ws.processor.modeler.wsdl.WSDLModeler.buildJAX
    BModel(WSDLModeler.java:2234)
    at com.sun.tools.internal.ws.processor.modeler.wsdl.WSDLModeler.internal
    BuildModel(WSDLModeler.java:176)
    at com.sun.tools.internal.ws.processor.modeler.wsdl.WSDLModeler.buildMod
    el(WSDLModeler.java:122)
    at com.sun.tools.internal.ws.wscompile.WsimportTool.run(WsimportTool.jav
    a:172)
    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.WsImport.main(WsImport.java:41)

    Please give me solution.

    Vijay Kashav

    • Don

      Is ur wsdl present?

  • Gopinath

    Hi, In the above example, how to call the web service method “add” from javascript ?. Please let me know if any idea. thanks, Gopinath

  • Sathish Kumar Narayanan

    Wonderful article !! got the basics of JAX WS without confusing it with axis 2 and cxf ..

  • Thirumala Reddy

    Thanks for article. I got the basics of JAX WS.

    I have problem at
    In soapUI

    10
    20

    In place of arg0 and arg1 i want replace with firstNumber and secondNumber. where can i change.

    • Thirumala Reddy

      I got it ……

  • Sailaja

    Very useful document and clear article

  • Dawood Syed

    I have created the WS and consumed it for the 1st time ever using the example provided above. Awesome example with very good details to the point. Thanks a lot Praveen! – Dawood

  • Sharad Meena

    Thanks praveen for the nice Web Service Tutorial. I am getting below error while generating client classes using ‘wsimport’; need your help. Getting below errors….
    D:SETDEVTools-UsedTestAppsCalcWSClient>C:jdk1.7.0_25binwsimport -s src -d bin http://localhost:8080/CalcWS/Calculator?wsdl
    parsing WSDL…
    [ERROR] Server returned HTTP response code: 502 for URL: http://localhost:8080/CalcWS/Calculator?wsdl
    Failed to read the WSDL document: http://localhost:8080/CalcWS/Calculator?wsdl, because 1) could not find the document; /2) the document could not be read; 3) the root element of th
    e document is not .
    [ERROR] failed.noservice=Could not find wsdl:service in the provided WSDL(s):
    At least one WSDL with at least one service definition needs to be provided.
    Failed to parse the WSDL.

    • Aravind Swamy Naidu

      Facing the same error. Any solution guys???

      • Amir Farooq

        any update on this as i am facing the same issue even though i can see the result in the browser

  • Sanjay Kumar

    what is QName in CalculatorService

  • Leena

    hey the tutorial is nice but am getting an error 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 as yours
    and there are two projects that is CalcWS and CalcWSClient
    it might be a silly mistake but am a beginner so plz help. Thanks.

    • Leena Sri

      please help me in this regard

  • Kumaran

    Hii I Got below error on executing ” wsimport -s src -d bin http://localhost:8080/CalcWS/Calculator?wsdl ” in cmd pmt

    [ERROR] Server returned HTTP response code: 400 for URL: http://localhost:8080/CalcWS/Calculator?wsdl

    Failed to read the WSDL document: http://localhost:8080/CalcWS/Calculator?wsdl, because 1) could not find the document; /2) the document could not be read; 3) the root element of the document is not .

    [ERROR] failed.noservice=Could not find wsdl:service in the provided WSDL(s):

    At least one WSDL with at least one service definition needs to be provided.

    Failed to parse the WSDL.

  • Aravind Swamy Naidu

    Praveen Macherla Hi Praveen could you please check the below issue. im unable to run wsimport. Please let me know the solution.

    D:workspace1CalWS7Client>wsimport -s src -d bin http://localhost:8080/CalWS7/Calculator7?wsdl

    parsing WSDL…

    [ERROR] Server returned HTTP response code: 502 for URL: http://localhost:8080/CalWS7/Calculator7?wsdl

    Failed to read the WSDL document: http://localhost:8080/CalWS7/Calculator7?wsdl, because 1) could not find the document; /2) the document could not be read; 3) the root element of the document is not

    .

    [ERROR] failed.noservice=Could not find wsdl:service in the provided WSDL(s):

    At least one WSDL with at least one service definition needs to be provided.

    Failed to parse the WSDL.

    • The Open Tutorials

      The server may not be running. Make sure you are able to view the wsdl in browser by specifying the url directly in address bar.

      • Amir Farooq

        i am facing the same problem, however the server is running and i am able to see the response on the browser but when i am using cmd prompt for wsimport facing the same issue. please help need in dire need of a solution.

    • http://theopentutorials.com Praveen Macherla

      Also check if your pc is behind a proxy.

  • raushan

    Its very helpful for me to understanding basic.
    Thanks a lot

  • Pingback: Provider com.sun.xml.ws.spi.ProviderImpl could not be instantiated

  • Pingback: What is the easiest way to generate code from wsdl (cxf)?

  • Pingback: Are no stub classes indispensable to horde a standalone webservice ? don't we need a server to horde a webservice? - Zieler Gyan