Deploy JAX-WS web services on Tomcat

Here’s a guide to show you how to deploy JAX-WS web services on Tomcat servlet container. See following summary steps of a web service deployment.

  1. Create a web service (of course).
  2. Create a sun-jaxws.xml, defines web service implementation class.
  3. Create a standard web.xml, defines WSServletContextListener, WSServlet and structure of a web project.
  4. Build tool to generate WAR file.
  5. Copy JAX-WS dependencies to “${Tomcat}/lib” folder.
  6. Copy WAR to “${Tomcat}/webapp” folder.
  7. Start It.

Directory structure of this example, so that you know where to put your files.

jaxws-deploy-tomcat--folder

1. WebServices

A simple JAX-WS hello world example.

File : HelloWorld.java


package com.mkyong.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 getHelloWorldAsString();
	
}

File : HelloWorldImpl.java


package com.mkyong.ws;

import javax.jws.WebService;

//Service Implementation Bean

@WebService(endpointInterface = "com.mkyong.ws.HelloWorld")
public class HelloWorldImpl implements HelloWorld{

	@Override
	public String getHelloWorldAsString() {
		return "Hello World JAX-WS";
	}
}

Later, you will deploy this hello world web service on Tomcat.

2. sun-jaxws.xml

Create a web service deployment descriptor, which is also known as JAX-WS RI deployment descriptor – sun-jaxws.xml.

File : sun-jaxws.xml


<?xml version="1.0" encoding="UTF-8"?>
<endpoints
  xmlns="http://java.sun.com/xml/ns/jax-ws/ri/runtime"
  version="2.0">
  <endpoint
      name="HelloWorld"
      implementation="com.mkyong.ws.HelloWorldImpl"
      url-pattern="/hello"/>
</endpoints>

When user access /hello/ URL path, it will fire the declared web service, which is HelloWorldImpl.java.

Note
For detail endpoint attributes , see this article.

3. web.xml

Create a standard web.xml deployment descriptor for the deployment. Defines WSServletContextListener as listener class, WSServlet as your hello servlet.

File : web.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, 
Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>
    <listener>
        <listener-class>
                com.sun.xml.ws.transport.http.servlet.WSServletContextListener
        </listener-class>
    </listener>
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>
        	com.sun.xml.ws.transport.http.servlet.WSServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>120</session-timeout>
    </session-config>
</web-app>

4. WAR Content

Use Ant, Maven or JAR command to build a WAR file to include everything inside. The WAR content should look like this :


WEB-INF/classes/com/mkyong/ws/HelloWorld.class
WEB-INF/classes/com/mkyong/ws/HelloWorldImpl.class
WEB-INF/web.xml
WEB-INF/sun-jaxws.xml
Note
For those who are interested, here’s the Ant file to build this project and generate the WAR file.

File : build.xml


<project name="HelloWorldWS" default="dist" basedir=".">
    <description>
        Web Services build file
    </description>
  <!-- set global properties for this build -->
  <property name="src" location="src"/>
  <property name="build" location="build"/>
  <property name="dist"  location="dist"/>
  <property name="webcontent"  location="WebContent"/>

  <target name="init">
        <!-- Create the time stamp -->
        <tstamp/>
        <!-- Create the build directory structure used by compile -->
        <mkdir dir="${build}"/>
  </target>

  <target name="compile" depends="init"
  	description="compile the source " >
        <!-- Compile the java code from ${src} into ${build} -->
        <javac srcdir="${src}" destdir="${build}"/>
  </target>

  <target name="war" depends="compile"
  	description="generate the distribution war" >
	    
	<!-- Create the war distribution directory -->
  	<mkdir dir="${dist}/war"/>
    
  	<!-- Follow standard WAR structure -->
  	<copydir dest="${dist}/war/build/WEB-INF/" src="${webcontent}/WEB-INF/" />
  	<copydir dest="${dist}/war/build/WEB-INF/classes/" src="${build}" />
  		
	<jar jarfile="${dist}/war/HelloWorld-${DSTAMP}.war" basedir="${dist}/war/build/"/>
  </target>
  
</project>

5. JAX-WS Dependencies

By default, Tomcat does not comes with any JAX-WS dependencies, So, you have to include it manually.

1. Go here http://jax-ws.java.net/.
2. Download JAX-WS RI distribution.
3. Unzip it and copy following JAX-WS dependencies to Tomcat library folder “{$TOMCAT}/lib“.

  • jaxb-impl.jar
  • jaxws-api.jar
  • jaxws-rt.jar
  • gmbal-api-only.jar
  • management-api.jar
  • stax-ex.jar
  • streambuffer.jar
  • policy.jar

6. Deployment

Copy the generated WAR file to {$TOMCAT}/webapps/ folder and start the Tomcat server.

For testing, you can access this URL : http://localhost:8080/HelloWorld/hello, if you see following page, it means web services are deploy successfully.

jaxws-deploy-tomcat--example

Download Source Code

Download It – JAX-WS-Deploy-To-Tomcat-Example.zip (13KB)

Reference

  1. JAX-WS WAR File Packaging
  2. Deploying Metro endpoint
  3. Publishing a RESTful Web Service with JAX-WS

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Fremont
Guest
Fremont

i use latest jaxws-ri-2.x.jar. I found ha-api.jar and jaxb-core are also required.

Carlos
Guest
Carlos

Thanks Fremont! I was missing that!

Arnon
Guest
Arnon

Hi Mkyoung, thanks for your tutorial. I Did exactly what you say and worked perfectly ;)

Raja
Guest
Raja

Does this websevice works fine on Websphere server v8.0 Or do we need to change anything. Please advice

Yogesh Malhotra
Guest
Yogesh Malhotra

If I understood it correctly, sun-jaxws.xml and servlet config is required in case of deploying web service to tomcat server only.

lorenzo
Guest
lorenzo

Using eclipse and crating a new java project…the same using the command jar -cvf WebServices.war * it create only the xml file but not the classes………WHY????

ramasrinu
Guest
ramasrinu

and wsdl as follows…..

ramasrinu
Guest
ramasrinu

Hi young…wsdl document cant be parsed in client app….why wsdl document not well structured…following exception coming at client app

parsing WSDL…

[ERROR] Server returned HTTP response code: 502 for URL: http://localhost:8585/SampleWebService/hello?wsdl

Failed to read the WSDL document: http://localhost:8585/SampleWebService/hello?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):

Luca Viggiani
Guest
Luca Viggiani

Hi, thanks for your tutorial. Just as a side note, in your para 5. “JAX-WS Dependencies”, two jars are missing: jaxb-core.jar and ha-api.jar (with jaxws-ri-2.2.10.zip)

Rob
Guest
Rob

How do I see the actual output? I want to output something with my service

Arnab
Guest
Arnab

What if I have two Service implementation?

Allen Eben
Guest
Allen Eben

Thanks for a great tutorial but am still having

HTTP Status 404 – /HelloWorld-20101123/hello
type Status report
message /HelloWorld-20101123/hello
description The requested resource (/HelloWorld-20101123/hello) is not available
I copied the required jar files to /usr/share/tomcat7/lib. please is that the correct path to tomcat7 lib folder

javawsnewbie
Guest
javawsnewbie

Hi, I followed your tut but didn’t want to use eclipse but when I deployed under tomcat I got error 404 why ? My files structure here http://www33.zippyshare.com/v/70463488/file.html

Sagnik
Guest
Sagnik
when i try to deploy the war in JBoss/Tomcat it gives along list of exception— org.apache.catalina.LifecycleException: Failed to start component [Stan e[Catalina].StandardHost[localhost].StandardContext[/HelloWorld-2010112 at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.j at org.apache.catalina.core.ContainerBase.addChildInternal(Cont .java:901) at org.apache.catalina.core.ContainerBase.addChild(ContainerBas 7) at org.apache.catalina.core.StandardHost.addChild(StandardHost. at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig. ) at org.apache.catalina.startup.HostConfig$DeployWar.run(HostCon 1880) at java.util.concurrent.Executors$RunnableAdapter.call(Executor 1) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.jav at java.util.concurrent.FutureTask.run(FutureTask.java:166)……… Can anyone help me with this
Umanath M
Guest
Umanath M

After generate war by ran ant build.xml, the given url http://localhost:8080/HelloWorld/hello not working, so i did to changed the url http://localhost:8080/HelloWorld-20140512/hello It working fine, But WSDL could not open by using http://localhost:8080/HelloWorld-20140512/hello?wsdl. So how i can do ?

Hua Jie Yang
Guest
Hua Jie Yang

Is there anyway excluding adding web.xml entry? It’s urgly code.

trackback
404 Nicht gefunden: Invalid Request jax ws web service | Technology & Programming

[…] wrote a java jax-ws web service. I used this […]

Pise
Guest
Pise
Hi Mkyong, When I deploy above webservice in Jboss 4.2 it is working fine but when I deploy the same in Jboss 5.1 GA deployment fails and I get exception java.lang.LinkageError: loader constraint violation in interface itable initialization: when resolving method “com.sun.xml.ws.util.xml.XMLStreamReaderFilter.getAttributeName(I)Ljavax/xml/namespace/QName;” the class loader (instance of org/jboss/classloader/spi/base/BaseClassLoader) of the current class, com/sun/xml/ws/util/xml/XMLStreamReaderFilter, and the class loader (instance of ) for interface javax/xml/stream/XMLStreamReader have different Class objects for the type javax/xml/namespace/QName used in the signature I googled and come to know that this is due to some conflict in jar files but I am not able to identify which jar… Read more »
saibal
Guest
saibal
I am using tomcat/6.026 in windows. A. I got the error “SEVERE: Error listenerStart” after I added the jars in STEP 5 SOLUTION: Add the following 2 additional jars (as Kaushal has mentioned) 1. ha-api.jar 2. jaxb-core.jar B. From the download source code I took the HelloWorld-20101123.war and pasted it in the tomcat webapps directory while tomcat was running and automatically the application was deployed (hot deploy). Then I typed in the following in the browser http://localhost:8080/HelloWorld-20101123/hello and it works Thanks a lot to Mr. mykong who is doing a wonderful job in helping us with all the examples and… Read more »
scl
Guest
scl

yeah!!! working…

Chris the Viech
Guest
Chris the Viech

If you run into issues, just copy the whole content of the lib folder from the extracted jaxws-ri to your Tomcat libs folder. Worked for me. Greets

trackback
Tomcat JAX-WS deployment strange message: Prefix ‘ ‘ is already bound to ‘ ‘. Huh? | Ask & Answers

[…] I found the following simple tutorial which seems pretty good. http://www.mkyong.com/webservices/jax-ws/deploy-jax-ws-web-services-on-tomcat/ […]

faruk cevik
Guest
faruk cevik

Hello;
How can I publish a web service such folder:
http://localhost:8080/wstest/services/converter?wsdl

I tried various combinations but I could not managed

Santosh
Guest
Santosh

When I try to open the Web.xml in browser, I get the below error.

The XML page cannot be displayed
Cannot view XML input using style sheet. Please correct the error and then click the Refresh button, or try again later.

——————————————————————————–

Unspecified error Error processing resource ‘http://java.sun.com/j2ee/dtds/web-app_2_3.dtd’.

apara
Guest
apara

Hi thanks for this post, how can I create the wsdl file for this web service created ?

Beanie
Guest
Beanie

On a browser, type your web service address followed by ?wsdl, like stated on the 6th point (Deployment one).

apara
Guest
apara

Hi, thanks for this post. How can I create a wsdl file for this webservice created ? please help me, im new to WS

Jeet
Guest
Jeet

Thanks for the brilliant insights in java/jee by giving practical example. it would have been great of you have provided some use-cases where these will work.
And please recommend a book for Java Web Services (preferably SOAP)

Wrushasen Dakhane
Guest
Wrushasen Dakhane

Sorry I tried everything mentioned here but I am stuck at
SCHWERWIEGEND: WSSERVLET11: Runtime descriptor cannot be parsed: java
.lang.NoSuchMethodError: com.sun.xml.ws.assembler.TubelineAssemblyController: me
thod ()V not found

Please help me, I am running on Tomcat 7

SoapDummy
Guest
SoapDummy

you must read the older comments.
The answer was already posted.

Best regards.

Deniz
Guest
Deniz

Hi,

I added the jars you mentioned from jaxws-ri-2.2.8 but still no good :/

Kod
Guest
Kod

Any errors / stack trace. I am using this example and have now made it possible 3 external companies to connect to our web services(Well with added security measures). Please describe any errors you get or paste your stack trace..

Deniz
Guest
Deniz

Stack trace is:
SEVERE: WSSERVLET11: failed to parse runtime descriptor: java.lang.NoSuchMethodError: com.sun.xml.ws.assembler.TubelineAssemblyController: method ()V not found
java.lang.NoSuchMethodError: com.sun.xml.ws.assembler.TubelineAssemblyController: method ()V not found
at com.sun.xml.ws.assembler.TubelineAssemblerFactoryImpl$MetroTubelineAssembler.(TubelineAssemblerFactoryImpl.java:98)
at com.sun.xml.ws.assembler.TubelineAssemblerFactoryImpl.doCreate(TubelineAssemblerFactoryImpl.java:302)
at com.sun.xml.ws.api.pipe.TubelineAssemblerFactory.create(TubelineAssemblerFactory.java:111)
at com.sun.xml.ws.server.WSEndpointImpl.(WSEndpointImpl.java:187)
at com.sun.xml.ws.server.EndpointFactory.create(EndpointFactory.java:320)
at com.sun.xml.ws.server.EndpointFactory.create(EndpointFactory.java:315)
at com.sun.xml.ws.server.EndpointFactory.createEndpoint(EndpointFactory.java:158)
at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:577)
at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:560)
at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parseAdapters(DeploymentDescriptorParser.java:303)
at com.sun.xml.ws.transport.http.DeploymentDescriptorParser.parse(DeploymentDescriptorParser.java:179)
at com.sun.xml.ws.transport.http.servlet.WSServletContextListener.parseAdaptersAndCreateDelegate(WSServletContextListener.java:131)
at com.sun.xml.ws.transport.http.servlet.WSServletContainerInitializer.onStartup(WSServletContainerInitializer.java:65)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5280)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:657)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:536)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1462)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:792)
at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1445)
at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:860)
at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:357)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)

Kod
Guest
Kod
Hi Ok, this is classpath issues. Please try the following, assuming you running tomcat 6 or 7 as a stand alone app server (outside an IDE) on windows. 1. Got to the Tomcat lib folder >> C:\TomcatHome\lib find the jaxws-rt.jar (if not found, copy this jar and make sure it exists). 2. Got to c: \Tomcat \ webapps \ yourappname \ lib folder find the jaxws-rt.jar, if found, please remove it, no need for it to be here, Tomcat will find the classes in the main lib folder. Restart tomcat and it should work :-) As for running from an… Read more »
Deniz
Guest
Deniz

Thanks for the answer. But I am using the Tomcat inside NetBeans.. And I already put the jar files under Tomcat’s lib folder, still no good.

Kod
Guest
Kod

Much appreciated,thank you.

Kaushal
Guest
Kaushal

Hi,
I think we have to add jaxb-core.jar and ha-api.jar as well to server lib or project lib.
I have downloaded jaxws-ri-2.2.8 and added following jars to my project lib folder
1. gmbal-api-only.jar
2. ha-api.jar
3. jaxb-core.jar
4. jaxb-impl.jar
5. jaxws-api.jar
6. jaxws-rt.jar
7. management-api.jar
8. policy.jar
9. stax-ex.jar
10. streambuffer.jar

Please check and update the post.

Regards,
kaushal

Blaine Simpson
Guest
Blaine Simpson

Thanks, kaushal. Very useful.

Pallavi
Guest
Pallavi
hi, I have create new dynamic web project.(using eclipse-indigo & tomcat 6) created all classes.web.xml,build.xml,sun-jaxws.xml as specfied above. Also copied below jars : gmbal-api-only ha-api jaxb-impl jaxws-api jaxws-rt management-api policy stax-ex streambuffer and restart the tomcat & i got following exception: Jun 20, 2013 1:20:21 PM org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre6\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre7/bin/client;C:/Program Files/Java/jre7/bin;C:/Program Files/Java/jre7/lib/i386;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\Program Files\ImageConverter Plus;C:\Program Files\ImageConverter Plus\Microsoft.VC90.CRT;C:\Program Files\ImageConverter Plus\Microsoft.VC90.MFC;C:\Program Files\Java\jdk1.6.0_20\bin;C:\Documents and Settings\All Users\Application Data\Titanium\mobilesdk\win32\1.7.3.v20111012114613;C:\apache-ant-1.8.2\bin;C:\WINDOWS\system32\WindowsPowerShell\v1.0;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\TortoiseSVN\bin;C:\Program Files\K-Lite Codec Pack\QuickTime\QTSystem\;D:\GK\SkillSoft Courses\apache-ant-1.8.4-bin\apache-ant-1.8.4\bin;D:\GK\SkillSoft Courses\apache-ant-1.8.4-bin\apache-ant-1.8.4;C:\Program… Read more »
SoapDummy
Guest
SoapDummy

Hi Pallavi,

did you copy the jar into the lib directory beneath /lib or somewhere else?
What about the WARNING about the source parameter?
>>> WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ?source? to ?org.eclipse.jst.jee.server:HelloWorld? did not find a matching property.

Juan Carlos
Guest
Juan Carlos

Hi,

I have a problem, when I deployment the file HelloWorld.war the status aplication?s is false. In the log, the old message is “Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/HelloWorld]]”

Can you help me?