Skip to main content

Spring Web Services (Spring-WS)

What is meant by Spring-WS?
It is Web-Services provided by Spring Community and all spring capability are provided within this service such as dependency Injection. It is document-driven web-service. Is it Bounce? That means all requirements are specified first than web-service is written (actual code).
E.g. what data is to be send in request and what will be its response. So these things are decided first and then only you can easily write the code in case of spring-WS.

Why there is such thing of decide first and then code in Spring-WS? Or this just a theory that i just telling you to make you jumble?

No, of course not.Spring uses contract-first development in which there is loose coupling between contract and its implementation.
e.g You will first design WSDL (an XML document that describes web-service) and then its java implementation of contract.

Remember Spring -WS is Contract-First.
So start with the implementation of web-service.I will show it in step-wise manner.

We will develop web service of phone-book where client/user  (subscriber) will send person name and service will return that person's full name if present.

The .jar require for Spring-WS is
  • spring-ws-core - 2.1.3.RELEASE

Step 1:
First we will design Contract.This is done by designing XSD (XML Schema Definition) file.It will contain our SOAP request message and SOAP response message format though which communication will takes place between user and web-service.

Earlier I have told that contract is WSDL and not XSD.But in Spring-WS,we are not creating WSDL by hand ( but you can) and instead Spring will create WSDL from out designed XSD.

What are SOAP messages?
It is simple Object Access Protocol which specifies structure for implementation of web-service.Here,in our spring-WS, we will use SAAJ which will provide this information to our web-service.SAAJ is SOAP API for java.

Our request message will contain String of person name.This message will be processed by service an response will be replied.This response will also contain string containing full name.

so our contract will look like (phonebook.xsd)

<?xml version="1.0" encoding="UTF-8"?>;
<schema xmlns="" targetNamespace="" xmlns:tns="" elementFormDefault="qualified">;

    <element name="RequestMessage">;
      <element name="personName" type="string"></element>

   <element name="ResponseMessage">
      <element name="personFullName" type="string"></element>

you can create this file by using your IDE Editor or other editor.
Here two separate elements are present, each one describes our SOAP Exchange Messages for web service i.e one is request message and other is response message.

You can create multiple of request and response messages through which our web service will communicate.

e.g in our case we have one method ,which will take request message as parameter (containing person name) and it will have some processing logic and will return response message (containing persons full name).

If we create another method for another processing,it will have different request and response messages.

Note: All communication between our Web - Service and subscriber will be done through XML and only XML.

Why there is communication is through XML?
XML is nothing but TEXT in mark-up format.
Consider if your service is developed in JAVA and it is communicating through Java objects.Stop!,you may have in mind that how Java Object can be used to communicate?Simple through RMI.You can serialize the object.Then who are the expected users(subscribers) of our web service?Then the answer will be clients/users designed in Java Only.That means we restricting our service to Java as base.What if client is designed using other technology?
But if we communicate through that medium which will be understood by All.Answer is Text i.e. XML.Thought technology changes but XML will  not.

Step 2:
We have contract ready,Now its time to do actual Java coding.But here we have spring,we will code less and configure more,but these are simple configurations.

In this step I will repeatedly use word JAXb.So Question Arises what is Jaxb?
JAXB is Java XML Binding API.Means What ? It does the job of marshalling and unmarshalling?means What?
e.g if you want to  convert java class to XML or wise versa,then just use Jaxb,It accepts input as Java Class and results XML and vice versa.
There are also alternative to Jaxb.Spring will not stop you to use another alternative.Some are DOM4J,JiXM,SAX ,JDOM.
But in case of simplicity we will use Jaxb.But it also has

We will generate Java classes from XSD  schema file.Using Jaxb schemagen tool we can generate Java classes.
If you are using  IDE, then right click on XSD file,now click generate classes in given package.
we will have four Java classes generated.
  1.     - it will contain requested data
  2.   -it will contain response data
  3.            -It will guide JAXB parser for presence of Annotated Classes package.
  4.          -you can delete it,not must necessary.If you have multiple                schema  files,then it will be necessary,for current,it is not.
If you open any class,there some annotation.there are required for JAXB to generate XML from them.these annotations guides the JAXB about what is node and what are its childs. I will just introduce them to you.

    @XmlRootElement - it decide root  elemnt of XML.

    @XmlElement        - it decide child elements of XML.
        @XmlAccessorType(XmlAccessType.FIELD) - allows access by field name

    Step 3:
    we have Contract i.e. XSD file.So we will now require some request handler.That means all subscribers request handler.Spring provides MessageDispatcherServlet class, which merely extends (now Java Extends) DispatcherServletClass ,which dispatches XML incoming requests.It is just like a front- face to our web-service.

    Our web.xml look like


    Earlier I have mentioned that this message dispatcher dispatches incoming XML messages ! Hum-mm,dispatches to whom? here we have Endpoints.

    Step 4:
    Endpoints are central to Spring-WS.All XML message handling and business logic in present in them.
    How we can decide that this class is endpoint.Simple,just annotate with @Endpoint.

    As we have describing only one service of phonebook,hence we have single method.It will accept  request,process it and return response.

    Our endpoint look like

    public class PhoneBookEndPoint {
     public PhoneBookEndPoint() {}
     @PayloadRoot(localPart = "RequestMessage", namespace = "")
     public ResponseMessage processRequest(@RequestPayload RequestMessage request) {
      ResponseMessage response = new ResponseMessage();
      response.setPersonFullName("Surname Found to Name : "+request.getPersonName());
      return response;

    @PayloadRoot indicate what type of message this method handles.for that you have to give namespace of XML message and that message element name i.e localpart.
    What is namespace?It just as name that differentiates particular XML from other.
    @PequestPayload ,it tells WS to bind parameter to message payload.
    e.g here parameter  request is annotated with @RequestPayload.This parameter supported by JAXB as it has @XMLRootElement ,hence JAXB will unmarshall that message payload and result will be passed to method. 

    e.g. when user request particular web service then
    1. XML request message will arrive at MessageDispatcherServlet
    2. it will find Endpoint for that particular request
    3. it will delegate adaptor for that endpoint
    4. finally response will be returned
    You may think that how it can be possible Or will  spring do it automatically?
    Answer is we will tell him to do it by configuring it.

    Step 5:
    Now,we have XSD file containing Request and Response Message Description, WSDL(will automatically generated by spring with help of XSD),Java Classes of Request and Response Message,Message Dispatcher for handling mappings.
    Finally we will configure them to work in such manner.

    we will create beans in XML which is the first file messageDispatcher will be find in container.
    Those beans contains marshaller,endpoint and more like.

    Then question may arise what  is meant by beans?
    Beans are nothing but the reusable component and frankly speaking the object created through XML and following bean standard i.e. having getter and setter, no-arg constructor and implements serializable.

    Our config file (spring-ws-servlet.xml) look like

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns=""
     xmlns:p="" xmlns:xsi=""
     <sws:annotation-driven marshaller="jaxb2Marshaller"
      unmarshaller="jaxb2Marshaller" />
     <sws:dynamic-wsdl id="phonebook" portTypeName="phonebook"
      locationUri="/phonebook/" targetNamespace="">
      <sws:xsd location="/WEB-INF/classes/com/ws/schema/phonebook.xsd" />
     <bean class="" />
      <bean id="validatingInterceptor"
       <property name="schema"
        value="/WEB-INF/classes/com/ws/schema/phonebook.xsd" />
       <property name="validateRequest" value="true" />
       <property name="validateResponse" value="true" />
     <bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
      <property name="classesToBeBound">
      <property name="schema" value="classpath:com/ws/schema/phonebook.xsd" />

    I will give some information regarding some setting that are abruptly landed in the XML.
    Here we are creating beans of marshaller and Endpoint ,payload validator which will validate request and response.
    < sws:annotation-driven > will fine for annotations like @endpoint in project.

    < sws:dyanamic-wsdl > will create wsdl file and with the name phonebook and will be access by /phonebook/ location.

    here,our created wsdl file name will be the id i.e phonebook and we can access it by 


    And after long explanation we have developed Spring-WS.I think i have missed something what?I did not mention developed successfully or with bug unsuccessfully.How we can understand that our web service is working fine or not.

    Yes,we can test it and we have already tested it.How?
    when you will hit the URL 


    and if wsdl is not displayed on page/browser,then we have done something wrong.If wsdl is displayed on browser then it is working properly (but  logic inside endpoint method is your nightmare not the web service's.).

    Why wsdl has very much importance?
    Because user/subscriber/client communicate to we-service by WSDL only.Through with it can understand the parameters required for request and response message.
    e.g if you have client and it is calling the particular web-service.For communication purpose client will require information about request message which is compatible for that web-service.How client get that information?Simple,through wsdl file of that particular web-service.

    Very nice thing about Spring-WS is that it is easy to configure.
    Thank you.


    Popular posts from this blog

    Get Browser Name and Version in Javascript

    JQuery stopped providing $.browser function after 1.9 release.So you have to write your own code to get know browser and its version.There is not standard procedure or code to achieve this.
    But I will show you to get browser name and version of  IE > 6, Google Chrome And FF.

    Here we have AGENT to rescue.Every browser has navigation object available in its script.In this object userAgent field contains current browser information.

    So you can ask me What is User-Agent?How will it help us?
              As I said earlier it contain browser information.There is not standard to show each information but almost every browser support it.
        There is complicated history behind user-agent variable.But in simple sense we can say that user-agent is used by server side component to get information of client-side browser and its compatibility to page it will going to rendered.So we conclude that this user-agent information is little bit 50% same in all browser.

    Why is it(user-agent) 50% s…

    Share data between Iframe and its Parent using JQuery

    There could be requirement that you have to pass variables values to Iframe from parent or in other scenario you have to pass values from Iframe to its parent.I am going to show simple example of above situation with the help of JQuery.
               Support we have parent HTML page having iframe included like below

    <html> <body> <input id="parentValue" type="text" value="I am from Parent !" /> <iframe src="domainurl/relativepath" id="iframe"></iframe> <script> $(document).ready(function() { //code to take value from child iframe var childValue = $("#iframe").contents().find("#childValue").val(); alert(childValue); }); </script> </body> </html> 
            and we have frame code like below
    <html> <body> <input id="childValue" type="text" value="I …

    Spring Default Limit for Collection and Array is 256

    If you are working in Web Application Development then you may stuck or already had ,then you will get mad of getting this error

    How this error emanates in Spring?

    i will explain you with example.Suppose you are adding Values in List in JSP using JSTL tag or other.
    This list is in Form(HTML).When you POST this form,In behind Stage,Spring does binding of Object and List if present.

    But wait...
    In Spring,Default limit for array and collection growing is 256.

    Why this limit is Set?

    seldom you have to send List size greater than this limit.
    Spring has set this limit to avoid notable OutOfMemoryErrors in case of large indexes.

    So,than What if i want to set Collection greater than this size?

    I had told earlier,spring does binding behind.If we tell spring to increase it's size or set collection size behalf of spring.
    You you can do it.

    We have initBinder,  in Spring  it is called when spring does the binding mechanism
    e.g @Mod…