Advanced java code dealing with real world problems.

Friday, May 4, 2012

SOAP Web Service using Spring-WS 2.0 - Part 1

Spring Web Service framework has come a long way, and it has made implementing web services in java a trivial task with release 2.0. Let's walk-through a creation of a simple "Project Search" web service project, step by step.

Step 1) create a web project with your favorite IDE, I use Eclipse or IBM RAD.

Step 2) create or modify your web.xml with following entries:

            <!-- classpath*:spring-ws-test.xml, -->

    <description>Spring Message Dispatcher</description>



Step 3) create an xml schema that defines service request and response message format, and save it as ws-project.xsd under WEB-INF folder:

<schema xmlns=""

    <xs:element name="ProjectRequest" type="tns:ProjectRequestType"/>
    <xs:element name="ProjectResponse" type="tns:ProjectResponseType"/>

    <xs:complexType name="ProjectRequestType">
            <xs:element name="Name" type="xs:string"/>
    <xs:complexType name="ProjectResponseType">
            <xs:element name="Name" type="xs:string"/>
            <xs:element name="Description" type="xs:string"/>
            <xs:element name="Url" type="xs:string"/>
            <xs:element name="StartDate" type="xs:date"/>
            <xs:element name="EndDate" type="xs:date"/>

Step 4) create a Spring Web Service configuration file called "ws-test-servlet.xml" and save it under WEB-INF folder. Notice that the "servlet-name" in web.xml is used to name this Spring web service configuration xml file, this is required by Spring-WS framework.

<beans xmlns=""
    xmlns:xsi="" xmlns:context=""

<context:component-scan base-package=""/>

<sws:dynamic-wsdl id="projectSearch"
    locationUri="/SpringWSTest/" requestSuffix="Request" responseSuffix="Response"
  <sws:xsd location="/WEB-INF/ws-project.xsd"/>

In this config file, we tell Spring where our web service schema is located, and Spring will generate WSDL based on the xsd file. Please also notice that we have enabled "component-scan" and "annotation-driven" in the config file, this is required for our project.

Once our project is deployed to a servlet container, for example a local tomcat server, we should be able to access the wsdl file from browser with address: http://localhost:8080/SpringWSTest/projectSearch.wsdl

Step 5) create an Endpoint class that will be used to serve the request. For simplicity, we display the request xml to the console and load a static xml from a file and return it as response. The class is annotated with @Endpoint, and service method is annotated with @PayloadRoot:



import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.jdom2.input.DOMBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

 * Spring-WS End-Points are scoped as singleton by default and have to be thread safe.
public class ProjectSearchEndpoint {
    static Logger logger = Logger.getLogger(ProjectSearchEndpoint.class);
    @PayloadRoot(namespace = "", localPart = "ProjectRequest")
    public Element searchProjects(@RequestPayload Element request) {
        // print out xml payload using jdom
        XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
        DOMBuilder builder = new DOMBuilder();
        org.jdom2.Element doc =;
        try {
            xout.output(doc, System.out);
        catch (IOException e) {
            logger.error("Exception", e); // put your error handling logic here
        // load response from xml file and return it
        try {
            Document resp = loadDocumentFromFilePath("/TestXmls/TestResponse.xml");
            return resp.getDocumentElement();
        catch (Exception e) {
            logger.error("Exception", e); // put your error handling logic here
        return null;

    private Document loadDocumentFromFilePath(String doc_path)
            throws ParserConfigurationException, SAXException, IOException {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        InputStream doc_is = loader.getResourceAsStream(doc_path);
        if (doc_is == null) {
            throw new IllegalArgumentException("Could not find xml file: " + doc_path);
        // use jaxp to initialize a DOM parser
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(new InputSource(doc_is));
        return document;

Step 6) to make above Endpoint work, create a folder called "TestXmls" in your project's src (source) folder, and save following sample xml as "TestResponse.xml" to the folder. In real world you will need to construct a real response based on the request and return it.

    xsi:schemaLocation=" ws-project.xsd"
    <tns:Description>Test project using Spring-WS 2.0</tns:Description>

Step 7) deploy the project to your favorite container. And it's ready to serve.

No comments:

Post a Comment


About Me

An IT professional with more than 20 years of experience in enterprise computing. An Audio enthusiast designed and built DIY audio gears and speakers.