Click here to Skip to main content
15,867,453 members
Articles / Desktop Programming / Swing

Create a Simple Web Service Using JBossWS

Rate me:
Please Sign up or sign in to vote.
4.67/5 (18 votes)
5 Feb 2009CPOL15 min read 294K   3.2K   46   43
An article on how to create a simple web service using JBossWS, how to deploy and test

Introduction

A while ago, 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 to 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 purposes, but also for 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 or comments, please leave a note in the comments section below.

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 advanced 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 relatively easy to be migrated to other platforms.

Install JDK and Apache Ant

Installing 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 follows:

  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 on 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 follows:

  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:

Java
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 import 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
<?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>) specifies what the servlet is. It has a name "GreetingWebService" and is 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.

The 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:

XML
<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 copy 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 detailed information 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 follows:

  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 parameter.
  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

License

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


Written By
Team Leader The Judge Group
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
AnswerRe: I managed to get the webservice to start properly but when I ran the test class it gave threw this exception please help. Pin
seeteshh27-Feb-10 6:32
seeteshh27-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. Pin
ASRATHORE20-Dec-12 22:14
ASRATHORE20-Dec-12 22:14 
GeneralRe: I managed to get the webservice to start properly but when I ran the test class it gave threw this exception please help. Pin
ASRATHORE31-Dec-12 1:23
ASRATHORE31-Dec-12 1:23 
GeneralRe: I managed to get the webservice to start properly but when I ran the test class it gave threw this exception please help. Pin
Tom Sarro31-Dec-12 20:13
Tom Sarro31-Dec-12 20:13 
GeneralDid not work with jboss-5.1.0.GA, jbossws-3.2.0.GA, java 1.6.0_16, but made it work a little bit different Pin
aorex29-Oct-09 0:17
aorex29-Oct-09 0:17 
GeneralRe: Did not work with jboss-5.1.0.GA, jbossws-3.2.0.GA, java 1.6.0_16, but made it work a little bit different Pin
mart20117-Nov-10 3:08
mart20117-Nov-10 3:08 
QuestionNeed Help on webservices Pin
narmas28-Oct-09 10:06
narmas28-Oct-09 10:06 
AnswerRe: Need Help on webservices Pin
narmas4-Nov-09 10:38
narmas4-Nov-09 10:38 
This is solved by exposing only one method as @WebMethod
Generalclient error Pin
sej6726-Oct-09 10:34
sej6726-Oct-09 10:34 
Generalant run-test-app Pin
joey joey26-Aug-09 19:49
joey joey26-Aug-09 19:49 
GeneralRe: ant run-test-app Pin
Member 654635010-Sep-09 11:16
Member 654635010-Sep-09 11:16 
GeneralException while running the client application - invocation failed Pin
smo_makabu28-May-09 16:42
smo_makabu28-May-09 16:42 
GeneralCan't get the client application to run Pin
aroc072515-May-09 7:52
aroc072515-May-09 7:52 
QuestionRe: Can't get the client application to run Pin
aroc072515-May-09 8:25
aroc072515-May-09 8:25 
AnswerRe: Can't get the client application to run Pin
marekskoczylas22-May-09 5:33
marekskoczylas22-May-09 5:33 
QuestionNo "Registered Service Endpoints" listed [modified] Pin
aroc072515-May-09 6:28
aroc072515-May-09 6:28 
QuestionError Starting JBoss after adding greeting.war Pin
prokosha7-Apr-09 23:54
prokosha7-Apr-09 23:54 
AnswerRe: Error Starting JBoss after adding greeting.war Pin
prokosha9-Apr-09 0:22
prokosha9-Apr-09 0:22 
GeneralError Pin
pramoda844-Mar-09 22:20
pramoda844-Mar-09 22:20 

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

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