How to write Spring Web Services

Spring Web Services
Sprint Web Services

Spring Web Services (Spring-WS) is one of the venture developed by the Spring community. Its prime awareness is to create document-driven net services. The Spring internet services mission helps settlement-first soap service improvement, gives multiple ways to create bendy net services, which could manipulate XML payloads in a couple of ways. Being Spring based, Spring Web Services makes use of Spring concepts like Dependency Injection and Configurations seamlessly. Spring-WS calls for Spring three.zero version.Spring Framework changed into to begin with written by way of Rod Johnson and was first released beneath the Apache 2.zero license in June 2003. This educational has been written primarily based on the Spring Framework version 4.1.6 released in March 2015.

Spring Web Services (Spring-WS) is one of the projects evolved via the Spring community. Its top cognizance is to create file-driven internet services. The Spring internet services task facilitates settlement-first soap provider improvement, affords multiple approaches to create bendy internet services, which could manipulate XML payloads in multiple approaches.

The Spring Web Services makes use of Spring ideas like dependency injection and configurations seamlessly. The Spring-WS calls for Spring three.zero version. With settlement-first development, we begin with WSDL agreement and then will use JAVA to put into effect the specified contract.

as opposed to the agreement-last method where JAVA interfaces generate WSDL/XSD agreement. The WSDL based contract remains impartial of JAVA implementation within the settlement-first method. In case we require changing the JAVA interfaces, then there’s no need to speak the modifications made in the present WSDL settlement to the net services users. Spring-WS ambitions to offer free coupling among the WSDL settlement and its JAVA based implementation.

Features

Following are the features of Spring internet services −

  • XML Mapping to gadgets − XML based totally requests may be mapped to any item using the facts stored within the Message Payload, soap motion Header or through the use of an XPath Expression.
  • Multiple API Support to parse XML − apart from the same old JAXP APIs (DOM, SAX, StAX) to parse the incoming XML requests, other libraries like JDOM, dom4j, XOM are also supported.
  • multiple API support to marshal XML− Spring web services supports JAXB 1 and 2, Castor, XMLBeans, JiBX, and XStream libraries using its object/XML Mapping module. The object/XML Mapping module also can be utilized in non-web services code as nicely.
  • Spring based configurations − Spring internet services uses the Spring software Contexts for its configurations having a similar structure as that of the Spring internet MVC.
  • Integrated WS-security module − the use of the WS-safety module, you could sign, Encrypt, Decrypt cleaning soap Messages or Authenticate them.
  • Support for Acegi safety − the use of the WS-safety implementation of Spring web services, Acegi configuration may be used for your cleaning soap services.

Architecture

The Spring-WS task includes 5 most important modules, that are explained under.

  • Spring-WS core − it’s far the primary module and presents the primary Interfaces like WebServiceMessage and SoapMessage, the server-facet framework, powerful message dispatching functionality and support instructions to put into effect net service endpoints. It additionally affords net carrier patron consumer as WebServiceTemplate.
  • Spring-WS support − This module provides supports for JMS, emails, and so on.
  • Spring-WS security − This module is accountable to offer WS-protection implementation included with center net carrier Module. using this module, we will upload important tokens, sign, encrypt and decrypt cleaning soap messages. This module allows the use of the prevailing Spring security Implementation for authentication and authorization.
  • Spring XML − This module provides XML aid training for Spring internet services. This module is internally used by Spring-WS framework.
  • Spring OXM − This module presents aid training for XML vs object Mapping.

We will understand the process of setting up Spring-WS on Windows and Linux based systems. The Spring-WS can be easily installed and integrated with your current Java environment and MAVEN by following a few simple steps without any complex setup procedures. User administration is required while installation.

Sprint Architecture

System Requirements

The following table lists out the system requirements, while the subsequent steps will guide us through the environment setup procedure.

JDK Java SE 2 JDK 1.5 or above
Memory 1 GB RAM (recommended)
Disk Space No minimum requirement
Operating System Version Windows XP or above, Linux

Let us now proceed with the steps to install Spring-WS.

Step 1: Verify the Java Installation

To begin with, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the following two commands depending on the platform you are working on.

If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table.

Platform Command Sample Output
Windows Open command console and type −

\>java -version

Java version “1.7.0_60”

Java (TM) SE Run Time Environment (build 1.7.0_60-b19)

Java Hotspot (TM) 64-bit Server VM (build 24.60-b09,mixed mode)

Linux Open command terminal and type −

$java -version

java version “1.7.0_25”

Open JDK Runtime Environment (rhel-2.3.10.4.el6_4-x86_64)

Open JDK 64-Bit Server VM (build 23.7-b01, mixed mode)

We assume the readers of this tutorial have Java SDK version 1.7.0_60 installed on their system.

In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed.

Step 2: Set your Java Environment

Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine.

Platform Description
Windows Set JAVA_HOME to C:\ProgramFiles\java\jdk1.7.0_60
Linux Export JAVA_HOME=/usr/local/java-current

Append the full path of Java compiler location to the System Path.

Platform Description
Windows Append the String “C:\Program Files\Java\jdk1.7.0_60\bin” to the end of the system variable PATH.
Linux Export PATH=$PATH:$JAVA_HOME/bin/

Execute the command java -version from the command prompt as explained above.

Step 3: Download Maven archive

Download Maven 3.3.3 from https://maven.apache.org/download.cgi

OS Archive name
Windows apache-maven-3.3.3-bin.zip
Linux apache-maven-3.3.3-bin.tar.gz
Mac apache-maven-3.3.3-bin.tar.gz

Step 4: Extract the Maven archive

Extract the archive, to the directory you wish to install Maven 3.3.3. The subdirectory apache-maven-3.3.3 will be created from the archive.

OS Location
Windows C:\Program Files\Apache Software Foundation\apache-maven-3.3.3
Linux /usr/local/apache-maven
Mac /usr/local/apache-maven

Step 5: Set Maven environment variables

Add M2_HOME, M2 and MAVEN_OPTS to the environment variables.

OS Output
Windows
Set the environment variables using system properties.

M2_HOME=C:\Program Files\Apache Software Foundation\apache-maven-3.3.3

M2=%M2_HOME%\bin

MAVEN_OPTS=-Xms256m -Xmx512m

Linux
Open command terminal and set environment variables.

export M2_HOME=/usr/local/apache-maven/apache-maven-3.3.3

export M2=$M2_HOME/bin

export MAVEN_OPTS=-Xms256m -Xmx512m

Mac
Open command terminal and set environment variables.

export M2_HOME=/usr/local/apache-maven/apache-maven-3.3.3

export M2=$M2_HOME/bin

export MAVEN_OPTS=-Xms256m -Xmx512m

Step 6: Add Maven bin directory location to the system path
Now append M2 variable to the System Path.

OS Output
Windows Append the string ;%M2% to the end of the system variable, Path.
Linux export PATH=$M2:$PATH
Mac export PATH=$M2:$PATH
Step 7: Verify Maven installation
Now open the console, execute the following mvn command.

OS Task Command
Windows Open Command Console c:\> mvn –version
Linux Open Command Terminal $ mvn –version
Mac Open Terminal machine:< joseph$ mvn –version
Finally, verify the output of the above commands, which should be something as shown below −

OS Output
Windows
Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T17:27:37+05:30)

Maven home: C:\Program Files\Apache Software Foundation\apache-maven-3.3.3

Java version: 1.7.0_75, vendor: Oracle Corporation

Java home: C:\Program Files\Java\jdk1.7.0_75\jre

Default locale: en_US, platform encoding: Cp1252

Linux
Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T17:27:37+05:30)

Maven home: /usr/local/apache-maven/apache-maven-3.3.3

Java version: 1.7.0_75, vendor: Oracle Corporation

Java home: /usr/local/java-current/jdk1.7.0_75/jre

Mac
Apache Maven 3.3.3 (7994120775791599e205a5524ec3e0dfe41d4a06; 2015-04-22T17:27:37+05:30)

Maven home: /usr/local/apache-maven/apache-maven-3.3.3

Java version: 1.7.0_75, vendor: Oracle Corporation

Java home: /Library/Java/Home/jdk1.7.0_75/jre

Step 8: Setup Eclipse IDE
All the examples in this tutorial have been written using the Eclipse IDE. It is recommended that the readers should have the latest version of Eclipse installed on their machine. To install the Eclipse IDE, download the latest Eclipse binaries from the following link https://www.eclipse.org/downloads/. Once the installation is downloaded, unpack the binary distribution into a convenient location.

For example in C:\eclipse on windows, or /usr/local/eclipse on Linux/Unix and finally set the PATH variable appropriately. Eclipse can be started by executing the following commands on the windows machine, or you can simply double click on eclipse.exe.

%C:\eclipse\eclipse.exe
Eclipse can be started by executing the following commands on the UNIX (Solaris, Linux, etc.) machine −

$/usr/local/eclipse/eclipse
After a successful startup, if everything is fine then it should display the following screen −

Eclipse Home page
Step 9: Setup Apache Tomcat
We can download the latest version of Tomcat from https://tomcat.apache.org/. Once the installation is downloaded, unpack the binary distribution into a convenient location. For example in the C:\apache-tomcat-7.0.59 on a windows machine, or in the /usr/local/apache-tomcat-7.0.59 on a Linux/Unix machine and then set the CATALINA_HOME environment variable pointing to the installation locations.

Tomcat can be started by executing the following commands on a windows machine, or you can simply double click on startup.bat

%CATALINA_HOME%\bin\startup.bat

or

C:\apache-tomcat-7.0.59\bin\startup.bat
Tomcat can be started by executing the following commands on UNIX (Solaris, Linux, etc.) machine −

$CATALINA_HOME/bin/startup.sh

or

/usr/local/apache-tomcat-7.0.59/bin/startup.sh
After a successful startup, the default web applications included with Tomcat will be available by visiting – http://localhost:8080/. If everything is ok, then it should display the following screen −

Tomcat
Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat website − https://tomcat.apache.org

Tomcat can be stopped by executing the following commands on a windows machine −

%CATALINA_HOME%\bin\shutdown

or

C:\apache-tomcat-7.0.59\bin\shutdown
Tomcat can be stopped by executing the following commands on the UNIX (Solaris, Linux, etc.) machine −

$CATALINA_HOME/bin/shutdown.sh

or

/usr/local/apache-tomcat-7.0.59/bin/shutdown.sh
Once we are done with this last step, we are ready to proceed for the first Web Services Example

Let us start writing an actual SOAP based web service with Spring-WS Framework. Before we start writing our first example using the Spring-WS framework, we have to ensure that the Spring-WS environment is setup properly as explained in Spring Web Services – Environment Setup chapter. We are assuming that the readers have some basic working knowledge with the Eclipse IDE.

Therefore, let us proceed to write a simple Spring WS Application which will expose a web service method to book a leave in an HR Portal.

Contract-first Approach
Spring-WS uses the Contract-first approach, which means we should have our XML Structures ready before writing any JAVA based implementation code. We are defining a LeaveRequest Object, which has sub-objects – Leave and Employee.

Following are the required XML constructs −

Leave.xml

2016-07-03
2016-07-07

Employee.xml

404
Mahesh
Parashar

LeaveRequest.xml

2016-07-03
2016-07-07

404
Mahesh
Parashar

hr.xsd

 

 

Create the Project
Let us now open a command console, go the C:\MVN directory and execute the following mvn command.

C:\MVN>mvn archetype:generate -DarchetypeGroupId = org.springframework.ws
-DarchetypeArtifactId = spring-ws-archetype -DgroupId = com.striveteach.hr
-DartifactId = leaveService
Maven will start processing and will create the complete Java Application Project Structure.

[INFO] Scanning for projects…
[INFO]
[INFO] ————————————————————————
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ————————————————————————
[INFO]
[INFO] Using property: groupId = com.striveteach.hr
[INFO] Using property: artifactId = leaveService
Define value for property ‘version’: 1.0-SNAPSHOT: :
[INFO] Using property: package = com.striveteach.hr
Confirm properties configuration:
groupId: com.striveteach.hr
artifactId: leaveService
version: 1.0-SNAPSHOT
package: com.striveteach.hr
Y: :
[INFO] ————————————————————————-

[INFO] Using following parameters for creating project from Old (1.x) Archetype:
spring-ws-archetype:2.0.0-M1
[INFO] ————————————————————————-

[INFO] Parameter: groupId, Value: com.striveteach.hr
[INFO] Parameter: packageName, Value: com.striveteach.hr
[INFO] Parameter: package, Value: com.striveteach.hr
[INFO] Parameter: artifactId, Value: leaveService
[INFO] Parameter: basedir, Value: C:\mvn
[INFO] Parameter: version, Value: 1.0-SNAPSHOT
[INFO] project created from Old (1.x) Archetype in dir: C:\mvn\leaveService
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————
[INFO] Total time: 35.989 s
[INFO] Finished at: 2017-01-21T11:18:31+05:30
[INFO] Final Memory: 17M/178M
[INFO] ————————————————————————
Now go to C:/MVN directory. We will see a java application project created named leaveService (as specified in artifactId). Update the pom.xml and add HumanResourceService.java and HumanResourceServiceImpl.java in the following folder – C:\MVN\leaveService\src\main\java\com\striveteach\hr\service folder. Once that is done, then add LeaveEndpoint.java in the following folder – C:\MVN\leaveService\src\main\java\com\striveteach\hr\ws folder.

pom.xml

4.0.0
com.striveteach.hr
leaveService
war 1.0-SNAPSHOT
leaveService Spring-WS Application
http://www.springframework.org/spring-ws

leaveService

org.springframework.ws
spring-ws-core
2.4.0.RELEASE

jdom
jdom
1.0

jaxen
jaxen
1.1

wsdl4j
wsdl4j
1.6.2

HumanResourceService.java
package com.striveteach.hr.service;

import java.util.Date;

public interface HumanResourceService {
void bookLeave(Date startDate, Date endDate, String name);
}
HumanResourceServiceImpl.java
package com.striveteach.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.striveteach.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.striveteach.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://striveteach.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

 

/WEB-INF/web.xml

striveteach HR Leave Service

spring-ws

org.springframework.ws.transport.http.MessageDispatcherServlet

transformWsdlLocations true

spring-ws
/*

/WEB-INF/hr.xsd

 

 

Build the Project
Let us now open the command console, go the C:\MVN\leaveService directory and execute the following mvn command.

C:\MVN\leaveService>mvn clean package
Maven will start building the project.

[INFO] Scanning for projects…
[INFO]
[INFO] ————————————————————————
[INFO] Building leaveService Spring-WS Application 1.0-SNAPSHOT
[INFO] ————————————————————————
[INFO]
[INFO] — maven-clean-plugin:2.5:clean (default-clean) @ leaveService —
[INFO] Deleting C:\mvn\leaveService\target
[INFO]
[INFO] — maven-resources-plugin:2.6:resources (default-resources) @ leaveServi
ce —
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] Copying 0 resource
[INFO]
[INFO] — maven-compiler-plugin:3.1:compile (default-compile) @ leaveService —

[INFO] Changes detected – recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e. b
uild is platform dependent!
[INFO] Compiling 3 source files to C:\mvn\leaveService\target\classes
[INFO]
[INFO] — maven-resources-plugin:2.6:testResources (default-testResources) @ le
aveService —
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\mvn\leaveService\src\test\resource
s
[INFO]
[INFO] — maven-compiler-plugin:3.1:testCompile (default-testCompile) @ leaveSe
rvice —
[INFO] No sources to compile
[INFO]
[INFO] — maven-surefire-plugin:2.12.4:test (default-test) @ leaveService —
[INFO] No tests to run.
[INFO]
[INFO] — maven-war-plugin:2.2:war (default-war) @ leaveService —
[INFO] Packaging webapp
[INFO] Assembling webapp [leaveService] in [C:\mvn\leaveService\target\leaveServ
ice]
[INFO] Processing war project
[INFO] Copying webapp resources [C:\mvn\leaveService\src\main\webapp]
[INFO] Webapp assembled in [7159 msecs]
[INFO] Building war: C:\mvn\leaveService\target\leaveService.war
[INFO] WEB-INF\web.xml already added, skipping
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————
[INFO] Total time: 19.667 s
[INFO] Finished at: 2017-01-21T11:56:43+05:30
[INFO] Final Memory: 18M/173M
[INFO] ————————————————————————
Import Project in Eclipse
Follow the steps given below to import the project in Eclipse.

Open Eclipse.

Select File → Import → option.

Select Maven Projects Option. Click on Next Button.

Select Project location, where leaveService project was created using Maven.

Click Finish Button.

Run the Project
Once we are done with creating source and configuration files, export the application. Right click on the application, use Export → WAR File option and save the leaveService.war file in Tomcat’s webapps folder.

Start the Tomcat server and ensure we are able to access other webpages from the webapps folder using a standard browser. Try to access the URL – http://localhost:8080/leaveService/leave.wsdl,

Related Articles:

    StriveBlue Home | Health-Choomandrakaali

    Post Author: Tech Siddha