Spring Web Services Tutorial For Beginners | Spring WS Integration

We offer you a brighter future with FREE online courses - Start Now!!

1. Objective

In our previous Spring Framework tutorial, we studied Bean Definition Inheritance. Today, in this article, we will learn about the Spring Web services. Moreover, we will see the features along with a working example of Spring Web Services. Along with this, we will discuss Architecture of web service in Spring Framework.
So, let’s start Spring Web Services.

Spring Web Services Tutorial For Beginners | Spring WS Integration

Spring Web Services Tutorial For Beginners | Spring WS Integration

2. What is Spring Web Services?

The main focus of Spring Webservice is to facilitate contract-first SOAP service development. It provides several ways to create flexible web services which help in manipulate XML payloads. Also, the Spring Web services are Spring based which has concepts like DI and configurations etc. Therefore, before moving forward the readers should have the understanding of Java programming language and Spring Framework along with working of Eclipse IDE so as to get going with examples.
Read about Spring BeanPostProcessors – Latest Tutorial 2018

3. Features of Spring Web Services

Some of the notable features of Spring Web services:

Features of Spring Web Services

Features of Spring Web Services

  • Spring-based configurations

As you know Spring Web services uses Spring Application contexts for its configurations having the very similar architecture to that of Spring MVC framework.

  • XML mapping to objects

The XML based requests can be mapped to any of the objects using info from SOAP Action header, Message Payload etc.

  • Multiple API Support to parse XML

Apart from JAXP APIs to parse XML requests other libraries such as don4j or XOM etc. are also supported by Spring Web services.

  • Support for Acegi security

With the Spring Webservice implementation of WS-security you can sign, encrypt, decrypt SOAP messages and authenticate them.
Let’s Discuss 5 Major Types of Scope in Spring

4. Architecture of Spring Web Services

The components of the architecture are described as follows:

Architecture of Spring Web services

Architecture of Spring Web services

  • Spring-WS core

It is the primary module of the Spring Web services architecture. It provides Central interfaces like SoapMessage and WebServiceMessage, the server side framework and support classes to implement ‘web service endpoints.

  • Spring-WS Support

This module is responsible for providing support for Java Messaging Services, emails etc.

  • Spring-WS Security

This module provides WS-Security implementation with core Webservice module integration. Using this you can add principal tokens, sign, encrypt and decrypt SOAP messages.

Architecture of Spring Web services

Spring Web Services – Architecture & Components

  • Spring XML

This module is responsible for providing XML support classes for Spring Web services and it is internally used by Spring-WS framework.

  • Spring-OXM

This module is for providing support classes for XML vs Object mapping.
Follow this link to know about the Spring Bean Life Cycle 

5. Spring Web Service Example

Now after understanding the Spring WS along with its features, you will see a working example.
You will see a simple Spring WS application which exposes a web service method to book a leave in the HR portal.
Since the Spring Web services use contract first approach which means you should have XML structures ready before using Java-based code.
So, you will now define a LeaveRequest object having Leave and Employee as sub-objects.
Leave.xml

<Leave xmlns = "http://example.com/hr/schemas">
   <StartDate>2018-06-23</StartDate>
   <EndDate>2018-06-27</EndDate>
</Leave>

Employee.xml

<Employee xmlns = "http://example.com/hr/schemas">   <Number>404</Number>   <FirstName>Mahesh</FirstName>   <LastName>Parashar</LastName></Employee>

LeaveRequest.xml

<LeaveRequest xmlns = "http://example.com/hr/schemas">   <Leave>      <StartDate>2018-06-23</StartDate>      <EndDate>2018-07-27</EndDate>   </Leave>      <Employee>      <Number>404</Number>      <FirstName>Mahesh</FirstName>      <LastName>Parashar</LastName>   </Employee></LeaveRequest>

 Hr.xsd

<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"   xmlns:hr = "http://example.com/hr/schemas"   elementFormDefault = "qualified"   targetNamespace = "http://example.com/hr/schemas">      <xs:element name = "LeaveRequest">      <xs:complexType>         <xs:all>
    <xs:element name = "Leave" type = "hr:LeaveType"/>            <xs:element name = "Employee" type = "hr:EmployeeType"/>         </xs:all>      </xs:complexType>   </xs:element>      <xs:complexType name = "LeaveType">      <xs:sequence>         <xs:element name = "StartDate" type = "xs:date"/>         <xs:element name = "EndDate" type = "xs:date"/>      </xs:sequence>   </xs:complexType>      <xs:complexType name = "EmployeeType">      <xs:sequence>         <xs:element name = "Number" type = "xs:integer"/>         <xs:element name = "FirstName" type = "xs:string"/>         <xs:element name = "LastName" type = "xs:string"/>      </xs:sequence>   </xs:complexType></xs:schema>
Example of Spring Web Services

Spring Web Service Example

a. Project Creation

Now open the command console and go to directory C:\MVN and execute the following:
C:\MVN>mvn archetype:generate -DarchetypeGroupId = org.springframework.ws-DarchetypeArtifactId = spring-ws-archetype -DgroupId = com.example.hr-DartifactId = leaveService
Have a look Spring Beans Autowiring – Modes with Eclipse IDE Example
Maven will then start processing and will then create the Java Application Project Structure. Now go to C:/MVN directory you will see a project named leaveService. There update the pom.xml and add java files HumanResourceService and HumanResourceServiceImpl in the folder:
C:\MVN\leaveService\src\main\java\com\example\hr\service
After this is done open the folder C:\MVN\leaveService\src\main\java\com\example\hr\ws and add LeaveEndpoint.java in it. 
Pom.xml

<?xml version = "1.0" encoding = "UTF-8"?>
<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/maven-v4_0_0.xsd"> 
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.example.hr</groupId>
   <artifactId>leaveService</artifactId>
   <packaging>war</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>leaveService Spring-WS Application</name>
   <url>http://www.springframework.org/spring-ws</url> 
   <build>
      <finalName>leaveService</finalName>
   </build>  
   <dependencies>
      <dependency>
         <groupId>org.springframework.ws</groupId>
         <artifactId>spring-ws-core</artifactId>
         <version>2.4.0.RELEASE</version>
      </dependency>    
      <dependency>
         <groupId>jdom</groupId>
         <artifactId>jdom</artifactId>
         <version>1.0</version>
      </dependency>    
      <dependency>
         <groupId>jaxen</groupId>
         <artifactId>jaxen</artifactId>
         <version>1.1</version>
      </dependency>    
      <dependency>
         <groupId>wsdl4j</groupId>
         <artifactId>wsdl4j</artifactId>
          <version>1.6.2</version>
      </dependency>
   </dependencies>
</project>

HumanResourceService.java

package com.example.hr.service;
import java.util.Date;
public interface HumanResourceService {
   void bookLeave(Date startDate, Date endDate, String name);
}

HumanResourceServiceImpl.java

package com.example.hr.service;
import java.util.Date;
import org.springframework.stereotype.Service;
@Service
public class HumanResourceServiceImpl implements HumanResourceService {
   public void bookLeave(Date startDate, Date endDate, String name) {
      System.out.println("Booking holiday for [" + startDate + "-" + endDate + "]
         for [" + name + "] ");
   }
}

LeaveEndpoint.java

package com.example.hr.ws;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import com.example.hr.service.HumanResourceService;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.Namespace;
import org.jdom.xpath.XPath;
@Endpoint
public class LeaveEndpoint {
   private static final String NAMESPACE_URI = "http://example.com/hr/schemas";
   private XPath startDateExpression;
   private XPath endDateExpression;
   private XPath nameExpression;
   private HumanResourceService humanResourceService;
   @Autowired
   public LeaveEndpoint(HumanResourceService humanResourceService) throws JDOMException {
      this.humanResourceService = humanResourceService;
      Namespace namespace = Namespace.getNamespace("hr", NAMESPACE_URI);
      startDateExpression = XPath.newInstance("//hr:StartDate");
      startDateExpression.addNamespace(namespace);
      endDateExpression = XPath.newInstance("//hr:EndDate");
      endDateExpression.addNamespace(namespace);
      nameExpression = XPath.newInstance("concat(//hr:FirstName,' ',//hr:LastName)");
      nameExpression.addNamespace(namespace);
   }
   @PayloadRoot(namespace = NAMESPACE_URI, localPart = "LeaveRequest")                  
   public void handleLeaveRequest(@RequestPayload Element leaveRequest) throws Exception {
      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
      Date startDate = dateFormat.parse(startDateExpression.valueOf(leaveRequest));
      Date endDate = dateFormat.parse(endDateExpression.valueOf(leaveRequest));
      String name = nameExpression.valueOf(leaveRequest);
      humanResourceService.bookLeave(startDate, endDate, name);
   }
}

/WEB_INF/spring-ws-servlet.xml

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:context = "http://www.springframework.org/schema/context"
   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
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   <context:component-scan base-package = "com.example.hr"/>
   <bean id = "humanResourceService"
      class = "com.example.hr.service.HumanResourceServiceImpl" />
   <sws:annotation-driven/>
   <sws:dynamic-wsdl id = "leave"
      portTypeName = "HumanResource"
      locationUri = "/leaveService/"
      targetNamespace = "http://example.com/hr/definitions">
      <sws:xsd location = "/WEB-INF/hr.xsd"/>
   </sws:dynamic-wsdl>
</beans>

/WEB_INF/web.xml

<web-app xmlns = "http://java.sun.com/xml/ns/j2ee"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://java.sun.com/xml/ns/j2ee
   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
   version = "2.4">
   <display-name>Example HR Leave Service</display-name>
   <servlet>
       <servlet-name>spring-ws</servlet-name>
      <servlet-class>
         org.springframework.ws.transport.http.MessageDispatcherServlet
      </servlet-class>
      <init-param>
         <param-name>transformWsdlLocations</param-name>
         <param-value>true</param-value>
      </init-param>
   </servlet>
   <servlet-mapping>
      <servlet-name>spring-ws</servlet-name>
      <url-pattern>/*</url-pattern>
   </servlet-mapping>
</web-app>

/WEB_INF/hr.wsd

<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"
   xmlns:hr = "http://example.com/hr/schemas"
   elementFormDefault = "qualified"
   targetNamespace = "http://example.com/hr/schemas">
   <xs:element name = "LeaveRequest">
      <xs:complexType>
         <xs:all>
            <xs:element name = "Leave" type = "hr:LeaveType"/>
            <xs:element name = "Employee" type = "hr:EmployeeType"/>
         </xs:all>
      </xs:complexType>
   </xs:element>
   <xs:complexType name = "LeaveType">
      <xs:sequence>
         <xs:element name = "StartDate" type = "xs:date"/>
         <xs:element name = "EndDate" type = "xs:date"/>
      </xs:sequence>
   </xs:complexType>
   <xs:complexType name = "EmployeeType">
      <xs:sequence>
         <xs:element name = "Number" type = "xs:integer"/>
         <xs:element name = "FirstName" type = "xs:string"/>
         <xs:element name = "LastName" type = "xs:string"/>
      </xs:sequence>
   </xs:complexType>
</xs:schema>

b. Project Build

Now after creating and writing all the code let’s build the project. Open a command console and go to C:\MVN\leaveService directory and execute the below command:

C:\MVN\leaveService>mvn clean package

Maven will start building the project.
Do you the Jobs & Salary Trends of Spring Framework

c. Import the project in Eclipse

Following are the steps to import the project in Eclipse:

  • Open Eclipse application.
  • Select the option File->Import.
  • Click on Maven Projects option and click on the next button.
  • Select the location of your project.
  • Click the finish button.

d. Run the project

Now your project is ready for execution. Right click on an application and use the option Export->WAR File and save leaveService.war in Tomcat web apps.
Start the Tomcat server and make save you are able to access the other web pages using your browser. Access the URL- http://localhost:8080/leaveService/leave.wsdl.
If there is no problem with your code the Spring Web application will run and you will see the following message in your URL site with document tree:
This XML file does not appear to have any style information associated with it.
So, this was all about Spring Web Services. Hope you like our explanation.

6. Conclusion

Hence, in this session, you learned about the Spring Framework integration with Web Services and its features. You got the detailed knowledge of Spring Web Services with the help of a working example. This session was a step forward for those developers who need more understanding of the Spring Framework and its integration with others. Still, you have a doubt, feel free to ask in the comment section.
See Also- Spring Boot CLI
For reference

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *