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.

e.g.
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="http://www.w3.org/2001/XMLSchema" targetNamespace="http://www.example.org/phonebook" xmlns:tns="http://www.example.org/phonebook" elementFormDefault="qualified">;

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

   <element name="ResponseMessage">
    <complexType>
     <sequence>
      <element name="personFullName" type="string"></element>
     </sequence>
    </complexType>
   </element> 
   
</schema>

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. RequestMessage.java     - it will contain requested data
  2. ResponseMessage.java   -it will contain response data
  3. package-info.java            -It will guide JAXB parser for presence of Annotated Classes package.
  4. ObjectFactory.java          -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


    <servlet>
            <servlet-name>spring-ws</servlet-name>
            <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>spring-ws</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    

    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


    @Endpoint
    public class PhoneBookEndPoint {
    
     public PhoneBookEndPoint() {}
    
     @PayloadRoot(localPart = "RequestMessage", namespace = "http://www.example.org/phonebook")
     @ResponsePayload
     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="http://www.springframework.org/schema/beans"
     xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:sws="http://www.springframework.org/schema/web-services"
     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
           http://www.springframework.org/schema/web-services http://www.springframework.org/schema/web-services/web-services-2.0.xsd">
    
     <sws:annotation-driven marshaller="jaxb2Marshaller"
      unmarshaller="jaxb2Marshaller" />
    
     <sws:dynamic-wsdl id="phonebook" portTypeName="phonebook"
      locationUri="/phonebook/" targetNamespace="http://www.example.org/phonebook">
      <sws:xsd location="/WEB-INF/classes/com/ws/schema/phonebook.xsd" />
     </sws:dynamic-wsdl>
    
     <bean class="com.ws.endpoint.PhoneBookEndPoint" />
     
     <sws:interceptors>
      <bean id="validatingInterceptor"
       class="org.springframework.ws.soap.server.endpoint.interceptor.PayloadValidatingInterceptor">
       <property name="schema"
        value="/WEB-INF/classes/com/ws/schema/phonebook.xsd" />
       <property name="validateRequest" value="true" />
       <property name="validateResponse" value="true" />
      </bean>
     </sws:interceptors>
    
     <bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
      <property name="classesToBeBound">
       <list>
        <value>com.ws.domain.RequestMessage</value>
        <value>com.ws.domain.ResponseMessage</value>
       </list>
      </property>
      <property name="schema" value="classpath:com/ws/schema/phonebook.xsd" />
     </bean>
    
    </beans>
    

    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 

    http://localhost:8080/phonebook/phonebook.wsdl
    

    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 

    http://localhost:8080/phonebook/phonebook.wsdl
    

    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.

    References:
    http://docs.spring.io/spring-ws/sites/2.0/
    https://jaxb.java.net/nonav/2.2.4/docs/api/javax/xml/bind/Marshaller.html

    Popular posts from this blog

    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


    java.lang.ArrayIndexOutOfBoundsException:Arrayindexoutofrange256
    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…

    Apache FOP Tutorial for PDF Generation

    What is meant by Apache FOP?

    Apache is providing open source JAVA application for PDF(or any other format) file generation from XML data.Simply to can give data in XML,it gives output in PDF or any format.But it is primary for PDF output.

    Official explanation,
    OP (Formatting Objects Processor) is the world's first print formatter driven by XSL formatting objects (XSL-FO) and the world's first output independent formatter. It is a Java application that reads a formatting object (FO) tree and renders the resulting pages to a specified output. Output formats currently supported include PDF, PCL, PS, SVG, XML (area tree representation), Print, AWT, MIF and TXT

    How wcan configure apache fop with our project?

    I am going to explain how to generate PDF using Apache FOP.
    I will explain it in steps

    Step 1:
    You will require 3 jar for configurations.Here fop jar depend on both avalon api and avalon impl.
                  1.    apache fop 1.1
                  2.    avalon-framework-api 4.3.1
        …