Spring Web Services Tutorial For Beginners | Spring WS Integration
Job-ready Online Courses: Click for Success - 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.
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:
- 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:
- 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.
- 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>
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
Did you like our efforts? If Yes, please give DataFlair 5 Stars on Google