SAX Servlet Example

Aim
Create a simple java SAX (Simple API for XML) servlet demonstrating all the basic fundamentals. This example servlet will accept some parameters and output some XML. This Can be used with the AJAX tutorial Ajax Example Using XMLHttpRequest and Callback. SAX maps element to objects well. If your data is structured in a way that makes it easy to create this mapping you should use SAX. If however, your data is much better represented as a tree then you should use DOM.

Assumptions
You have an application/web server and a compatible JDK installed.

Versions used in this example
Sofware/ComponentImage
Windows XP SP2N/A
tomcat 6N/A
JDK 1.5.0N/A
Links to these files can be found here.

This tutorial will follow the directory structure below. This is pretty much the standard webapps structure. The SAXHelloWorldServlet directory will be referred to as the project directory. This servlet accepts a parameter called 'name' and echoes it back with a greeting.

SAXHelloWorldServlet
_|_WEB-INF
_|__|__classes
_|__|__web.xml
_|_SAXServletDemo.java


Write and Compile Servlet
  1. Write the servlet,
     1. import java.io.*;
     2. 
     3. import javax.servlet.*;
     4. import javax.servlet.http.*;
     5. 
     6. import org.xml.sax.*;
     7. import org.xml.sax.helpers.*;
     8. import javax.xml.parsers.*;
     9. import javax.xml.transform.*;
    10. import javax.xml.transform.stream.*;
    11. import javax.xml.transform.sax.*;
    12. 
    13. public class SAXServletDemo extends HttpServlet {
    14.     
    15.     public void doGet(HttpServletRequest request, HttpServletResponse response){
    16.     try{
    17.         String name=request.getParameter("name");
    18.         String message="Hello there from the SAX servlet";
    19.         
    20.         response.setContentType("text/xml");
    21.         
    22.         SAXTransformerFactory tfactory= (SAXTransformerFactory)SAXTransformerFactory.newInstance();
    23.         TransformerHandler thandle   = tfactory.newTransformerHandler();
    24.         Transformer tformer          = thandle.getTransformer();
    25.         
    26.         thandle.setResult(new StreamResult(response.getWriter()));
    27.         tformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
    28.                 
    29.         thandle.startDocument();
    30.         AttributesImpl attribs = new AttributesImpl();
    31.         thandle.startElement("","","user-data",attribs);
    32.         
    33.         if(name!=null){
    34.             attribs.clear();
    35.             attribs.addAttribute("","","type","CDATA","Alias");
    36.             thandle.startElement("","","name",attribs);
    37.             thandle.characters(name.toCharArray(),0,name.length());
    38.             thandle.endElement("","","name");
    39.         }
    40.         
    41.            attribs.clear();
    42.         attribs.addAttribute("","","type","CDATA","greeting");
    43.         thandle.startElement("","","message",attribs);
    44.         thandle.characters(message.toCharArray(),0,message.length());
    45.         thandle.endElement("","","message");
    46.         
    47.         thandle.endElement("","","user-data");
    48.         thandle.endDocument();
    49.         
    50.     }catch(Exception e){
    51.         e.printStackTrace();
    52.     }
    53. 
    54.     }
    55. }
    Hide line numbers
  2. `
  3. Compile the code, setting your tomcat's lib dir as an ecternal directory to pickup the servlet api,

    ..workspace\SAXHelloWorldServlet>javac -d WEB-INF\classes -extdirs D:\apache-tomcat-6.0.18\lib *.java
  4. `
  5. Create the web.xml file as show below in the WEB-INF directory
     1. <?xml version="1.0" encoding="UTF-8"?>
     2. <web-app>
     3. 
     4.     <display-name>SAX XML Output</display-name>
     5. 
     6.     <servlet>
     7.         <servlet-name>SAX XML</servlet-name>
     8.         <servlet-class>SAXServletDemo</servlet-class>
     9.     </servlet>
    10. 
    11.     <servlet-mapping>
    12.         <servlet-name>SAX XML</servlet-name>
    13.         <url-pattern>/saxxmldemo.xml</url-pattern>
    14.     </servlet-mapping>
    15. 
    16.     <welcome-file-list>
    17.         <welcome-file>index.html</welcome-file>
    18.     </welcome-file-list>
    19. </web-app>
    Hide line numbers
  6. `
  7. Copy the directory to the webapps directory in tomcat or create a war file and deploy it in an application server such as glassfish.

Testing
  1. Open up a browser ant type in http://127.0.0.1:8080/SAXJHelloWorldServlet/saxxmldemo.xml?name=spiderman
    You should see the XML below,
     1. <?xml version="1.0" encoding="UTF-8"?>
     2. <user-data> 
     3.    <name type="Alias">spiderman</name>
     4.    <message type="greeting">Hello there from the SAX servlet</message>
     5. </user-data> 
    Hide line numbers

Back to the tutorial trail | Home

AJAX Example Using XMLHttpRequest and a Callback

Aim
To introduce AJAX in a quick and painless way. We will use a static xml page to simulate a result from the server. Or you can use SAX Servlet example which is tailor made for this ajax example (AJAX = Asynchronous Javascript And XML).

Assumptions
You alread have a webserver installed. If you want to use the SAX Servlet as the backend for this tutorial then you need to have it compiled and deployed.

A big part of WEB 2 is of course AJAX which is asynchronous javascript and xml. We will breakdown an AJAX request down. A complete list of the code is available at the end of this page.

When you load the page the first thing that happens is the creation of an XMLHttpRequest object to handle the xml functions.
1.  <html>
2.  <head>
3.  <script langua="javascript">
4.  function new_XHR() {
5.      var xhr;
6.      try{
7.          xhr = new ActiveXObject("Msxml2.XMLHTTP");
8.      }catch(e){
9.      try{
10.          xhr = new ActiveXObject("Microsoft.XMLHTTP");
11.          }catch(E){
12.              xhr = false;
13.          }
14.      }
15.      if(!xhr && typeof XMLHttpRequest != 'undefined'){
16.          xhr = new XMLHttpRequest();
17.      }
18.      return xhr;
19.  }
...
What we are trying to do here, is instantiate an XMLHttpRequest object. As you can see I have not bothered to handle the error if the browser cannot instantiate an object.


Now lets have a look at the actual HTML
...
49.  <body>
50.  <form>
51.  Name <input id="NameBox" type="text"/>
52.  <a href="javascript:DoCallback()">Send the data without submitting the form</a>
53.  </form>
54.  <div id="MessagePane"/>
55.  </body>
56.  </html>
57.  
This shows a textbox and a URL. When you click on the URL it calls the javascript DoCallback function.

The XMLHTTP request
...
20.  
21.  var myxhr;
22.  function DoCallback(){
23.        myxhr = new_XHR();
24.        myxhr.onreadystatechange=MyCallback;
25.        myxhr.open('GET',"saxxmldemo_static.xml?"
26.          +"name="+document.getElementById("NameBox").value);
27.        myxhr.send(null);
28.      }
29.
...
This sets the callback function onreadystatechange=MyCallback. As you can see this is adding the value in the textbox to the URL. This really doesn't matter if you are using the saxxmldemo_static.xml as this is a static xml file. If you want to use the SAX Servlet example replace line 25 with
myxhr.open('GET', 'http://127.0.0.1:8080/SAXJHelloWorldServlet/saxxmldemo.xml?
This will point to the SAX Servlet which will echo the 'name'. Make sure you have the SAX Servlet example deployed and ready to go.

The Callback
...
29.         
30.  function MyCallback(){
31.      var name;
32.      var message;
33.      if(myxhr.readyState==4 && myxhr.status==200){
34.          var subrootNode = myxhr.responseXML.getElementsByTagName('user-data');
35.          for(i = 0 ; i < subrootNode[0].childNodes.length ; i++){
36.              var node = subrootNode[0].childNodes[i];
37.              if(node.tagName=="name")
38.                  name=node.firstChild.nodeValue;
39.              else if(node.tagName=="message")
40.                  message=node.firstChild.nodeValue;
41.              else{}
42.          }
43.          document.getElementById("MessagePane").innerHTML = "Hey "+name+" the server says \""+message+"\""; 
44.      }
45.  }
...
This is the function that gets called when the XMLHttpRequest object changes state i.e receives a response. As you can see on line 33, we are only interested in readyState=4 (document has loaded) and status 200 which means successful. You should have more error handling code here. You can use childNodes to drill down and extract the information or you can use getElementsByTagName(). The message is written to the html div  with the id 'MessagePane' using innerHTML.

childNodes[n]
_|_childNodes[0] (.firstChild)
_|_childNodes[1]
_|__|_childNodes[0] (.firstChild)
_|__|_childNodes[1]
_|_childNodes[2]


The xmldemo_static.xml
 1. <?xml version="1.0" encoding="UTF-8"?>
 2. <user-data>
 3.     <name type="Alias">Doctor Octopus</name>
 4.     <message type="greeting">Hello there from the SAX servlet</message>
 5. </user-data>
Hide line numbers


Entire listing of index.html
 1. <html>
 2. <head>
 3. <script langua="javascript">
 4. function new_XHR() {
 5.     var xhr;
 6.     try{
 7.         xhr = new ActiveXObject("Msxml2.XMLHTTP");
 8.     }catch(e){
 9.     try{
10.         xhr = new ActiveXObject("Microsoft.XMLHTTP");
11.         }catch(E){
12.             xhr = false;
13.         }
14.     }
15.     if(!xhr && typeof XMLHttpRequest != 'undefined'){
16.         xhr = new XMLHttpRequest();
17.     }
18.     return xhr;
19. }
20. 
21. var myxhr;
22. function DoCallback(){
23.       myxhr = new_XHR();
24.       myxhr.onreadystatechange=MyCallback;
25.       myxhr.open('GET',"http://127.0.0.1:8080/SAXJHelloWorldServlet/saxxmldemo.xml?"
26.         +"name="+document.getElementById("NameBox").value);
27.       myxhr.send(null);
28.     }
29.        
30. function MyCallback(){
31.     var name;
32.     var message;
33.     if(myxhr.readyState==4 && myxhr.status==200){
34.         var subrootNode = myxhr.responseXML.getElementsByTagName('user-data');
35.         for(i = 0 ; i < subrootNode[0].childNodes.length ; i++){
36.             var node = subrootNode[0].childNodes[i];
37.             if(node.tagName=="name")
38.                 name=node.firstChild.nodeValue;
39.             else if(node.tagName=="message")
40.                 message=node.firstChild.nodeValue;
41.             else{}
42.         }
43.         document.getElementById("MessagePane").innerHTML = 
44.                                     "Hey "+name+" the server says \""+message+"\""; 
45.     }
46. }
47. 
48. </script>
49. </head>
50. <body>
51. <form>
52. Name <input id="NameBox" type="text"/>
53. <a href="javascript:DoCallback()">Send the data without submitting the form</a>
54. </form>
55. <div id="MessagePane"/>
56. </body>
57. </html>
Hide line numbers
Back to the tutorial trail | Home

Tutorial Trail - List of all the Examples Tutorials and Helloworlds

Every C++, Java, PHP, perl, Javascript tutorial and example is listed here. Clean, simple and concise. C++ and Java tutorials based on application and technologies. This is frequently updated as tutorials are added.


Core Tutorial Trail
Core C++ and Java tutorials such as sockets, threads, servlets and general programming examples.


Application Tutorial Trail
Application tutorials such as javaEE technologies, web services, Database connection pools on glassfish and tomcat.


Scripting and Web2 Tutorial Trail
Web related tutorials on Javascript, Perl and PHP. Learn how to create exciting widgets using technologies such as AJAX and DOM. Blog configuration and tips.

Installing and Setting Up Glassfish 2

Aim
To install and setup a domain in the Glassfish 2 application server. We can then use this Glassfish server for various java tutorials such as web-services, EJBs and JMS. This covers basic setup and configuration of Glassfish 2. Leave any questions or problems as comments and I will endeavour to answer them.

Assumptions
We assume that the jdk 1.5.0 or compatible version and Ant are already installed.

Versions used in this example
Software ComponentImage
Glassfish 2glassfish-installer-v2.1-b60e-windows.jar
Ant 1.7 apache-ant-1.7.1-bin.zip
JDK 1.5.0N/A
Links to these files can be found here

Install/unzip
  1. Download the image/binary and save it to the directory where you wish to install glassfish. Example C:\Program Files\.
  2. `
  3. Now open a command prompt and cd into the directory where you saved the file.
  4. `
  5. Run java -jar to unpack the file. This will create a directory called glassfish.

    C:\Program Files>java -jar glassfish-installer-v2.1-b60e-windows.jar
    This will popup a window with the license agreement. Scroll to the end and press Agree. You should see your prompt fill up with files being unpacked.
  6. `
  7. Now cd into the glassfish directory that the previous command created.
  8. `
  9. Run ant on the setup.xml file. I don't have ant in my path so I'm specifying the full path to my ant executable.

    C:\Program Files\glassfish>D:\downloads\apache-ant-1.7.1\bin\ant -f setup.xml
  10. `
  11. Create a directory called domains under the glassfish directory.
  12. `
  13. Now cd into the glassfish\asadmin\bin directory,
  14. `
  15. Run the asadmin create-domain command to create a domain for our applications. I have chosen port 8082 because on conflichs with apache's web-server and tomcat. You can put in whatever you like. This will create a domain1 directory under the domains directory.

    ...glassfish\bin>asadmin create-domain --adminuser admin --adminport 4848 --instanceport 8082 domain1
    Remember the passwords you typed for admin and master password. The name of this domain will be domain1.
  16. Cd into the domain1\bin directory and run startserver.bat. For admin username type admin and type the passwords you entered when you created the domain.
  17. `
  18. Check the logfiles at domain1\logs to make sure everything looks ok.
  19. `
  20. Open a browser and go to http://127.0.0.1:8082. You should see a welcome page.
  21. `
  22. In the browser type http://127.0.0.1:4848 and login using admin and the password you created. You are now done.

Back to the tutorial trail | Home.

Web Services Example Using Glassfish 2

Aim
The aim of this java web-service tutorial is to write a simple 'Hello World' web service and client in Java. This tutorial will be using the jax-rpc framework in the Glassfish 2 application server. We will create a web-serive and deploy it in Glassfish. Then we will connect to it using a java client. The files and structures are exactly the same as the JWSDP 2 tutorial. In fact you could deploy the war file from that tutorial in Glassfish and it would work fine. Leave any questions or problems as comments and I will endeavour to answer them.

Assumptions
This article assumes that you have Galssfish 2 installed and a domain configured. Please see Installing and Setting up Glassfish 2 for more details. For purposes of this example the glassfish domain is running on port 8082 and the project directory is GlassfishWSHelloWorld.

Versions used in this example
Sofware/Component
Image
Windows XP SP2
N/A
Glassfish 2
glassfish-installer-v2.1-b60e-windows.jar
Java JDK 1.5.0
N/A
Links to these files can be found here

Although this is a quick 'helloworld' tutorial we will not sacrifice neatness for speed - so all the source files, class files etc will be kept in separate directories and as clean as possible. You will thank me for this later.

Create this directory structure in your working directory- similar to something you would get from eclipse. The structure used in this example is given below. GlassfishWSHelloworld will be referred to as your project or working directory. Create this structure.

GlassfishWSHelloWorld
_|_client_bin
_|_client_src
_|__|_config.xml
_|___GlassfishWSHelloWorldClient.java
_|_web_bin
_|__|_WEB-INF
_|_____|_classes
_|_____|_jaxrpc-ri.xml
_|_____|_web.xml
_|_web_src
_.__|_HelloWorldServiceImplementation.java
_.__|_HelloWorldServiceInterfacejava

The Glassfish app server is installed in the D:\downloads\glassfish directory for this tutorial.

Compiling the webservice code
  1. Write the code
    We don't really need an interface for this example, but I have added one for completeness, because we will use these exact same files for the JWSDP example. In this tutorial the HelloCallEcho function will be exposed.
     1. package helloworld;
     2. 
     3. import java.rmi.RemoteException;
     4. 
     5. public interface HelloWorldServiceInterface extends java.rmi.Remote{
     6.     public String HelloCallEcho(String hellostring)throws java.rmi.RemoteException;
     7.     public int HelloCallAdd(int helloNumber1, int helloNumber2)throws java.rmi.RemoteException;
     8. }
    Hide line numbers
    Save this as HellowWorldServiceInterface.java in your web_src directory.

    Next, create the implementation
     1. package helloworld;
     2. 
     3. public class HelloWorldServiceImplementation implements HelloWorldServiceInterface{
     4. 
     5.     public String HelloCallEcho(String hellostring) {
     6.         return "Web service echoing back - "+hellostring;
     7.     }
     8.     
     9.     public int HelloCallAdd(int helloNumber1, int helloNumber2) {
    10.         return helloNumber1 + helloNumber2;
    11.     }
    12. }
    Hide line numbers
    Save this as HelloWorldServiceImplementation.java under in your web_src directory
  2. `
  3. Now compile the code.

    ..workspace\GlassfishWSHelloWorld>javac -d web_bin\WEB-INF\classes web_src\*.java

  4. `
  5. Open a command prompt and cd into your project directory (GlassfishWSeHelloWorld in this example).Your web_bin directory should have some class file in there.
  6. `
  7. Create the jaxrpc-ri.xml file in the web_bin\META-INF directory.
     1. <?xml version="1.0" encoding="UTF-8"?>
     2. <webServices xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/dd"
     3.     version="1.0"
     4.     targetNamespaceBase="http://hello.org/wsdl"
     5.     typeNamespaceBase="http://hello.org/types"
     6.     urlPatternBase="/ws">
     7. 
     8.     <endpoint name="JWSDPGlassHelloWorld" 
     9.         displayName="Hello World from JWSDP 2" 
    10.         description="This is a Hello World Echo service"
    11.         wsdl="/WEB-INF/JWSDPGlassHelloWorld.wsdl"
    12.         interface="helloworld.HelloWorldServiceInterface"
    13.         implementation="helloworld.HelloWorldServiceImplementation"/>
    14. 
    15.     <endpointMapping
    16.         endpointName="JWSDPGlassHelloWorld"
    17.         urlPattern="/hello"/>
    18.     
    19. </webServices>
    Hide line numbers

  8. `
  9. Create the web.xml file in the same WEB-INF directory.
     1. <?xml version="1.0" encoding="UTF-8"?>
     2. <web-app>
     3.     <display-name>Hello Service</display-name>
     4.     <description>
     5.         Returns a String saying Hello
     6.     </description>
     7. 
     8.     <session-config>
     9.         <session-timeout>60</session-timeout>
    10.     </session-config>
    11.     
    12. </web-app>
    Hide line numbers

  10. `
  11. Cd into web_bin directory and jar it all up using,

    ..workspace\GlassfishWSHelloWorld\web_bin>jar -cvf HelloWorldServices.jar *

  12. `
  13. Now use the wsdeploy tool to create the war file that will be deployed to tomcat
    ..workspace\GlassfishWSHelloWorld\web_bin>d:\downloads\glassfish\bin\wsdeploy.bat -o GlassfishWSHelloWorld.war HelloWorldServices.jar


Deploying the Service
  1. Open up your broswer and go to the Glassfish admin console. This is http://127.0.0.1:4848 for this tutorial. See Installing and Setting up Glassfish 2 for more details.
  2. `
  3. Login as admin to the console.
  4. `
  5. Deploy the GlassfishWSHelloWorld.war application under applications -> web applications -> deploy.
  6. `
  7. Now navigate to 'http://127.0.0.1:8082/GlassfishWSHelloWorld/hello.' You should see a table with some links. Click on the WSLD link to have a look at the WSDL.

Generating the stub code - required for the client.
  1. Create the config.xml file in your client_src directory. Wscompile will use this to find the wsdl to create the stubs,
     1. <?xml version="1.0" encoding="UTF-8"?>
     2. <configuration
     3.     xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
     4.     <wsdl
     5.         location="http://127.0.0.1:8082/GlassfishWSHelloWorld/hello?WSDL"
     6.         packageName="helloworld">
     7.     </wsdl>
     8. </configuration>
    Hide line numbers

  2. `
  3. Open a prompt and cd to your working directory.
  4. `
  5. Generate the client stub by running wscompile.bat. This should be in your jwsdp install directory under 'jaxrpc\bin.' We use -s option to install all the stub code in the client_src directory.
    workspace\GlassfishWSHelloWorld>D:\downloads\glassfish\bin\wscompile.bat -gen -keep -d client_bin -s client_src client_src\config.xml


Compiling the client
  1. Write the actual client code and save this as GlassfishWSHelloWorldClient.java under the client_src directory.
     1. import helloworld.*;
     2. 
     3. public class GlassfishWSHelloWorldClient
     4. {
     5.     public static void main (String args[])
     6.         throws Exception
     7.     {
     8.         JWSDPGlassHelloWorld_Impl service =  new JWSDPGlassHelloWorld_Impl();
     9.         HelloWorldServiceInterface stub = service.getHelloWorldServiceInterfacePort();
    10.         String response = stub.helloCallEcho("client says hello JWSDP");
    11.         System.out.println ( response );
    12.     }
    13. }
    Hide line numbers

  2. `
  3. Now compile it using

    ..workspace\GlassfishWSHelloWorld\client_src>javac -d ..\client_bin -Djava.ext.dirs=D:\downloads\glassfish\lib GlassfishW
    SHelloWorldClient.java
    This should place all the files into the 'client_bin' directory

Running the application
  1. CD into client_bin and run the client using the command below,
    ..workspace\GlassfishWSHelloWorld\client_bin>java -Djava.ext.dirs=D:\downloads\glassfish\lib GlassfishWSHelloWorldClient
    You should see a printout saying 'hello back' from the web service.

Looking at the soap messages using tcpmon
The way the monitor works is like a proxy. Your client connects to the monitor and the monitor connects to the web-service. Remember that Glassfish is running on port 8082
  1. Go back and edit the HelloworldServiceInterface_Stub.java. This is one of the files generated by wscompile and should be under the client_src\helloworld directory. Around line 40. Change the port to 8083 and save.
    original
    public HelloWorldServiceInterface_Stub(HandlerChain handlerChain) {
    super(handlerChain);
    _setProperty(ENDPOINT_ADDRESS_PROPERTY, "http://127.0.0.1:8082/GlassfishWSHelloWorld/hello");
    modified
    public HelloWorldServiceInterface_Stub(HandlerChain handlerChain) {
    super(handlerChain);
    _setProperty(ENDPOINT_ADDRESS_PROPERTY, "http://127.0.0.1:8083/GlassfishWSHelloWorld/hello");

  2. `
  3. Compile the client code as explained previously.
  4. `
  5. Open up another seprate command prompt and start up tcpmon.

    ...\anywhere>java -cp D:\downloads\axis-bin-1_4\axis-1_4\lib\axis.jar org.apache.axis.utils.tcpmon
    Please refer to the final section in the Setting up Axis2 on Tomcat for more details on this step and why we are using the axis.jar core from Axis 1. This should startup tcpmon.
  6. `
  7. In the tcpmon gui change the target port from 8080 to 8082, in the listen port type in 8083 and press add.
  8. `
  9. Go to the 8083 tab at the top.
  10. `
  11. Now open up a command prompt and run the recompiled client as explained in the previous section- You should see SOAP messages sent back and forth.

Back to the tutorial trail | Home.

Mega Software Download Page

All the software for the tutorials on this site are given below. Happy downloading! Please leave a comment to report broken links.

Ant
apache-ant-1.7.1-bin.zip

Axis2

axis2-1.4.1-bin.zip
axis2-1.4.1-war.zip
axis-bin-1_4.zip

Eclipse
eclipse-java-ganymede-win32.zip

GlassFish V2
glassfish-installer-v2.1-b60e-windows.jar

JDK


JMS
openjms-0.7.7-beta-1.zip
Sun MQ 4.3 mq4_3-installer-WINNT.zip (contains JMS C-API)

JWSDP 2
jwsdp-2_0-windows-i586.exe

MySQL
Connector J mysql-connector-java-5.1.7.tar.gz
Connector C++ mysql-connector-c++-noinstall-1.0.5-win32.zip

Oracle
Client 10201_client_win32.zip

Perl
ActivePerl-5.10.1.1006-MSWin32-x86-291086.msi

Php +Components
PhpMailer



Struts 2
struts-2.1.6-all.zip

Tomcat
apache-tomcat-6.0.18.zip

Visual Studio Express Editions 2008
VC++, VC#, VB and SQLServer


Some tools developed in http and javascript
Cool Tools Page

Web Services Example Using JWSDP 2 and Tomcat

Aim
The aim of this tutorial is to write a simple 'Hello World' web service and client in Java. This example will be using the JWSDP2 framework on Tomcat. We will create a web service, deploy it to the JWSDP2 framework in Tomcat and then write a java client to connect to the web-service. Leave any questions or problems as comments and I will endeavour to answer them. See Web Services Example Using Axis2 and Tomcat for an alternative to JWSDP.

Assumptions
This article assumes that you have the JWSDP 2 installed and configured on Tomcat. Please see Setting up JWSDP2 on Tomcat for more details. For purposes of this example Tomcat is running on port 8080 and the project directory is JWSDP2TomcatHelloWorld.

Versions used in this example
Sofware/ComponentImage
Windows XP SP2N/A
JWSDP 2jwsdp-2_0-windows-i586.exe
tomcat 6apache-tomcat-6.0.18.zip
Java JDK 1.5.0N/A
Links to these files can be found here

Although this is a quick 'helloworld' tutorial we will not sacrifice neatness for speed - so all the source files, class files etc will be kept in separate directories and as clean as possible. You will thank me for this later.

Create this directory structure in your working directory- similar to something you would get from eclipse. The structure used in this example is given below. The JWSDP2TomcatHelloWorld will be referred to as your project or working directory. Create this structure.

JWSDP2TomcatHelloWorld
_|_client_bin
_|_client_src
_|__|_config.xml
_|___JWSDP2TomcatHelloWorldClient.java
_|_web_bin
_|__|_WEB-INF
_|_____|_classes
_|__.__.__|_jaxrpc-ri.xml
_|__.__.__|_web.xml
_|_web_src
_.__|_HelloWorldServiceImplementation.java
_.__|_HelloWorldServiceInterfacejava

The JWSDP2 in installed in the C:\Sun\jwsdp-2.0 directory for this tutorial.

Compiling the webservice code
  1. We don't really need an interface for this example, but I have added one for completeness, because we will use these exact same files for the JWSDP example. In this tutorial we will expose the HelloCallEcho function
     1. package helloworld;
     2. 
     3. import java.rmi.RemoteException;
     4. 
     5. public interface HelloWorldServiceInterface extends java.rmi.Remote{
     6.     public String HelloCallEcho(String hellostring)throws java.rmi.RemoteException;
     7.     public int HelloCallAdd(int helloNumber1, int helloNumber2)throws java.rmi.RemoteException;
     8. }
    Hide line numbers
    Save this as HellowWorldServiceInterface.java in your web_src directory.

    Next create the implementaion
     1. package helloworld;
     2. 
     3. public class HelloWorldServiceImplementation implements HelloWorldServiceInterface{
     4. 
     5.     public String HelloCallEcho(String hellostring) {
     6.         return "Web service echoing back - "+hellostring;
     7.     }
     8.     
     9.     public int HelloCallAdd(int helloNumber1, int helloNumber2) {
    10.         return helloNumber1 + helloNumber2;
    11.     }
    12. }
    Hide line numbers
    Save this as HelloWorldServiceImplementation.java under in your web_src directory

  2. Open a command prompt and cd into your project directory (JWSDP2TomcateHelloWorld in this example).

  3. Compile the code

    ..workspace\JWSDP2TomcatHelloWorld>javac -d web_bin\WEB-INF\classes web_src\helloworld\*.java

  4. Your web_bin directory should have some class file in there.
  5. Create the jaxrpc-ri.xml file in the web_bin\META-INF directory.
     1. <?xml version="1.0" encoding="UTF-8"?>
     2. <webServices xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/dd"
     3.     version="1.0"
     4.     targetNamespaceBase="http://mysite.org/wsdl"
     5.     typeNamespaceBase="http://mysite.org/types"
     6.     urlPatternBase="/Hello">
     7. 
     8.     <endpoint name="JWSDPTomHelloWorld" 
     9.         displayName="Hello World from JWSDP 2" 
    10.         description="This is a Hello World Echo service"
    11.         wsdl="/WEB-INF/JWSDPTomHelloWorld.wsdl"
    12.         interface="helloworld.HelloWorldServiceInterface"
    13.         implementation="helloworld.HelloWorldServiceImplementation"/>
    14. 
    15.     <endpointMapping
    16.         endpointName="JWSDPTomHelloWorld"
    17.         urlPattern="/hello"/>
    18.     
    19. </webServices>
    Hide line numbers

  6. Create the web.xml file in the same WEB-INF directory.
     1. <?xml version="1.0" encoding="UTF-8"?>
     2. <web-app>
     3.     <display-name>Hello Service</display-name>
     4.     <description>
     5.         Returns a String saying Hello
     6.     </description>
     7. 
     8.     <session-config>
     9.         <session-timeout>60</session-timeout>
    10.     </session-config>
    11.     
    12. </web-app>
    Hide line numbers

  7. Cd into web_bin directory and jar it all up using,

    ..workspace\JWSDP2TomcatHelloWorld\web_bin>jar -cvf HelloWorldServices.jar *

  8. Now use the wsdeploy tool to create the war file that will be deployed to tomcat
    ..workspace\JWSDP2TomcatHelloWorld\web_bin>c:\Sun\jwsdp-2.0\jaxrpc\bin\wsdeploy.bat -o JWSDP2TomcatHelloWorld.war HelloWorldServices.jar

Deploying the Service
  1. Copy the jwsdp2tomcathelloworld.war file to your tomcat webapps directory. After a few seconds tomcat would have extracted the directory.

  2. Open a browser and navigate to 'http://127.0.0.1:8080/JWSDP2TomcatHelloWorld/hello.' You should see a table with some links. Click on the WSLD link to have a look at the WSDL.

Generating the stub code - required for the client.
  1. Create the config.xml file in your client_src directory. Wscompile will use this to find the wsdl to create the stubs,
     1. <?xml version="1.0" encoding="UTF-8"?>
     2. <configuration
     3.     xmlns="http://java.sun.com/xml/ns/jax-rpc/ri/config">
     4.     <wsdl
     5.         location="http://127.0.0.1:8080/JWSDP2TomcatHelloWorld/hello?WSDL"
     6.         packageName="helloworld">
     7.     </wsdl>
     8. </configuration>
    Hide line numbers

  2. Open a prompt and cd to your working directory.

  3. Generate the client stub by running wscompile.bat. This should be in your jwsdp install directory under 'jaxrpc/bin.' We use the -s to specify that all the stubs be installed in the client_src directory.
    workspace\JWSDP2TomcatHelloWorld>C:\Sun\jwsdp-2.0/jaxrpc/bin/wscompile.bat -gen -keep -d client_bin -s client_src client_src/config.xml

Compiling the client
  1. Write the actual client code,
     1. public class JWSDP2TomcatHelloWorldClient
     2. {
     3.     public static void main (String args[])
     4.         throws Exception
     5.     {
     6.         JWSDPTomHelloWorld_Impl service =  new JWSDPTomHelloWorld_Impl();
     7.         HelloWorldServiceInterface stub = service.getHelloWorldServiceInterfacePort();
     8.         String response = stub.helloCallEcho("client says hello JWSDP");
     9.         System.out.println ( response );
    10.     }
    11. }  
    Hide line numbers
    Save this as JWSDP2TomcatHelloWorldClient.java in the client_src directory.

  2. Open a prompt to the project directory and compile it using extdirs to point to the jar files in your environment.
    ..workspace\JWSDP2TomcatHelloWorld>javac -cp client_src -d client_bin -extdirs C:\Sun\jwsdp-2.0\saaj\lib;C:\Sun\jwsdp-2.0\jaxrpc\lib;C:\Sun\jwsdp-2.0\jwsdp-shared\lib client_src\JWSDP2TomcatHelloWorldClient.java
    This should place all the files into the 'client_bin' directory

Running the application
  1. CD into client_bin and run the client using the command below.
    ..workspace\JWSDP2TomcatHelloWorld\client_bin>java -Djava.ext.dirs=C:\Sun\jwsdp-2.0\saaj\lib;C:\Sun\jwsdp-2.0\jaxrpc\lib;C:\Sun\jwsdp-2.0\fastinfoset\lib;C:\Sun\jwsdp-2.0\jwsdp-shared\lib;C:\Sun\jwsdp-2.0\jaxb\lib;C:\Sun\jwsdp-2.0\sjsxp\lib JWSDP2TomcatHelloWorldClient
    You should see a printout saying 'hello back' from the web service.

  2. If you are getting errors have a look a the launcher.server.log in the tomcat log directory. You might see ClassNotFound Errors. Make sure the required jars are copied into your tomcat lib directory. MultipartMime errors need the mail.jar. See Setting up JWSDP2 with Tomcat 6 for more details.

Looking at the soap messages using tcpmon
The way the monitor works is like a proxy. Your client connects to the monitor and the monitor connects to the web-service. Remember that Tomcat is running of port 8080.
  1. Go back and edit the HelloworldServiceInterface_Stub.java. This is one of the files generated by wscompile and should be under the client_src\helloworld directory. Around line 40. Change the port to 8081 and save.
    originalpublic HelloWorldServiceInterface_Stub(HandlerChain handlerChain) {
    super(handlerChain);
    _setProperty(ENDPOINT_ADDRESS_PROPERTY, "http://127.0.0.1:8080/JWSDP2TomcatHelloWorld/hello");
    modifiedpublic HelloWorldServiceInterface_Stub(HandlerChain handlerChain) {
    super(handlerChain);
    _setProperty(ENDPOINT_ADDRESS_PROPERTY, "http://127.0.0.1:8081/JWSDP2TomcatHelloWorld/hello");

  2. Compile the client code as explained previously.
  3. Open up another seprate command prompt and start up tcpmon.

    ...\anywhere>java -cp D:\downloads\axis-bin-1_4\axis-1_4\lib\axis.jar org.apache.axis.utils.tcpmon
    Please refer to the final section in the Setting up Axis2 on Tomcat for more details on this step and why we are using the axis.jar core from Axis 1. This should startup tcpmon.

  4. In the tcpmon gui, in the listen port type in 8081 and press add.

  5. Go to the 8081 tab at the top.

  6. Now open up a command prompt and run the recompiled client as explained in the previous section- You should see SOAP messages sent back and forth.