Monday, August 25, 2008

Developing web services using Spring ws and JAXB marshaller

Spring web services a product of spring community, helps in developing web services using contract first web services and helps in manipulating the xml in many ways. In this tutorial I am about to show a step by step guide in developing spring web services using JAXB as mashalling technology.

You can download spring, spring web services here.

We are about to develop a web service which search the blogs based on a search criteria on title string and published date.

So lets get started,

1.Create a web application
This is a general spring web MVC application. for a skeleton application, you can just run this maven archetype to quickly start with,

mvn archetype:create -DarchetypeGroupId=org.springframework.ws \
-DarchetypeArtifactId=spring-ws-archetype \
-DarchetypeVersion=1.5.4 \
-DgroupId=com.teja \
-DartifactId=spring-ws-test

Or you can just add the spring nature to your existing web application by configuring the web.xml shown in the next step. Here is the file structure I am using for this simple demo.



2.Configure web.xml.
  1. <servlet>

  2. <servlet-name>spring-ws</servlet-name>

  3. <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>

  4. </servlet>

  5. <servlet-mapping>

  6. <servlet-name>spring-ws</servlet-name>

  7. <url-pattern>/*</url-pattern>

  8. </servlet-mapping>

  9. <servlet-mapping>

  10. <servlet-name>spring-ws</servlet-name>

  11. <url-pattern>*.wsdl</url-pattern>

  12. </servlet-mapping>

  13. <servlet-mapping>

  14. <servlet-name>spring-ws</servlet-name>

  15. <url-pattern>*.soap</url-pattern>

  16. </servlet-mapping>



Spring strongly supports only contract first web services for several reasons like Fragility, performance, re usability and versioning.
You can find more information visit this link

So lets start first by developing our XSD....
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"

  3. targetNamespace="http://com.tejakantamneni/schemas"

  4. xmlns:tns="http://com.tejakantamneni/schemas"

  5. elementFormDefault="qualified">



  6. </xsd:schema>






This is a plain regular xsd where we will define all our xml elements going to create our wsdl file.
Lets define our blog object, the blog is just a complex type object with three properties the "Title" for the blog, the "AbstractDetail" of the blog and the date when the blog is published "PublishedDate". This can be defined in the xml complex type
as follows...

  1. <xsd:complexType name="Blog">

  2. <xsd:sequence>

  3. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  4. <xsd:element name="AbstractDetail" type="xsd:string" nillable="true"/>

  5. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  6. </xsd:sequence>

  7. </xsd:complexType>


Next step is defining the search criteria object, I am wrapping the search criteria into a seperate object so that in future, we can extend the search criteria by adding more elements like author, subject. Here the xsd definition of the search criteria
object with two fields title and published date.

  1. <xsd:element name="SearchCriteria">

  2. <xsd:complexType>

  3. <xsd:sequence>

  4. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  5. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  6. </xsd:sequence>

  7. </xsd:complexType>

  8. </xsd:element>


The next stepa are creating the actual request object for our web service, which is basically a wrapper on the search criteria and our response object which is just a array/list of blog objects (which can be either zero size, if search results nothing
or can be of size n if search returns n objects).
Here is our completed xsd,
  1. <?xml version="1.0" encoding="UTF-8"?>



  2. <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"

  3. targetNamespace="http://com.tejakantamneni/schemas"

  4. xmlns:tns="http://com.tejakantamneni/schemas"

  5. elementFormDefault="qualified">



  6. <xsd:element name="BlogSearchRequest">

  7. <xsd:complexType>

  8. <xsd:sequence>

  9. <xsd:element ref="tns:SearchCriteria" minOccurs="0" maxOccurs = "unbounded" />

  10. </xsd:sequence>

  11. </xsd:complexType>

  12. </xsd:element>



  13. <xsd:element name="BlogSearchResponse">

  14. <xsd:complexType>

  15. <xsd:sequence>

  16. <xsd:element name="blogList" type="tns:Blog" minOccurs="0" maxOccurs = "unbounded" />

  17. </xsd:sequence>

  18. </xsd:complexType>

  19. </xsd:element>



  20. <xsd:element name="SearchCriteria">

  21. <xsd:complexType>

  22. <xsd:sequence>

  23. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  24. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  25. </xsd:sequence>

  26. </xsd:complexType>

  27. </xsd:element>



  28. <xsd:complexType name="Blog">

  29. <xsd:sequence>

  30. <xsd:element name="Title" type="xsd:string" nillable="true"/>

  31. <xsd:element name="AbstractDetail" type="xsd:string" nillable="true"/>

  32. <xsd:element name="PublishedDate" type ="xsd:dateTime" nillable="true"/>

  33. </xsd:sequence>

  34. </xsd:complexType>

  35. </xsd:schema>



The next in developing our web services is defining our contract, the WSDL file.
Here is the complete version the WSDL file.
Essentilly we are improting the xsd file which we had created in the earlier step to use them in the wsdl
Then create the message parts, the port and the binding operation for the blog search service. This is self explanatory.
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <definitions name="BlogSearch" targetNamespace="http://com.tejakantamneni/definitions"

  3. xmlns="http://schemas.xmlsoap.org/wsdl/"

  4. xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"

  5. xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"

  6. xmlns:xsd="http://www.w3.org/2001/XMLSchema"

  7. xmlns:tns="http://com.tejakantamneni/definitions"

  8. xmlns:schema="http://com.tejakantamneni/schemas">

  9. <wsdl:types>

  10. <xsd:schema targetNamespace="http://com.tejakantamneni/definitions" xmlns:schema="http://com.tejakantamneni/schemas">

  11. <xsd:import namespace="http://com.tejakantamneni/schemas" schemaLocation="../schemas/BlogSearch.xsd"/>

  12. </xsd:schema>

  13. </wsdl:types>

  14. <wsdl:message name="BlogSearchRequest">

  15. <wsdl:part name="BlogSearchRequest" element="schema:BlogSearchRequest"/>

  16. </wsdl:message>



  17. <wsdl:message name="BlogSearchResponse">

  18. <wsdl:part name="BlogSearchResponse" element="schema:BlogSearchResponse"/>

  19. </wsdl:message>



  20. <wsdl:portType name="BlogSearchService">

  21. <wsdl:operation name="BlogSearchOperation">

  22. <wsdl:input message="tns:BlogSearchRequest" name="BlogSearchRequest" />

  23. <wsdl:output message="tns:BlogSearchResponse" name="BlogSearchResponse" />

  24. </wsdl:operation>

  25. </wsdl:portType>



  26. <wsdl:binding name="BlogSearchBinding" type="tns:BlogSearchService">

  27. <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>

  28. <wsdl:operation name="BlogSearchOperation">

  29. <soap:operation soapAction="http://tejakantamneni.com/SearchBlogs"/>

  30. <wsdl:input name="BlogSearchRequest">

  31. <soap:body use="literal" />

  32. </wsdl:input>

  33. <wsdl:output name="BlogSearchResponse">

  34. <soap:body use="literal" />

  35. </wsdl:output>

  36. </wsdl:operation>

  37. </wsdl:binding>



  38. <wsdl:service name="BlogSearchService">

  39. <wsdl:port binding="tns:BlogSearchBinding" name="BlogSearchBindingPort">

  40. <soap:address location="http://localhost:8080/spring-ws-test/BlogSearch.soap"/>

  41. </wsdl:port>

  42. </wsdl:service>



  43. </definitions>






next step is creating the JAXB objects for your xsd elements using xjc compiler. you can either craft the JAXB objects by hand or just
use the xjc compiler. I prefer the later one. see https://jaxb.dev.java.net/guide/ for more details. (My Intellij Idea supports generating JAXB objects directly from xsd).

(Posting all the code is not practical, So I am moving here ahead posting the important parts)
Here is the endpoint
  1. /*

  2. * To change this template, choose Tools | Templates

  3. * and open the template in the editor.

  4. */
  5. package com.teja.service.endpoint;
  6. import com.teja.Blog;
  7. import com.teja.BlogSearchRequest;
  8. import com.teja.BlogSearchResponse;
  9. import com.teja.SearchCriteria;
  10. import java.util.ArrayList;
  11. import java.util.Date;
  12. import java.util.GregorianCalendar;
  13. import java.util.List;
  14. import javax.xml.datatype.DatatypeConfigurationException;
  15. import javax.xml.datatype.DatatypeFactory;
  16. import javax.xml.datatype.XMLGregorianCalendar;
  17. import javax.xml.transform.Source;
  18. import org.springframework.beans.factory.annotation.Autowired;
  19. import org.springframework.oxm.Marshaller;
  20. import org.springframework.oxm.support.MarshallingSource;
  21. import org.springframework.ws.server.endpoint.annotation.Endpoint;
  22. import org.springframework.ws.server.endpoint.annotation.XPathParam;
  23. import org.springframework.ws.soap.server.endpoint.annotation.SoapAction;


  24. /**

  25. * @author Teja Kantamneni
  26. * @version 1.0 Aug 25, 2008 - 11:30:49 AM
  27. */


  28. @Endpoint
  29. public class BlogSearchEndpoint {

  30. public static final String BLOG_SEARCH_ACTION = "http://tejakantamneni.com/SearchBlogs";

  31. @Autowired
  32. Marshaller marshaller;

  33. @SoapAction(BLOG_SEARCH_ACTION)
  34. // public Source searchBlogs(@XPathParam("/sch:BlogSearchRequest/sch:SearchCriteria/sch:Title") String title, @XPathParam("/sch:BlogSearchRequest/sch:SearchCriteria/sch:PublishedDate") String publishedDate) throws DatatypeConfigurationException {
  35. public BlogSearchResponse searchBlogs(BlogSearchRequest blogSearchRequest) throws DatatypeConfigurationException {
  36. BlogSearchResponse blogSearchResponse = new BlogSearchResponse();
  37. List<Blog> resultBlogs = new ArrayList<Blog>();

  38. DatatypeFactory datatypeFactory = DatatypeFactory.newInstance();
  39. GregorianCalendar gregorianCalendar = new GregorianCalendar();
  40. gregorianCalendar.setTime(new Date());
  41. XMLGregorianCalendar xmlGregorianCalendar = datatypeFactory.newXMLGregorianCalendar(gregorianCalendar);

  42. Blog b = new Blog();
  43. b.setAbstractDetail("Abstract details -teja");
  44. b.setTitle("Teja test");
  45. b.setPublishedDate(xmlGregorianCalendar);

  46. resultBlogs.add(b);
  47. for (Blog blog : resultBlogs) {
  48. blogSearchResponse.getBlogList().add(blog);
  49. }
  50. return blogSearchResponse;
  51. }
  52. }




now the last and more important step, putting all the things together to deploy the service,configuring the spring-ws-servlet.xml

First and the most important point here is I am autowiring the endpoint by using the annotation @Endpoint.

So in the context.xml, we are defining the wsdl to be exposed as a bean using the class org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition.
I am specifying the JAXBMarshaller and injecting all the jaxb classes.
I am also configuring a couple of beans for validating and logging each and every request and response.


  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <beans xmlns="http://www.springframework.org/schema/beans"

  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  4. xmlns:context="http://www.springframework.org/schema/context"

  5. xmlns:jee="http://www.springframework.org/schema/jee"

  6. xmlns:lang="http://www.springframework.org/schema/lang"

  7. xmlns:util="http://www.springframework.org/schema/util"

  8. xmlns:p="http://www.springframework.org/schema/p"

  9. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

  10. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd

  11. http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd

  12. http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.5.xsd

  13. http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd">


  14. <bean id="BlogSearch" class="org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition"

  15. p:wsdl="/wsdls/BlogSearch.wsdl"/>


  16. <bean class="org.springframework.ws.server.endpoint.adapter.GenericMarshallingMethodEndpointAdapter" >

  17. <constructor-arg ref="marshaller" index="0"/>

  18. </bean>


  19. <bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">

  20. <property name="classesToBeBound">

  21. <list>

  22. <value>com.teja.Blog</value>

  23. <value>com.teja.BlogSearchRequest</value>

  24. <value>com.teja.BlogSearchResponse</value>

  25. <value>com.teja.SearchCriteria</value>

  26. </list>

  27. </property>

  28. <property name="schema" value="/schemas/BlogSearch.xsd" />

  29. </bean>


  30. <bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping">

  31. <property name="interceptors">

  32. <list>

  33. <bean class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor"/>

  34. <ref bean="validatingInterceptor"/>

  35. </list>

  36. </property>


  37. </bean>


  38. <bean class="org.springframework.ws.soap.server.endpoint.mapping.SoapActionAnnotationMethodEndpointMapping">

  39. <property name="interceptors">

  40. <list>

  41. <bean class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor"/>

  42. <ref bean="validatingInterceptor"/>

  43. </list>

  44. </property>


  45. </bean>


  46. <bean id="validatingInterceptor"

  47. class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor"

  48. p:schema="/schemas/BlogSearch.xsd"

  49. p:validateRequest="true"

  50. p:validateResponse="true"/>



  51. <bean class="org.springframework.ws.server.endpoint.adapter.XPathParamAnnotationMethodEndpointAdapter">

  52. <property name="namespaces">

  53. <props>

  54. <prop key="sch">http://com.tejakantamneni/schemas</prop>

  55. <prop key="xs">http://www.w3.org/2001/XMLSchema</prop>

  56. </props>

  57. </property>

  58. </bean>


  59. <!-- scan classes for dependency annotations -->

  60. <context:component-scan base-package="com.teja"/>

  61. <context:annotation-config/>


  62. <bean class="org.springframework.ws.soap.server.endpoint.SoapFaultAnnotationExceptionResolver">

  63. <property name="order" value="2"/>

  64. </bean>


  65. </beans>




you can access the wsdl at http://localhost:8080/spring-ws-test/wsdl/BlogSearch.wsdl

10 comments:

NazakatQureshi said...

Its look Great,

But i am new in Spring Web Services, it will be nice for me to have complete source code.

can i get the complete source code for this Example.

Waitng for your kind Response!

Teja said...

Sorry for the late reply... got to dig in to find the old files..
http://rapidshare.com/files/241572573/spring-ws-test.zip

Anonymous said...

Hi Teja,
thks for this great tuto. i need the complete source if it's possible. thks,

Anonymous said...

need the complete source code

san said...

can you please update the total code or send to san_121087@yahoo.com

joe said...

Hi Teja,
Can you please share spring-ws-test.zip (your sample WS on spring)??
my mail id: jovinvjoy@gmail.com

Unknown said...

Hi Trja
Please can you share the code source
the link in rapidshare is deleted

or if you can send it by email

elkina.hamza (a) gmail . com

Thank you :)

Sachin Gupta said...

One of the high accuracy based Algorithmic trading software

Sachin Gupta said...

Open your less brokerage demat account for share market

Anonymous said...

There are limitations on what tribes can spend gaming proceeds on, targeted on the welfare of the tribe and its members, the operations of its government, economic development, charity, and local government companies. You can guess on horse races at one of many state’s four personal horse racing tracks, one of its five racing festivals, 점보카지노 or at one of its 23 simulcast locations, the place have the ability to|you possibly can} watch the race on TV and place a guess. You also can place a guess from residence – or anywhere – with on-line advance deposit wagering. This analysis is funded by the Massachusetts Gaming Commission. The knowledge are publicly out there to other researchers via the Massachusetts Gaming Commission’s Data Storage and Access project and by request to the Massachusetts Gaming Commission, Director of Research and Responsible Gaming, Mark Vander Linden, These analyses current findings for month-to-month (i.e., regular) participation since this degree of participation is attribute of drawback gambling.