scott nichol
Home >> Soap >> Servlet Client for Apache SOAP
Servlet Client for Apache SOAP

The Apache SOAP distribution includes a number of sample applications. These generally consist of a Java class that implements the SOAP service and one or more Java classes that are clients to the service. These classes implement console applications. That is mostly fine for demonstrating basic coding and confirming proper operation, but does not reflect the variety of clients that is required in the real world. For example, it is common to want to integrate the results of one or more SOAP calls into a page to be displayed by a browser.

This document provides an example of a servlet that acts as a SOAP client to the stockquote sample provided with Apache SOAP. In response to an HTTP GET request, the servlet provides an HTML page containing a form that allows the user to specify a stock ticker symbol (e.g. IBM) and the endpoint URL for the stockquote service (e.g. http://localhost:8080/soap/servlet/rpcrouter). When the form is POSTed, the servlet uses this data to create and invoke the call to the stockquote service, then provides an HTML page containing the result from the service.

The examples and descriptions below assume that Apache SOAP has been installed according to these instructions. To the extent the environment in which you work differs from the one described by those instructions, you will need to mentally adjust the text below. Also, the stockquote sample service must be deployed and tested, such as by executing the commands below.

j:
cd \soap-2_2\samples\stockquote
java org.apache.soap.server.ServiceManagerClient
     http://localhost:8080/soap/servlet/rpcrouter
     deploy DeploymentDescriptor.xml
java samples.stockquote.GetQuote
     http://localhost:8080/soap/servlet/rpcrouter IBM
Writing the servlet code
Deploying the servlet server
Resources

Writing the Servlet Code

The code implements a simple servlet that happens to make a SOAP call as part of its processing in the doPost method.

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URL;
import java.util.Vector;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.soap.*;
import org.apache.soap.rpc.*;

public class GetQuote extends HttpServlet {
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
             throws ServletException, IOException {
    // Send the response
    resp.setContentType("text/html; charset=iso-8859-1");
    Writer w = resp.getWriter();
    PrintWriter pw = new PrintWriter(w);
    pw.println("<html><head><title>Get Quote</title></head><body>");
    pw.println("<form method=\"POST\" action=\"" +
                                  req.getContextPath() + req.getServletPath() + "\">");
    pw.println("Symbol: <input type=\"text\" name=\"symbol\" value=\"\"><br>");
    pw.println("URL: <input type=\"text\" name=\"endpointURL\" value=\"\"><br>");
    pw.println("<input type=\"submit\" value=\" Get \"><br>");
    pw.println("</form></body></html>");
    pw.flush();
    pw.close();
    w.flush();
    w.close();
  }

  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
             throws ServletException, IOException {
    // Read form variables.
    String url = req.getParameter("endpointURL");
    if (url == null || url.length() == 0)
      url = getServletConfig().getInitParameter("defaultEndpointURL");
    URL endpointURL = new URL(url);
    String symbol = req.getParameter("symbol");
  
    // Initialize pseudo-constants
    String encodingStyleURI = Constants.NS_URI_SOAP_ENC;
    String soapAction = "";
  
    // Create call
    Call call = new Call();
    call.setTargetObjectURI("urn:xmltoday-delayed-quotes");
    call.setMethodName("getQuote");
    call.setEncodingStyleURI(encodingStyleURI);
    Vector params = new Vector();
    params.addElement(new Parameter("symbol", String.class, symbol, null));
    call.setParams(params);
  
    // Send the start of the response
    resp.setContentType("text/html; charset=iso-8859-1");
    Writer w = resp.getWriter();
    PrintWriter pw = new PrintWriter(w);
    pw.println("<html><head><title>Quote</title></head><body><p>");

    // Invoke SOAP method
    try {
      Response response = call.invoke(endpointURL, soapAction);
    
      if (response.generatedFault()) {
        Fault fault = response.getFault();
        pw.println("SOAP call generated a fault: " + fault.toString());
      } else {
        Parameter result = response.getReturnValue();
        pw.println("Current quote for symbol " + symbol + " is " + result.getValue());
      }
    } catch (SOAPException e) {
      pw.println("SOAP exception: " + e);
      e.printStackTrace(pw);
    } finally {
      pw.println("</p></body></html>");
      pw.flush();
      pw.close();
      w.flush();
      w.close();
    }
  }
}

The J2EE deployment descriptor for this single servlet web application is below.

<?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>
  <display-name>ServletClient</display-name>
  <description>Apache SOAP ServletClient</description>
  <servlet>
    <servlet-name>GetQuote</servlet-name>
    <display-name>GetQuote</display-name>
    <description>Apache SOAP ServletClient GetQuote</description>
    <servlet-class>GetQuote</servlet-class>
    <init-param>
      <param-name>defaultEndpointURL</param-name>
      <param-value>http://localhost:8080/soap/servlet/rpcrouter</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>GetQuote</servlet-name>
    <url-pattern>/servlet/GetQuote</url-pattern>
  </servlet-mapping>
</web-app>
Return to top.

Deploying the Servlet

The first step in deploying the servlet is building it. The following ant build file is used to create the war file. Note that a copy of soap.jar is included in the war file.

<?xml version="1.0"?>
<project default="compile" basedir=".">

  <target name="init">
    <property name="name" value="servletclient"/>
    <property name="build.compiler" value="classic"/>
    <property name="debug" value="off"/>

    <property name="src.dir" value="./src"/>
    <property name="build.dir" value="./build"/>
    <property name="build.dest" value="${build.dir}/classes"/>
    <property name="dist.dir" value="./dist"/>
    <property name="webapps.dir" value="./webapps"/>

    <property name="build.file" value="build.xml"/>
  </target>

  <!-- =================================================================== -->
  <!-- Compiles the source directory                                       -->
  <!-- =================================================================== -->
  <target name="compile"
          depends="init"
          description="Compiles the source files.">
    <mkdir dir="${build.dest}"/>
    <javac srcdir="${src.dir}" destdir="${build.dest}" debug="${debug}" />
  </target>

  <!-- =================================================================== -->
  <!-- Packages the Web Application as a Web ARchive.                      -->
  <!-- =================================================================== -->
  <target name="buildwar" depends="compile">
    <mkdir dir="${dist.dir}/webapps"/>

    <war warfile="${dist.dir}/webapps/${name}.war"
         webxml="${webapps.dir}/${name}/WEB-INF/web.xml">
      <fileset dir="${webapps.dir}/${name}">
        <include name="*.html"/>
      </fileset>
      <classes dir="${build.dest}"/>
      <lib dir="./jar"/>
    </war>
  </target>
</project>

Then, execute the following to deploy the web application.

  • j:
  • cd \jakarta-tomcat-4.0.1\bin
  • shutdown
  • xcopy path-to-war\servletclient.war \jakarta-tomcat-4.0.1\webapps
  • startup

Run the servlet by pointing your browser to http://localhost:8080/servletclient/servlet/GetQuote.

Return to top.

Resources

The source for this page.

Return to top.