Wednesday, September 17, 2008

Building JAX-WS web service

Last year I wrote a small step by step guide to build JAX-RPC web services. Now JAX-RPC has been replaced by new standard JAX-WS, so I thought it is good time to write an entry for JAX-WS as well. Building web services with JAX-WS is pretty straight forward though it might look cumbersome to a newbie. In this entry I am going explain the basic steps for building a Java first web service, which I developed and tested with JAX-WS 2.1.4, Java 6 update 6 and Tomcat 6.0.16.

Step #1 - Write an interface

@WebService(targetNamespace = "", name = "MyService")
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL)
public interface MyService {

    String sayHello(@WebParam(name = "name") String name);

Step #2 - Implement the interface
@WebService(endpointInterface = "pkg.MyService")
public class MyServiceImpl implements MyService {

    public String sayHello(String name) {
        return "Hello " + name + "!";

Step #3 - Configure web.xml

The JAX-WS context listener and servlet are required to be configured in deployment descriptor (web.xml). The WSServletContextListener initializes and configures the web service endpoint and WSServlet serves the service requests using implementing class.

Step #4 - sun-jaxws.xml

The JAX-WS RI uses information available in this file while initializing and configuring a web service endpoint. This file should be present in WEB-INF directory.
        url-pattern='/myService' />

Step #5 - Build and deploy

Here is an Ant script to prepare the server side stuff-
<!-- Define classpath. -->
<path id="jaxws.classpath">
    <pathelement location="${java.home}/../lib/tools.jar" />
    <fileset dir="${jaxws.lib.dir}">
        <include name="*.jar" />

<!-- Declare ant tasks required to generate service and client. -->
<taskdef name="apt" classname="" classpathref="jaxws.classpath" />
<taskdef name="wsgen" classname="" classpathref="jaxws.classpath" />
<taskdef name="wsimport" classname="" classpathref="jaxws.classpath" />

<!-- Run the 'apt' tool on annotated code to generate server side stuff. -->
<target name="buildService">
    <apt fork="true" destdir="${classes.dir}" 
         debug="${debug}" verbose="${verbose}" classpathref="jaxws.classpath">
        <source dir="${src.main.dir}">
            <include name="**/" />

    <jar destfile="${build.home}/server.jar" basedir="${classes.dir}" compress="true" />

Now package all this in a WAR file and deploy on the server. The web service can be accessed at http://localhost:8080/testws/myService (URL may change according to the server configuration).

Update Feb 13, 2009: With latest versions of Java 6 and JAX-WS, apt task is optional. See this comment below.

Step #6 - Generate client

And this script will generate client side stubs. Here first we are generating WSDL and then using that to generate client side stubs. Though we can avoid the WSDL generation and use the live URL by deploying the web service on a server but usually that is not feasible in a project where build process is automated.
<!-- Generate the client, for that first WSDL needs to be generated. -->
<target name="genClient" depends="buildServer">
    <wsgen sei="pkg.MyServiceImpl" 
        genwsdl="true" verbose="${verbose}" keep="true">
            <pathelement location="${classes.dir}/server" />

    <wsimport destdir="${classes.dir}/client" 
        package="pkg" debug="${debug}" 
        xendorsed="true" keep="true" />

    <jar jarfile="${build.home}/ws-client.jar" basedir="${classes.dir}/client" compress="true" />

Step #7 - Invoke the service

Here is the sample code to invoke the web service, which we just built and deployed.
// Get a handle to web service client interface
WebServiceClient ann = MyServiceImplService.class.getAnnotation(WebServiceClient.class);
MyServiceImplService service = new MyServiceImplService(new URL(
    new QName(ann.targetNamespace(),;
MyService myService = service.getMyServiceImplPort();

// Invoke methods
String hello = myService.sayHello("Vinod");

Thats it. We are done. Source code of this example is available here.

Update Apr 12, 2010 - A new post JAX-WS Web service with Maven shows usage of Maven as build script for building JAX-WS web services.


Anonymous said...

Have you kept source files in this tutorial where we can directly download and test it

Anonymous said...

I am using eclise Version: 3.4.1,tomcat 6.0 and jdk-6u10-windows-i586-p,JAXWS2.1.4-20080502. Anything other than this I need to install? Could you provide more step and source code?

Anonymous said...

The code available in this entry the only thing that one will need to deploy and test a web service.

The steps mentioned also should be sufficient and the packages you installed will work for this example.

Anonymous said...

Thanks! I followed your tutorial, and I was able to get a jax-ws webservice up and running.

My only problem now is that the WSDL seems to be split in two parts, one part containing the service and the binding definitions, and one imported part containing the port type and the message definitions.

This is a problem because I'm importing the WSDL in an old Borland Delphi 7 project, and the importer does not parse the import tag properly.

Do you know if there's a way to make the server output a single WSDL containing all the definitions?

Anonymous said...

Unfortunately JAX-WS RI from Sun does not support single WSDL generation. See here

Though the way it segregates the WSDL components into separate parts is really good, but not all tools can consume that.

Anonymous said...

Thank you for the detailed example. I have run into a problem I can't seem to figure out. At the wsimport task I get an error that says "authorization file not found". I can't seem to find any information what the authorization file is for or what to put in it, even though I found the -xauthfile line for ant and command line. If you can help, it would be very appreciated.

Anonymous said...

I never came across "authorization file not found". Seems to be something weird.

Anonymous said...

It would be great for a newbie if u elaborate it like steps for wsgen is missing give the full ant build.xml and can you please explain the steps more thoroughly for a newbie like me

Anonymous said...

How to deployt the application on tomcat I mean how to generate the WSDL using WSGEN .Can u give the direction on which file to run wsgen on

Anonymous said...

java.lang.NoSuchMethodError: com.sun.xml.bind.api.JAXBRIContext.mangle..

This error is thr wen i run wsgen why

Anonymous said...

am using JDK6 update 10 and not able to run the application what changes i need to make

Anonymous said...

I am getting the wsdl but how do i get the result in my browser like Hello myname i passed this URL


but it gives me a table instead of the result

Anonymous said...

Sorry for the previous post
I am getting the wsdl but how do i get the result in my browser like Hello myname i passed this URL


but it gives me a table instead of the result

Anonymous said...

To test the web service generate client side stubs and invoke a method programmatically. To test a web service in browser you need a tool something like Soap Client

Anonymous said...

After the wsimport it gave me some more files which all files will i need for client

Anonymous said...

I have deployed the wervice on tomcat on my local system and want to access the service through browser how do i do that

Anonymous said...

See Step #5 - Build and deploy

Anonymous said...

Source code for this example is available here.

Anonymous said...

I am a new bie to webservices, i was able to get through till wsgen, but when running wsgen, i got this error pkg.MyServiceImpl is not found.

can you please help me what needs to be done inorder to locate this class

Anonymous said...

Did you tried it with the source code available with this post?

Rahul Juneja said...

I did try this source code and everything seems to be good but i was just wondering do we still need apt - annotation processing tool with the latest version of JAX-WS or we can just write the classes and compile it and drop the war file in the server and server on deploy/runtime time parses those annotations and host webservice.


Anonymous said...

Yes Rahul, now apt task is optional. Tried it wih JAX-WS 2.1.5, Java 6 update 10 and Tomcat 6.0.18. All works well without apt task.

Anonymous said...

Hello vinod,

I am using maven to generate my artifacts. I have a simple pojo class that i have annotated as a webservice.
maven is generating the wsdl file and the request and responsjavascript:void(0)e wrapper files , but it is NOT generating the
client proxy classes that are required. I think in ANT we use the APT tool to generate these, but in Maven , i am not able to use them .

using jax-ws 2.1 and maven 2.0.9

maven entry without the angle brackets

i have used the following entries within the configuration element of the mojo plugin

sei - name of the impl class
genWsdl - set to true
resourceDestDir - for wsdl
verbose - set to true

Any help , greatly appreciated. Banging my head on this for last 4 days.


Rahul Juneja said...


Does this code helps you. I took this from sun website.

Anonymous said...


You will need to do something like-

                        <id>My Service</id>
                        <id>My Service</id>

Anonymous said...

vinod , Rahul :

Many thanks for your quick response to my question on generating client classes. I have used vinod s solution of using both wsgen and wsimport in my pom.xml and now the client classes are being generated .

I read the link suggested by Rahul Junega about JAX-WS and maven. I think there is NO mention of the fact that both wsimport as well as wsgen should be used if we want to have client classes as well as the wsdl to be generated from the SEI .

It s been a steep climb !. Thanks for your help !

Kasi said...

I have a method in my class that takes a Item java class as a parameter and returns a Person java class. Both are simple pojo's .

I am using jax-ws and use maven commands like wsimport and wsgen to generate my client artifacts and .wsdl file.

How do one create the Item class that needs to get passed across the wire to the webservice.

Also when we want to test the above call from a main() method, how do we populate the parameter.

Has anyone come across this scenario before ?

Many thanks for looking.

Anonymous said...

Replying to my own question raised on 18th March 2008 -

1. In a client class , when we need to pass a java object as a parameter to the webservice method call ,
we will have to take a look at the generated ObjectFactory class that has several convienience methods
( createXXX() methods ) :

ex :
ObjectFactory objectFactory = new ObjectFactory();
cockpit.jaxws.client.Item itemParam = objectFactory.createItem() ;

2. By inspecting the classes generated for us by the JAX WS RT , we can set parameters correctly when making a call to the WS from our client class .

3 . Also if the WS call ,returns us a say a Java Object(then we can use the getReturn() method found in all the complex types generated classes.

Hope this helps someone who gets caught out like me .

Anonymous said...

Two questions of the generation of the JAX-WS artifacts pertaining to
wsgen and wsimport .

wsgen question
1) With the wsgen plugin ,we have
configuration tag

Here we specify the FQCN of the MyImpl class . Hence we are stuck to only one java class , which will have the @WebService annotation to be exposed as a Webserivce.

What if we have several classes that need to be exposed as webservices ?

Is there a way to specify multiple
sei> classes.

2) Related wsimport question
In a contract last scenario in JAX-WS when we run the wsgen goal,
then each of these classes should be generating a separate .wsdl file
The .wsdl files which will then find a place under
the wsimport goal like this

goal wsgen
end goal tag
end goals tag

wsdlFiles tag
wsdlFile -tag
List tag - MyImplService.wsdl
List tag - MyImplService2.wsdl
wsdlFile -end tag wsdlFiles - end tag

Having multiple sei and multiple wsdlFiles will certainly help in cleaner and self contained devlopment and prevent clutter.
Any help , greatly appreciated

Anonymous said...

Kasi, March 18
wsimport generates necessary classes to be used as input / output for web service methods, one can use those objects (POJOs). For testing in main() method, just create an instance of the relevant generated class, populate the required fields and pass the object as web service method argument.

Kasi, March 23
1. No need to look at ObjectFactory, just create instance of the generated classes as explained above.
2. Yes.
3. Just use the returned object, which is a POJO.

Kasi, March 24
Invoke wsgen / wsimport multiple times, once for each @WebService class. Remember here we need wsgen just to enable the wsimport to generate the client. If WSDL files are already available then this wsgen task is not required. One another use of this WSDL is explained here

Anonymous said...

could you please look in to a problem i have encountered with adding content to the soap message body part which i have posted in the forum "". Thank you

Anonymous said...

Hi Vinod,

Thank you for your response according to the discussion in the page:

I need your help if possible.
I am beginner in developing with web services and have some questions:

the second application receive the object sent by the first one,
1)need I to create a client?
If yes,in which side and how?
Can I use Eclipse WTP to generate the client?
2)The first step I did is to create the web service from a Java Class which contains the method send but eclipse return an error: IWAB0019E Error in getting method from Java bean. I don't know how to resolve the problem.

3)How can I begin:

Now I have two java classes, the first one contains the method send which returns a java object and the second contains the method receive not implemented yet.

With kind regards.

Anonymous said...

1. Yes, client side stubs are required by the application, which consumes the web service. You can use ant task mentioned at step #6. I never used Eclipse WTP.
2. For exposing web service (@Stateless and @WebService) with Weblogic 10, running 'apt' task on web service class is enough. Otherwise steps mentioned here to build web service should work with Weblogic 10 as well.

Anonymous said...

1)Where should I write the XML code mentioned at step #6?
what would be the result of this XML code(creating automatically a new project of the client or what?)
2)The code mentioned at step #7 contain an URL,I think I don't need web page in My project, do I?
3)Where should I write the interface and its implementation mentioned at step #1 an #2?Under a new web project that I have to create?
3)You said to package all this in a WAR file, have I to package them together in the same directory or what?


Anonymous said...

1. In ant build script. Download the code available with this post and go through it. It will help in understanding the whole stuff.
2. Web services in Java are always exposed using a servlet, so a web service will always have an endpoint URL.
3. In the application, which is going to expose the web service.
4. Run the ant script available in the code with this post and look at the generated artifacts, that will make things clear.

Anonymous said...

I have in the web project a folder named build, it is empty.Is there where I should copy the ant script?
how run it? with the server?

Anonymous said...

Hi Vinod,

the second application will receive the object, so I think I should create the web service through its method receive which should be implemented separately as an interface .Do you agree with me?

Anonymous said...

No, web service will be exposed by the first application, which is going to SEND the object. Second application will have the client side stubs (created by wsimport task) to invoke the SEND method of the first application.

Anonymous said...

Thank you for your response.
As you said, the method send should be exposed as web service by the first application, but it contains data types unrecognized by Eclipse as I am working with a private framework that belongs to a company.So an interface is generated to convert to simple types like string and array...
this interface doesn't contain the whole implementation , but only the method's prototype and the conversions.
Should I add the implementation or what?

Anonymous said...

Hi Vinod,

My supervisor told me that I shouldn't expose the method send as web service as the object will be sent internally.He told me to expose the interface of the method receive as web service and create the client in the second application.
I am asked to call the method receive in the method send.
What do you think?

Anonymous said...

Hi Vinod,

I created the client, and some java classes are automatically generated like stub, servicelocator, proxy...
I wrote the code client to access and invoke the service.Where should I place this code.

chinmay said...

Hi Vinod,

I developed a simple hello web service using eclipse 3.4, Axis2 , Tomcat and java 1.5. I am able to successfully test the web service using eclipse web browser. Now i want to access the web service through a jsp client. Can u guide me through..

Please mail me the details to mail id

Any Help will be greatly appreciated..

Thanks in advance..

chinmay said...

Hi Vinod,

I developed a simple hello web service using eclipse 3.4, Axis2 , Tomcat and java 1.5. I am able to successfully test the web service using eclipse web browser. Now i want to access the web service through a jsp client. Can u guide me through..

Please mail me the details to mail id

Any Help will be greatly appreciated..

Thanks in advance..

Anonymous said...

Hi Vinod;

I want to generate axis client from wsdl file,I executed a command line but it doesn't work, have any idea?

With my regards.

Anonymous said...

Hi Vinod,

When I run the genClient im getting error pkg.MyServiceImpl not found.
But the class file is available in the mentioned classpath in the wsgen command.

Anonymous said...

ur really getting famous. I saw ur blog name on google first page. Indeed, this is an achievement.

keep guessing (let u later)

Uday Kumar said...

awesome post. I really very thankfull to you.

Itried so many times to deploy a simple jax-ws webservice in jboss.

Everytime i failed to do that.

First time i found a post which contains series of steps to deploy the jax-ws webservice successfully.

Thanks a lot and i really be the fan of you now.

Anonymous said...

Excellent site/effort!

Vinod, you mention in your examples/comments about JAX-WS RI jars. Can you be more specific?

I mean, what exactly are the jars to be copied into the endorsed directory?

And where does one download them from? What version? (I could not download it from your RI link, is it broken as it did not work for me?)

Anonymous said...

With recent updates of Java 6, endorsed directory mechanism is no longer required for JAX-WS. JAX-WS RI can be downloaded from

Unknown said...

Are SOAP hadlers only way to capture request and resonse XMl while calling web service or there is some other way available as well

Santosh Sharma said...

Dear Vinod,
Thanks for providing good tutorial.

Can we implement JAX-WS using JDK 1.5 and tomcat-5.0.28. Please advise.

nihar said...

Hi Vinod ,

How can i call multiple web services from a single client ?

i have created jax-ws artifacts for both services but the problem is both services are sharing same package name and method names.
so when i am trying to include it in my web service client as a jar its giving me error


Anonymous said...


Why don't you create client stubs for both of the web services in different packages?

nihar said...

Well i want to create client stub for both of the web services in a different package but as i am creating JAX WS client using netbeans , it directly takes package name from WSDL files only.

i dont have a option to generate sources in a different packages as netbeans doesn't allow it to do that.

so do you have any idea how to do it ?


Anonymous said...


No clues about Netbeans though one can always define the package name while invoking 'wsimport' as mentioned at Step #6 - Generate client above.

Anonymous said...

An extremely good intro book on JAX-WS can be found here: Short, thorough and and the "up and running part" is very accurate.

Kiran Kumar S V said...

Good post and very useful Vinod. Every where it is referred as jax-ws is used with java 1.6 version only. is is possible to do all the steps mentioned in 1.5? If so can u pls let me know the dependent libraries?

Anonymous said...


Steps for using JAX-WS with Java 5 would also be same. Only difference is that with Java 5 one has to put JAX-WS jars in classpath.

Anonymous said...

Hi Vinod

I have a problem as mentioned below.
I want to create a webservice which is part of the application.
To start, I have a wsdl and related xsd file.
Using jaxws-maven-plugin's wsimport tool, I got required java classes.
Now I have webservice implementation class which has @Webservice annotation. This annotation has fields like serviceName, portName, endpointInterface & targetNamespace. This class uses these newly generated classes and other classes (from the app) too.
Now using mvn clean package jboss:hard-deploy command, I deploy the war file to jboss server.
When I try to open the url http://localhost:8080/appcontext/serviceName?wsdl it gives me http 404 error which is resource not found.

My war file does not show wsdl file. Please help me to know what am I missing. and where should be the wsdl file in a war file?

Thanks in advance.

Anonymous said...


Did you made relevant entries in web.xml and sun-jaxws.xml files ?

Anonymous said...

Hi Vinod
Thanks for the quick reply.
Giving you more details, actually I am integrating Maven with the existing spring application.
That existing application did not have anything related to WS inside web.xml or sun-jaxws.xml.
Hence I have not updated them explicitly.
But if you could please let me know what changes I should do, I can try.

Thanks so much for your time and help.

Anonymous said...

thank you so much sir. Very useful article that solved my problem.

Raman said...

Hi Vinod,

Looking forward to extended help

We have built few web-services for different arch layers

Main-WS: runs on web server (Apache)

myINTERFACEservice – runs on App server (Tomcat)

myservice1 - runs on App server (Tomcat)
myservice2 - runs on App server (Tomcat)
myservice3 - runs on App server (Tomcat)
myservice4 - runs on App server (Tomcat)
myservice5 - runs on App server (Tomcat)

WS (myservice1, 2, 3……) are intended to only communicate thru “myINTERFACEservice” running on Tomcat

In local QA environment all are working fine as intended BUT fails in production environment.

Presently, our Web Server (Apache in port 80) and Application Server (Tomcat in port 1024) running in the same box although both Web Server & Application Server do communicate but communication with webservices are still a challenge in productive environment.

Also looking forward to configure webservices in Tom to be evoked thru only Main-WS in Apache

Please advice

Raman said...

Thank you very much. This was very useful for me.
It is unbelievable how many incomplete and even misleading posts regarding the topics of the application server deployment nightmare are out there. It is good to see something coherent and correct like this.

Anonymous said...

Hi Vinod,

This example is very good to start with the webservices project.

However I tried to add more service classes and get the following error

\src\java\com\demo\service\ The endpoint interface com.demo.service.SecondService does not match the interface com.demo.service.FirstService.

Looks like apt is not able to map the classes.. For e.g. here it is trying to compile but mapping to

Can you please help me on this?


Vinod Singh said...


Looks like your bumping into this bug / limitation of JAX-WS You should keep web services classes in different package and process them separately.

sathish said...

i read ur post.This s very useful to me.For my b.e project, i have created a simple jax-ws calc application.Also a client service is created and the corresponding service is consumed and i m getting output.
the next module i have to do is to implement xml attacks in webservice.i have googled many websites,but cant do anything....can u please help me sir?
i need to finish this module for further extension to my project.....


Vinod Singh said...


What is xml attacks in webservice ?

Anonymous said...

Hi Vinod,

we can create each service as a separate jar file and include it in the war file while creating.

For this we need to iterate the buildServer target by passing the service names and creating service specific jars.

The bad part with this approach is we cannot control including the common classes in each jar file though we can control the main service implementation classes i.e. all the common class files will be part of each service jar file.

But my problem is solved since I need at most 2 to 3 services in my application and they are just for testing purposes only not for prod deployment.

Thanks for the wonderful start up code for webservices.


Anonymous said...

Hey Vinod,

Appreciate all your help. I just started working on JAX-WS i could create the JAX-b objects and client as well.

I'm actually consuming services from a 3rd party service provider. all i have to do is write client and get response.

And i even developed the client. when i run the client from my work place i get a HTTP transport error:

But when i run the same from out of my VPN i get the response. I been trying to find out how do i add the proxy to the webservice call in JAX-WS

Vinod Singh said...

See here Proxy Authentication in Java

Anonymous said...

Awesome tutorial Sir. I was able to deploy service on localhost and consume it with the client you mentioned. I am new to java web services. What will i have to do deploy service in apache on my pc and let others consume it with client through the Internet? Is is possible? Or can i deploy on a globally accessible apache server and then consume it through its URL? If yes please guide me. Thanking you in advance

Anonymous said...

The problem with examples like these is they always seem to use simple return types. This seems a little pointless, what about complex object binding e.g. Account or user or something other than "hello"?