Click here to Skip to main content
Click here to Skip to main content

Create a Simple Web Service Using JBossWS

, 5 Feb 2009
Rate this:
Please Sign up or sign in to vote.
An article on how to create a simple web service using JBossWS, how to deploy and test.

Introduction

A while back, I was assigned to work on a project on which I needed to create a simple web service that would run in JBoss App Server. As I searched the web for some detailed tutorials, I didn't find any detailed tutorial that could help me. Eventually I figured out all the pieces I had the design and implement in order to get such a web service working. I decided to summarize the things I learned in this article, not only for my own record keeping purpose, but also helping others who needed similar information.

The intention of this article is to provide a detailed tutorial on the following topics:

  • Software required for this article.
  • How to create a simple web service for JBoss App Server?
  • How to deploy and undeploy the web service into JBoss App Server?
  • How to design a simple test app to test the running web service?

I hope readers will enjoy this article! If you have any questions of comments, please leave it in the FAQ section.

Background

While I was searching for detailed tutorials, I received great help from this guide. The shortcoming of this guide was the lack of certain details. It may be very obvious to some advance developers, without these details a lot of beginners can get confused. This article attempts to fill these gaps. I recommend readers also review this guide after reading my article.

Install and Configure the Required Software

This tutorial requires setup and configuration of the following software packages:

  • JDK 1.5 (or higher).
  • Apache Ant (current version is 1.7.1).
  • JBoss App Server (current version is 5.0.0 GA).
  • JBossWS (current version is 3.0.5 GA).

I also recommend the use of Eclipse IDE. But, for this tutorial, all work can be done using a simple code editor (like UltraEdit32, Crimson Editor, or Notepad++), Command Prompt, and Apache Ant.

For my own convenience, this tutorial was created on Windows XP. And it should be relative easy to be migrated to other platforms.

Install JDK and Apache Ant

Install JDK on Windows XP is super easy, just download the MSI installer, then install it either default to "Program Files" or directly to "C:\". After installing JDK, it is recommended to configure the system variables:

  1. Create system environment "JAVA_HOME" and point it to the JDK base directory (i.e. C:\Program Files\Java\jdk-1.5.0_17 or C:\jdk-1.5.0_17).
  2. Also add "%JAVA_HOME%\bin" to the system variable "PATH".

After configuring the system variable, open a Command Prompt and type "java -version". The output will indicate the version of JDK installed in the system. This should help verify the success of JDK installation. After the verification, close the Command Prompt.

Install Apache Ant is also easy, download the binary executable archive file from the Apache Ant Project web page (here). Then unzip the archive file to "C:\". This will unpack the archive file to "C:\apache-ant-1.7.1". "C:\apache-ant-1.7.1" will be the base directory of Apache Ant. After the unpacking, also configure the system variables as following:

  1. Create system environment "ANT_HOME" and point it to the Apache Ant base directory (i.e. C:\apache-ant-1.7.1).
  2. Also add "%ANT_HOME%\bin" to the system variable "PATH".

After configuring the system variable, perform verification by opening a Command Prompt and type "ant -version". If configuration is correctly done, the output will indicate the version of Apache Ant installed in the system.

Install JBoss and JBossWS

This tutorial teaches how to create web service that runs in JBoss. So installing and configuring JBoss Application Server (current version 5.0.0.GA) and JBoss Web Services (also refer as JBossWS, current version 3.0.5.GA) is also required. You can find the install packages (zip archives) in these two locations:

The process of installing JBoss is similar to installing Apache Ant. All you need to do is to unzip the archive file containing JBoss App Server binary executables to "C:\". It will create a new directory called "C:\jboss-5.0.0.GA", which is the base directory of JBoss App Server. After the unpacking, create system environment "JBOSS_HOME" and point it to "C:\jboss-5.0.0.GA". Although optional, you can also add "%JBOSS_HOME%\bin" to the system variable "PATH".

The last step is to install JBossWS package. The steps are as following:

  1. First unzip the JBossWS binary executable archive to "C:\". This will create folder "C:\jbossws-native-bin-dist".
  2. From Windows Explorer, navigate to "C:\jbossws-native-bin-dist". Inside the folder, locate the file "ant.properties.example".
  3. Make a copy of "ant.properties.example", then rename it to "ant.properties".
  4. Start up your favorite code editor (like UltraEdit32, or Notepad++), then open up "ant.properties" for editing.
  5. Locate the line "jboss500.home=@jboss500.home@", change it to "jboss500.home=/jboss-5.0.0.GA". Then save it and close the code editor.
  6. Open Command Prompt, navigate to "C:\jbossws-native-bin-dist". Then run the command "ant deploy-jboss500". When it finishes successfully, JBossWS will be installed and configured properly for use.

Create a Simple Web Service

Now we are ready to create a simple web service. There are two ways to create web services:

  • Top down. Using JBossWS to create proxy classes from existing WSDL and associated XSD files. Then implement the web service port interface.
  • Bottom up. Create a simple web service via POJO. Then package the classes for deployment.

In this tutorial, the approach will be discussed is the bottom up approach, because this is the easiest way to create a web service. The source codes can be found in the downloads section. The steps will be discussed in the following sub-sections.

Create a simple Java project

This tutorial uses Eclipse IDE and Apache Ant for building the sample project. Creating this sample project is no different from creating a simple Java HelloWorld project. After getting the sample source code, you can see that in the base directory "webservice", there are two folders:

  • "bin": This folder is used to contain the build output.
  • "src": This folder contains the source. The source file "Greeting.java" can be found under subfolder tutorial/hanbo/webservice.
In the base directory, there are a number of text files:
  • .classpath: This file is auto-generated by Eclipse.
  • .project: This file is also auto-generated by Eclipse.
  • build.xml: This is the Apache Ant build file.

First, let's take a look at the source file "Greeting.java". The entire source code looks like this:

package tutorial.hanbo.webservice;

import javax.jws.WebService;
import javax.jws.WebMethod;

@WebService
public class Greeting
{
   @WebMethod
   public String greetClient(String userName)
   {
      return "Greeting " + userName + "! Have a nice day...";
   }
}
This is all the Java code you need to write to create a simple web service. Let's examine the source in detail:
  1. The first line declares the package of the web service.
  2. The next two code lines imports the classes needed. They are annotations used by class declaration and method declaration.
  3. Declare a class called "Greeting"; it is annotated with "WebService", which means that the class "Greeting" is a web service.
  4. Inside class "Greeting", declare a public method called "greetClient()". It is annotated with "WebMethod", which means that this method is a web method that can be invoked remotely.
    • Method "greetClient()" takes a String type parameter called "userName". Its body will create a new String object and return.

If the reference libraries are not added to this project, the project won't compile in Eclipse. So take a look at the .classpath file and see all the needed reference libraries (i.e. the referencing jar files). These libraries were part of the JBoss package. They can be found in 3 different folders:

  • C:\jboss-5.0.0.GA\client
  • C:\jboss-5.0.0.GA\lib
  • C:\jboss-5.0.0.GA\lib\endorsed
Just add all these jar files in the three folders to the sample project, then all the compile errors will be gone. However, two jar files must be removed, they are:
  • C:\jboss-5.0.0.GA\client\jaxws-rt.jar
  • C:\jboss-5.0.0.GA\client\jaxws-tools.jar
The reason that they must be removed from the project was to get rid of an exception. This may have been a weird bug with JBossWS. When I first worked on this sample, I had encountered the exception while trying to deploy the completed web service to JBoss App Server. After searching through Google results, the solution I found was to get rid of these two jar files from the project classpath.

The Deployment Descriptor

A web service has to be deployed in order for the client access. In this tutorial, the web service will be packaged as a war file and deployed as a servlet. The war file contains a deployment descriptor, a file named "web.xml" specifies the URL.Servlet mapping. When a request is sent to JBoss App Server, JBoss will route the request to specific servlet based on the URL/Servlet mapping specified in the web.xml files.

In the project's base directory, you can locate the web.xml file in src/resources sub directory. The content of this file looks like this:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
 "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
  <servlet>
    <servlet-name>GreetingWebService</servlet-name>
    <servlet-class>tutorial.hanbo.webservice.Greeting</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>GreetingWebService</servlet-name>
    <url-pattern>/*</url-pattern>
  </servlet-mapping>
</web-app>

The content of this descriptor file can be easily understood. The entire content has two parts:

  • The first part (from <servlet> to </servlet>) specify what the servlet is. It has a name "GreetingWebService" and mapped to a Java class "tutorial.hanbo.webservice.Greeting".
  • The second part (from <servlet-mapping> to </servlet-mapping>) specify the URL to servlet mapping. If the request URL points to the web service, then the request will be handled by the web service.

Next section will describe how to package the war file.

Packaging with Apache Ant

Packaging the war file can be done with Apache Ant. In the build.xml, you can find a number of targets. They are used to perform build actions. One of the targets has the name of "packaging". This is the target used to create a war file for deployment, as shown following:

<target name="packaging" >
  <war destfile="bin/greeting.war" webxml="src/resources/web.xml">
    <classes dir="bin/classes"/>
  </war>
</target>

In this target section, there is only one action to perform -- to build a war file using a task named "war". This task takes three parameters:

  • destfile: this is the first attribute of the XML tag "war", used to specify what the war file name is and in which folder it will be output.
  • webxml: this is the second attribute of the XML tag "war", used to specify where to find the web.xml file, which is to be packaged as part of the war file.
  • classes: this is a sub XML tag under XML tag "war", it is used to specify the classes files to be included in the war file.
To run this target, all you need to do is use the following command in Command Prompt:
> ant packaging
The output of the command looks like the following:
Buildfile: build.xml

packaging:
      [war] Building war: %project_base_directry%\bin\greeting.war

BUILD SUCCESSFUL
Total time: 1 second
In the bin directory under project's base directory, you will find the newly created war file. Using a zip compression/decompression tool like 7-zip, you will be able to open this archive file and explore its inner structure. Inside, there are two directories, one is called "META-INF", which contains "MANIFEST.MF" file; the other one is called WEB-INF, inside, there is a subdirectory called "classes" and a file called "web.xml". The Greeting.class is under the subdirectory "tutorial/hanbo/webservices" in "classes".

Since the war file has been successfully built, it is time for deployment.

Deployment and Undeployment

Before attempting to deploy the sample war file into JBoss App Server, you must first start the JBoss App Server. Since we are just using JBoss as a mean to testing a simple web service, this tutorial will not discuss how to run JBoss was a service. Instead, we will open another Command Prompt, then start the JBoss App Server in this newly opened Command Prompt.

To start the JBoss App Server, use the newly opened Command Prompt to navigate to "C:\jboss-5.0.0.GA\bin", then run the start up script "run.bat". After JBoss App Server starts up, you have to wait for a while until the Command Prompt shows output like this:

15:34:41,889 INFO  [ServerImpl] JBoss (Microcontainer)
[5.0.0.GA (build: SVNTag=JBoss_5_0_0_GA date=200812041714)] Started in 5m:3s:150ms
The above output indicates JBoss App Server has been started successfully.

To shut down JBoss App Server, activate the Command Prompt that runs the JBoss App Server. Press Ctrl+C to halt the execution, then close the Command Prompt.

To deploy the war file, all you need to do is copying the war file (greeting.war), then paste it in "C:\jboss-5.0.0.GA\server\default\deploy". After taking this step, you will notice the Command Prompt in which the JBoss App Server is running will output the deployment progress like this:

15:35:21,422 INFO  [DefaultEndpointRegistry] register: jboss.ws:context=greeting,endpoint=GreetingWebService
15:35:22,453 INFO  [TomcatDeployment] deploy, ctxPath=/greeting, vfsUrl=greeting.war
15:35:28,172 INFO  [WSDLFilePublisher] WSDL published to:
file:/C:/jboss-5.0.0.GA/server/default/data/wsdl/greeting.war/GreetingService4604908665079984702.wsdl
The above output basically shows the deployment process is successful.

The next step is to test the deployment. Open a browser window, then navigate to "http://localhost:8080/jbossws/services". After the page loads up, you should be able to see section "Registered Service Endpoints" listing the detail info on the deployment of web service "GreetingWebService". Another test you can try is to see the WSDL file generated dynamically by JBossWS. For this tutorial, the link to the generated WSDL is "http://127.0.0.1:8080/greeting?wsdl". It can be viewed by using the same browser window.

Undeploy the web service can be done by simply deleting the war file (greeting.war) in "C:\jboss-5.0.0.GA\server\default\deploy". Once you've done that, the Command Prompt will show the progress of undeployment:

16:51:12,229 INFO  [TomcatDeployment] undeploy, ctxPath=/greeting, vfsUrl=greeting.war
16:51:13,307 INFO  [DefaultEndpointRegistry] remove: jboss.ws:context=greeting,endpoint=GreetingWebService
The above output basically shows the undeployment process is successful.

In build.xml, two targets are provided to deploy or undeploy the web service. They are simply using Apache Ant's copy file and delete file tasks to accomplish deploy and undeploy operations. To deploy web service, use target "deploy". To undeploy web service, use target "undeploy".

Test the Web Service using a Web Service Client

If you don't test the newly created web service, you won't be able to know whether or not it is working. Since in this tutorial, the web service is extremely simple, only exposing one web method that takes a string as parameter, testing it can be done via dynamic invocation. Dynamic invocation is, as many others has remarked, "a nasty way of creating a web service client". Most of the web services in the real world utilize complicated data objects and performs complex operations. Using dynamic invocation to create code to exercise such complex web services can be extremely difficult. It is better to create web service clients by using proxy classes generated by JBossWS from WSDL and associated XSD files.

The web service client is simply a console application written in Java. I have separated this test application into a different project, called "webservice-test". This project uses the same set of reference jars as the web service project. A build.xml is provided not only for building the project on command line, but also for running the test application. To build the project, use command "ant compile". After building the project, to the test application, use command "ant run-test-app". But, before running this test app, be sure to deploy the sample web service first.

Let's take a look at the source code of the test application. The two main sections of the source code are:

  • The import statements, used to import a number of classes used by the web service client.
  • The main method that contains the execution flow of the program.
The import statements look like this:
import javax.xml.rpc.Call;
import javax.xml.rpc.Service;
import javax.xml.rpc.ServiceFactory;
import javax.xml.rpc.ParameterMode;
import javax.xml.namespace.QName;
As the abover code shows, we only import the classes needed. The ServiceFactory class is used to create a Service object. The Service object is able to create a call object. Using the Call object, we can make a remote procedure call to the web method exposed by the web service. Because the web method takes a input parameter, we are going to need ParameterMode to specify how the parameter will be used. Since the generated WSDL also uses namespaces, we also need QName objects that represent qualified names.

The following code will invoke the sample web service:

public static void main(String[] argv)
{
   try
   {
      String NS_XSD
         = "http://www.w3.org/2001/XMLSchema";
      ServiceFactory factory
         = ServiceFactory.newInstance();
      Service service = factory.createService(
         new QName(
            "http://webservice.hanbo.tutorial/",
            "GreetingService"
         )
      );

      Call call = service.createCall(new QName(
         "http://webservice.hanbo.tutorial/",
         "GreetingPort"
      ));

      call.setTargetEndpointAddress(
         "http://localhost:8080/greeting?wsdl"
      );
      call.setOperationName(
         new QName(
            "http://webservice.hanbo.tutorial/",
            "greetClient"
         )
      );

      QName QNAME_TYPE_STRING = 
         new QName(NS_XSD, "string");
      call.setReturnType(QNAME_TYPE_STRING);

      call.addParameter(
         "arg0", QNAME_TYPE_STRING, 
         ParameterMode.IN
      );
      String[] params = { "Murphy Brown" };

      String result = (String)call.invoke(params);
      System.out.println(result);
   }
   catch (Exception e)
   {
      e.printStackTrace();
   }
}
This segment of code shows how dynamic invocation works. As you can see, it is fairly complicated. The logic is as following:
  1. First, a ServiceFactory object is created.
  2. Then call the ServiceFactory object's createService() to create a Service object. The pass-in parameter is a QName object.
    • The QName object represents the service named "GreetingService" with the namespace of "http://webservice.hanbo.tutorial/".
  3. Use the newly created Service object's createCall() method to create a Call object. The Call object represents the web service port.
  4. For the Call object, we need to:
    • Set the target end point address (setTargetEndPointAddress()). This is the URL to the dynamically generated WSDL.
    • Set the operation name (setOperationName()). This is the name of the web method we want to call.
    • Set the return value type (setReturnType()). In this case, the return is a standard string value.
    • Add the pass in parameters (addParameter()). In this case, the only pass in parameter is a string parmeter.
  5. After setting up the Call object, we can finally invoke the web method by calling invoke() method of the Call object. The parameter that passed into invoke() is an array of objects representing the input parameter of which the remote web method will use. In this case, there is only one parameter. It is a string "Murphy Brown".
If all goes well, the application can be run via Eclipse or Apache Ant in Command Prompt. If you choose to run it via Apache Ant, the command is:
> ant run-test-app
If everything goes well, the output would look like this:
> ant run-test-app
Buildfile: build.xml

run-test-app:
     [java] Greeting Murphy Brown! Have a nice day...

BUILD SUCCESSFUL
Total time: 8 seconds

Point of Interests

There you go. This is how a simplest web service is created, deployed, and tested. I know in its current form, the web service provides no use at all. I like to think this tutorial provides a skeleton of a web service. Any reader can use it as a start point; add more features, deploy and test; then add more feature, deploy and test again, until the final product can fulfill real users' needs.

I hope you enjoy this article as much as I enjoyed writing it.

History

  • 2/4/2009: Revision completed.
  • 2/3/2009: Begin revision.
  • 2/2/3009: Initial Draft was done.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Hanbo

United States United States
No Biography provided

Comments and Discussions

 
QuestionPerfect explanation PinmemberChanna Gayan27-Nov-13 0:32 
QuestionException when running client PinmemberMember 90537401-Jun-12 2:45 
GeneralThanks! PinmemberMember 883520417-Apr-12 9:15 
Questionhow is the targetNamespace="http://webservice.hanbo.tutorial in the wsdl file set? Pinmemberabhishek.gummadi28-Jul-11 14:19 
QuestionError while runing client to test deployed webservice -- BCIA PinmemberBCIA10-Jul-11 3:31 
GeneralNot Clear on How Client Should be deployed Pinmemberjanice18924-Apr-11 13:50 
GeneralRe: Not Clear on How Client Should be deployed PinmemberMember 78938214-May-11 9:20 
GeneralRe: Not Clear on How Client Should be deployed PinmemberSeeteshHindlekar2-May-12 3:13 
AnswerHints & Tips [modified] Pinmembermart201131-Oct-10 4:00 
GeneralRe: Hints & Tips Pinmemberjanice18924-Apr-11 14:14 
GeneralProvider com.sun.xml.rpc.client.ServiceFactoryImpl not found [modified] Pinmemberffruit17-Oct-10 6:04 
AnswerRe: Provider com.sun.xml.rpc.client.ServiceFactoryImpl not found Pinmembermart20116-Nov-10 23:21 
GeneralRe: Provider com.sun.xml.rpc.client.ServiceFactoryImpl not found Pinmemberroeeeli4-Apr-11 3:57 
GeneralRe: Provider com.sun.xml.rpc.client.ServiceFactoryImpl not found [modified] PinmemberSeeteshHindlekar2-May-12 3:15 
Generala new java pattern Pinmemberheartsofsea2-Jul-10 9:27 
QuestionImpossible to invoke webservice Pinmembergianluca.galantucci1-Apr-10 20:28 
AnswerRe: Impossible to invoke webservice [modified] Pinmembermart20117-Nov-10 0:33 
GeneralExample ran successfully Pinmemberjforpartha2-Mar-10 20:24 
Generaljava.lang.UnsupportedOperationException: setProperty must be overridden by all subclasses of SOAPMessage Pinmemberseeteshh27-Feb-10 6:30 
GeneralRe: java.lang.UnsupportedOperationException: setProperty must be overridden by all subclasses of SOAPMessage PinmemberDaniel Mij24-Mar-10 7:05 
Generaljboss PinmemberMember 377910017-Jan-10 23:33 
GeneralJBOSS PinmemberMember 377910017-Jan-10 23:32 
QuestionI managed to get the webservice to start properly but when I ran the test class it gave threw this exception please help. Pinmembersurawatthana21-Nov-09 21:49 
AnswerRe: I managed to get the webservice to start properly but when I ran the test class it gave threw this exception please help. Pinmemberseeteshh27-Feb-10 6:32 
GeneralRe: I managed to get the webservice to start properly but when I ran the test class it gave threw this exception please help. PinmemberASRATHORE20-Dec-12 22:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140814.1 | Last Updated 5 Feb 2009
Article Copyright 2009 by Hanbo
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid