Spring WS - 快速指南
Spring WS - Overview
Spring Web Services(Spring-WS)是Spring社区开发的项目之一。 其主要重点是创建文档驱动的Web服务。 Spring Web Services项目促进了契约优先的SOAP Service Development ,提供了多种创建灵活Web服务的方法,可以通过多种方式处理XML有效负载。
Spring Web服务无缝地使用依赖注入和配置等Spring概念。 Spring-WS需要Spring 3.0版本。 通过契约优先开发,我们从WSDL Contract开始,然后使用JAVA来实现所需的合同。
与JAVA接口生成WSDL/XSD契约的契约最后方法相反。 基于WSDL的合同在合同优先方法中仍然独立于JAVA实施。 如果我们需要更改JAVA接口,则无需将现有WSDL合同中所做的更改传达给Web服务用户。 Spring-WS旨在提供WSDL契约与基于JAVA的实现之间的松散耦合。
特点 (Features)
以下是Spring Web Services的功能 -
XML Mapping to Objects - 可以使用Message Payload,SOAP Action Header中存储的信息或使用XPath Expression将基于XML的请求映射到任何对象。
Multiple API Support to parse XML - 除了用于解析传入XML请求的标准JAXP API(DOM,SAX,StAX)之外,还支持其他库,如JDOM,dom4j,XOM。
Multiple API Support to marshal XML - Spring Web Services使用其Object/XML Mapping模块支持JAXB 1和2,Castor,XMLBeans,JiBX和XStream库。 Object/XML Mapping模块也可以用在非Web服务代码中。
Spring based configurations - Spring Web Services将Spring Application Contexts用于具有与Spring Web MVC类似的体系结构的配置。
Integrated WS-Security module - 使用WS-Security模块,您可以签名,加密,解密SOAP消息或对其进行身份验证。
Support for Acegi Security - 使用Spring Web Services的WS-Security实现,Acegi配置可用于您的SOAP服务。
结构 (Architecture)
Spring-WS项目由五个主要模块组成,下面将对其进行说明。
Spring-WS Core - 它是主要模块,提供WebServiceMessage和SoapMessage等中央接口,服务器端框架,强大的消息调度功能以及实现Web服务端点的支持类。 它还提供Web Service使用者客户端作为WebServiceTemplate 。
Spring-WS Support - 该模块为JMS,电子邮件等提供支持。
Spring-WS Security - 该模块负责提供与核心Web服务模块集成的WS-Security实现。 使用此模块,我们可以添加主要令牌,签名,加密和解密SOAP消息。 此模块允许使用现有的Spring Security Implementation进行身份验证和授权。
Spring XML - 此模块为Spring Web Services提供XML支持类。 该模块由Spring-WS框架内部使用。
Spring OXM - 此模块提供XML与对象映射的支持类。
Spring WS - Environment Setup
在本章中,我们将了解在基于Windows和Linux的系统上设置Spring-WS的过程。 Spring-WS可以通过几个简单的步骤轻松安装并与您当前的Java environment和MAVEN集成,而无需任何复杂的设置过程。 安装时需要用户管理。
系统需求 (System Requirements)
下表列出了系统要求,后续步骤将指导我们完成环境设置过程。
JDK | Java SE 2 JDK 1.5或以上版本 |
Memory | 1 GB RAM(推荐) |
磁盘空间 | 没有最低要求 |
操作系统版本 | Windows XP或更高版本,Linux |
现在让我们继续安装Spring-WS的步骤。
第1步:验证Java安装
首先,您需要在系统上安装Java软件开发工具包(SDK)。 要验证这一点,请根据您正在使用的平台执行以下两个命令中的任何一个。
如果Java安装已正确完成,那么它将显示Java安装的当前版本和规范。 下表给出了示例输出。
平台 | 命令 | 样本输出 |
---|---|---|
Windows | 打开命令控制台并输入 - \> java -version | Java版“1.7.0_60” Java(TM)SE运行时环境(版本1.7.0_60-b19) Java Hotspot(TM)64位服务器VM(内置24.60-b09,混合模式) |
Linux | 打开命令终端并输入 - $ java -version | java版“1.7.0_25” 打开JDK运行时环境(rhel-2.3.10.4.el6_4-x86_64) 打开JDK 64位服务器VM(内置23.7-b01,混合模式) |
我们假设本教程的读者在他们的系统上安装了Java SDK版本1.7.0_60。
如果您没有Java SDK,请从https://www.oracle.com/technetwork/java/javase/downloads/index.html下载其当前版本并安装它。
第2步:设置Java环境
将环境变量JAVA_HOME为指向计算机上安装Java的基本目录位置。
S.No. | 平台和描述 |
---|---|
1 | Windows 将JAVA_HOME设置为C:\ProgramFiles\java\jdk1.7.0_60 |
2 | Linux 导出JAVA_HOME =/usr/local/java-current |
将Java编译器位置的完整路径附加到系统路径。
S.No. | 平台和描述 |
---|---|
1 | Windows 将字符串“C:\Program Files\Java\jdk1.7.0_60\bin”附加到系统变量PATH的末尾。 |
2 | Linux 导出PATH = $ PATH:$ JAVA_HOME/bin/ |
如上所述,从命令提示符执行命令java -version 。
第3步:下载Maven存档
从https://maven.apache.org/download.cgi下载Maven 3.3.3
OS | 存档名称 |
---|---|
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 |
第4步:提取Maven存档
将存档解压缩到要安装Maven 3.3.3的目录。 将从存档创建子目录apache-maven-3.3.3。
OS | 位置(根据您的安装可能会有所不同) |
---|---|
Windows | C:\Program Files\Apache Software Foundation\apache-maven-3.3.3 |
Linux | /usr/local/apache-maven |
Mac | /usr/local/apache-maven |
第5步:设置Maven环境变量
将M2_HOME,M2和MAVEN_OPTS添加到环境变量中。
OS | output |
---|---|
Windows | 使用系统属性设置环境变量。 M2_HOME = C:\Program Files\Apache Software Foundation\apache-maven-3.3.3 M2 =%M2_HOME%\ bin中 MAVEN_OPTS = -Xms256m -Xmx512m |
Linux | 打开命令终端并设置环境变量。 export M2_HOME =/usr/local/apache-maven/apache-maven-3.3.3 出口M2 = $ M2_HOME/bin 导出MAVEN_OPTS = -Xms256m -Xmx512m |
Mac | 打开命令终端并设置环境变量。 export M2_HOME =/usr/local/apache-maven/apache-maven-3.3.3 出口M2 = $ M2_HOME/bin 导出MAVEN_OPTS = -Xms256m -Xmx512m |
步骤6:将Maven bin目录位置添加到系统路径
现在将M2变量附加到系统路径。
OS | output |
---|---|
Windows | 将字符串;%M2%附加到系统变量Path的末尾。 |
Linux | export PATH = $ M2:$ PATH |
Mac | export PATH = $ M2:$ PATH |
第7步:验证Maven安装
现在打开控制台,执行以下mvn命令。
OS | 任务 | 命令 |
---|---|---|
Windows | 打开命令控制台 | c:\> mvn --version |
Linux | 打开命令终端 | $ mvn --version |
Mac | 开放式终端 | 机器: |
最后,验证上述命令的输出,这些命令应如下所示 -
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版本:1.7.0_75,供应商:Oracle Corporation Java home:C:\Program Files\Java\jdk1.7.0_75\jre 默认语言环境:en_US,平台编码: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版本:1.7.0_75,供应商: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版本:1.7.0_75,供应商:Oracle Corporation Java home:/Library/Java/Home/jdk1.7.0_75/jre |
第8步:安装Eclipse IDE
本教程中的所有示例都是使用Eclipse IDE编写的。 建议读者在其计算机上安装最新版本的Eclipse。 要安装Eclipse IDE,请从以下链接https://www.eclipse.org/downloads/下载最新的Eclipse二进制文件。 下载安装后,将二进制分发包解压缩到方便的位置。
例如,在Windows上的C:\eclipse或Linux/Unix上的/usr/local/eclipse ,最后适当地设置PATH变量。 可以通过在Windows机器上执行以下命令来启动Eclipse,或者只需双击eclipse.exe即可。
%C:\eclipse\eclipse.exe
可以通过在UNIX(Solaris,Linux等)计算机上执行以下命令来启动Eclipse -
$/usr/local/eclipse/eclipse
成功启动后,如果一切正常,那么它应显示以下屏幕 -
第9步:设置Apache Tomcat
我们可以从https://tomcat.apache.org/下载最新版本的Tomcat。 下载安装后,将二进制分发包解压缩到方便的位置。 例如,在Windows机器上的C:\apache-tomcat-7.0.59 ,或在Linux/Unix机器上的/usr/local/apache-tomcat-7.0.59 ,然后设置CATALINA_HOME环境变量指向安装地点。
可以通过在Windows机器上执行以下命令来启动Tomcat,也可以只需双击startup.bat即可
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-7.0.59\bin\startup.bat
可以通过在UNIX(Solaris,Linux等)机器上执行以下命令来启动Tomcat -
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-7.0.59/bin/startup.sh
成功启动后,Tomcat附带的默认Web应用程序将通过访问 - http://localhost:8080/ 。 如果一切正常,那么它应该显示以下屏幕 -
有关配置和运行Tomcat的更多信息,请参阅此处包含的文档以及Tomcat网站 - https://tomcat.apache.org
可以通过在Windows机器上执行以下命令来停止Tomcat -
%CATALINA_HOME%\bin\shutdown
or
C:\apache-tomcat-7.0.59\bin\shutdown
可以通过在UNIX(Solaris,Linux等)计算机上执行以下命令来停止Tomcat -
$CATALINA_HOME/bin/shutdown.sh
or
/usr/local/apache-tomcat-7.0.59/bin/shutdown.sh
完成最后一步后,我们准备继续进行第一个Web服务示例,我们将在下一章中讨论。
Spring WS - First Application
让我们开始使用Spring-WS Framework编写一个基于SOAP的实际Web服务。 在我们开始使用Spring-WS框架编写第一个示例之前,我们必须确保正确设置Spring-WS环境,如Spring Web Services - Environment Setup一章中所述。 我们假设读者具有Eclipse IDE的一些基本工作知识。
因此,让我们继续编写一个简单的Spring WS应用程序,它将公开一个Web服务方法来预订HR门户中的休假。
Contract-first Approach
Spring-WS使用契约优先方法,这意味着我们应该在编写任何基于JAVA的实现代码之前准备好XML Structures 。 我们正在定义一个LeaveRequest对象,它有子对象 - Leave和Employee。
以下是必需的XML构造 -
Leave.xml
<Leave xmlns = "http://iowiki.com/hr/schemas">
<StartDate>2016-07-03</StartDate>
<EndDate>2016-07-07</EndDate>
</Leave>
Employee.xml
<Employee xmlns = "http://iowiki.com/hr/schemas">
<Number>404</Number>
<FirstName>Mahesh</FirstName>
<LastName>Parashar</LastName>
</Employee>
LeaveRequest.xml
<LeaveRequest xmlns = "http://iowiki.com/hr/schemas">
<Leave>
<StartDate>2016-07-03</StartDate>
<EndDate>2016-07-07</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://iowiki.com/hr/schemas"
elementFormDefault = "qualified"
targetNamespace = "http://iowiki.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>
创建项目
现在让我们打开命令控制台,转到C:\MVN目录并执行以下mvn命令。
C:\MVN>mvn archetype:generate -DarchetypeGroupId = org.springframework.ws
-DarchetypeArtifactId = spring-ws-archetype -DgroupId = com.iowiki.hr
-DartifactId = leaveService
Maven将开始处理并将创建完整的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.iowiki.hr
[INFO] Using property: artifactId = leaveService
Define value for property 'version': 1.0-SNAPSHOT: :
[INFO] Using property: package = com.iowiki.hr
Confirm properties configuration:
groupId: com.iowiki.hr
artifactId: leaveService
version: 1.0-SNAPSHOT
package: com.iowiki.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.iowiki.hr
[INFO] Parameter: packageName, Value: com.iowiki.hr
[INFO] Parameter: package, Value: com.iowiki.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] ------------------------------------------------------------------------
现在转到C:/MVN目录。 我们将看到一个名为leaveService的java应用程序项目(在artifactId中指定)。 更新pom.xml并在以下文件夹中添加HumanResourceService.java和HumanResourceServiceImpl.java - C:\MVN\leaveService\src\main\java\com\iowiki\hr\service文件夹。 完成后,将LeaveEndpoint.java添加到以下文件夹中 - C:\MVN\leaveService\src\main\java\com\iowiki\hr\ws文件夹。
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.iowiki.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.iowiki.hr.service;
import java.util.Date;
public interface HumanResourceService {
void bookLeave(Date startDate, Date endDate, String name);
}
HumanResourceServiceImpl.java
package com.iowiki.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.iowiki.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.iowiki.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://iowiki.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.iowiki.hr"/>
<bean id = "humanResourceService"
class = "com.iowiki.hr.service.HumanResourceServiceImpl" />
<sws:annotation-driven/>
<sws:dynamic-wsdl id = "leave"
portTypeName = "HumanResource"
locationUri = "/leaveService/"
targetNamespace = "http://iowiki.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>IoWiki 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.xsd
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"
xmlns:hr = "http://iowiki.com/hr/schemas"
elementFormDefault = "qualified"
targetNamespace = "http://iowiki.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>
构建项目 (Build the Project)
现在让我们打开命令控制台,转到C:\MVN\leaveService目录并执行以下mvn命令。
C:\MVN\leaveService>mvn clean package
Maven将开始构建该项目。
[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] ------------------------------------------------------------------------
在Eclipse中导入项目
按照下面给出的步骤在Eclipse中导入项目。
打开Eclipse。
选择File → Import →选项。
选择Maven项目选项。 单击“下一步”按钮。
选择项目位置,其中使用Maven创建了leaveService project 。
单击完成按钮。
运行项目
完成创建源文件和配置文件后,导出应用程序。 右键单击应用程序,使用Export→WAR File选项并将leaveService.war文件保存在Tomcat的webapps文件夹中。
启动Tomcat服务器并确保我们能够使用标准浏览器从webapps文件夹访问其他网页。 尝试访问URL - http:// localhost:8080/leaveService/leave.wsdl,如果Spring Web Application一切正常,我们应该看到以下屏幕。
Spring WS - Static WSDL
在上一章Spring -WS - First Application中 ,我们使用Spring WS Configuration自动生成了WSDL。 在这种情况下,我们将展示如何使用Spring WS公开现有的WSDL。
步 | 描述 |
---|---|
1 | 在Spring WS-First Application章节中解释,在com.iowiki包下创建一个名为leaveService的项目。 |
2 | 在/ WEB-INF/wsdl子文件夹下创建WSDL leave.wsdl。 |
3 | 更新/ WEB-INF子文件夹下的spring-ws-servlet.xml。 我们在这里使用static-wsdl标记而不是dynamic-wsdl。 |
4 | 最后一步是创建所有源文件和配置文件的内容,并导出应用程序,如下所述。 |
/WEB-INF/spring-ws-servlet.xml
<wsdl:definitions xmlns:wsdl = "http://schemas.xmlsoap.org/wsdl/"
xmlns:soap = "http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:schema = "http://iowiki.com/hr/schemas"
xmlns:tns = "http://iowiki.com/hr/definitions"
targetNamespace = "http://iowiki.com/hr/definitions">
<wsdl:types>
<xsd:schema xmlns:xsd = "http://www.w3.org/2001/XMLSchema">
<xsd:import namespace = "http://iowiki.com/hr/schemas"
schemaLocation = "hr.xsd"/>
</xsd:schema>
</wsdl:types>
<wsdl:message name = "LeaveRequest">
<wsdl:part element = "schema:LeaveRequest" name = "LeaveRequest"/>
</wsdl:message>
<wsdl:portType name = "HumanResource">
<wsdl:operation name = "Leave">
<wsdl:input message = "tns:LeaveRequest" name = "LeaveRequest"/>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name = "HumanResourceBinding" type = "tns:HumanResource">
<soap:binding style = "document"
transport = "http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name = "Leave">
<soap:operation soapAction = "http://mycompany.com/RequestLeave"/>
<wsdl:input name = "LeaveRequest">
<soap:body use = "literal"/>
</wsdl:input>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name = "HumanResourceService">
<wsdl:port binding = "tns:HumanResourceBinding" name = "HumanResourcePort">
<soap:address location = "http://localhost:8080/leaveService/"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
/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.iowiki.hr"/>
<sws:annotation-driven/>
<sws:static-wsdl id = "leave" location = "/WEB-INF/wsdl/leave.wsdl"/>
</beans>
运行项目
完成创建源文件和配置文件后,我们应该导出应用程序。 右键单击应用程序,使用Export→WAR File选项并将leaveService.war文件保存在Tomcat的webapps文件夹中。
现在,启动Tomcat服务器并确保我们可以使用标准浏览器从webapps文件夹访问其他网页。 尝试访问URL - http:// localhost:8080/leaveService/leave.wsdl,如果Spring Web Application一切正常,我们将看到以下屏幕。
Spring WS - Writing Server
在本章中,我们将了解如何使用Spring WS创建Web应用程序服务器。
步 | 描述 |
---|---|
1 | 在Spring WS-First Application章节中解释,在com.iowiki包下创建一个名为countryService的项目。 |
2 | 按照以下步骤中的说明创建countries.xsd,域类,CountryRepository和CountryEndPoint。 |
3 | 更新/ WEB-INF子文件夹下的spring-ws-servlet.xml。 |
4 | 最后一步是为所有源文件和配置文件创建内容并导出应用程序,如下所述。 |
countries.xsd
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema"
xmlns:tns = "http://iowiki/schemas"
targetNamespace = "http://iowiki/schemas"
elementFormDefault = "qualified">
<xs:element name = "getCountryRequest">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name = "getCountryResponse">
<xs:complexType>
<xs:sequence>
<xs:element name = "country" type = "tns:country"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name = "country">
<xs:sequence>
<xs:element name = "name" type = "xs:string"/>
<xs:element name = "population" type = "xs:int"/>
<xs:element name = "capital" type = "xs:string"/>
<xs:element name = "currency" type = "tns:currency"/>
</xs:sequence>
</xs:complexType>
<xs:simpleType name = "currency">
<xs:restriction base = "xs:string">
<xs:enumeration value = "GBP"/>
<xs:enumeration value = "USD"/>
<xs:enumeration value = "INR"/>
</xs:restriction>
</xs:simpleType>
</xs:schema>
创建项目
让我们打开命令控制台,转到C:\MVN目录并执行以下mvn命令。
C:\MVN>mvn archetype:generate -DarchetypeGroupId = org.springframework.ws
-DarchetypeArtifactId = spring-ws-archetype -DgroupId = com.iowiki
-DartifactId = countryService
Maven将开始处理并将创建完整的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.iowiki
[INFO] Using property: artifactId = countryService
Define value for property 'version': 1.0-SNAPSHOT: :
[INFO] Using property: package = com.iowiki
Confirm properties configuration:
groupId: com.iowiki
artifactId: countryService
version: 1.0-SNAPSHOT
package: com.iowiki
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.iowiki
[INFO] Parameter: packageName, Value: com.iowiki
[INFO] Parameter: package, Value: com.iowiki
[INFO] Parameter: artifactId, Value: countryService
[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\countryService
[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] ------------------------------------------------------------------------
现在转到C:/ MVN目录。 我们将看到一个名为countryService的java应用程序项目(在artifactId中指定)。 更新pom.xml。
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.iowiki.hr</groupId>
<artifactId>countryService</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>countryService Spring-WS Application</name>
<url>http://www.springframework.org/spring-ws</url>
<build>
<finalName>countryService</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>
创建域类
将countries.xsd复制到C:\mvn\countryService\src\main\resources文件夹中。 让我们打开命令控制台,转到C:\mvn\countryService\src\main\resources目录并执行以下xjc命令以使用countries.xsd生成域类。
C:\MVN\countryService\src\main\resources>xjc -p com.iowiki countries.xsd
Maven将开始处理并将在com.iowiki包中创建域类。
parsing a schema...
compiling a schema...
com\iowiki\Country.java
com\iowiki\Currency.java
com\iowiki\GetCountryRequest.java
com\iowiki\GetCountryResponse.java
com\iowiki\ObjectFactory.java
com\iowiki\package-info.java
在C:\mvn\countryService\src\main文件夹中创建文件夹java。 复制C:\mvn\countryService\src\main\java文件夹中的所有类。 创建CountryRepository和CountryEndPoint分别表示国家/地区数据库和国家/地区服务器。
CountryRepository.java
package com.iowiki;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.propertyeditors.CurrencyEditor;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
@Component
public class CountryRepository {
private static final List<Country> countries = new ArrayList<Country>();
public CountryRepository(){
initData();
}
public void initData() {
Country us = new Country();
us.setName("United States");
us.setCapital("Washington");
us.setCurrency(Currency.USD);
us.setPopulation(46704314);
countries.add(us);
Country india = new Country();
india.setName("India");
india.setCapital("New Delhi");
india.setCurrency(Currency.INR);
india.setPopulation(138186860);
countries.add(india);
Country uk = new Country();
uk.setName("United Kingdom");
uk.setCapital("London");
uk.setCurrency(Currency.GBP);
uk.setPopulation(63705000);
countries.add(uk);
}
public Country findCountry(String name) {
Assert.notNull(name);
Country result = null;
for (Country country : countries) {
if (name.trim().equals(country.getName())) {
result = country;
}
}
return result;
}
}
CountryEndPoint.java
package com.iowiki.ws;
import org.jdom.JDOMException;
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 org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import com.iowiki.Country;
import com.iowiki.CountryRepository;
import com.iowiki.GetCountryRequest;
import com.iowiki.GetCountryResponse;
@Endpoint
public class CountryEndPoint {
private static final String NAMESPACE_URI = "http://iowiki/schemas";
private CountryRepository countryRepository;
@Autowired
public CountryEndPoint(CountryRepository countryRepository) throws JDOMException {
this.countryRepository = countryRepository;
}
@PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest")
@ResponsePayload
public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request)
throws JDOMException {
Country country = countryRepository.findCountry(request.getName());
GetCountryResponse response = new GetCountryResponse();
response.setCountry(country);
return response;
}
}
/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.iowiki"/>
<sws:annotation-driven/>
<sws:dynamic-wsdl id="countries"
portTypeName = "CountriesPort"
locationUri = "/countryService/"
targetNamespace = "http://iowiki.com/definitions">
<sws:xsd location = "/WEB-INF/countries.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>IoWiki Country 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>
构建项目 (Build the Project)
让我们打开命令控制台。 转到C:\MVN\countryService目录并执行以下mvn命令。
C:\MVN\countryService>mvn clean package
Maven将开始构建该项目。
INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building countryService Spring-WS Application 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-clean-plugin:2.5:clean (default-clean) @ countryService ---
[INFO] Deleting C:\mvn\countryService\target
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ countrySer
vice ---
[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) @ countryService
---
[INFO] Changes detected - recompiling the module!
[WARNING] File encoding has not been set, using platform encoding Cp1252, i.e.
build is platform dependent!
[INFO] Compiling 4 source files to C:\mvn\countryService\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ co
untryService ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\mvn\countryService\src\test\resour
ces
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ country
Service ---
[INFO] No sources to compile
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ countryService ---
[INFO] No tests to run.
[INFO]
[INFO] --- maven-war-plugin:2.2:war (default-war) @ countryService ---
[INFO] Packaging webapp
[INFO] Assembling webapp [countryService] in [C:\mvn\countryService\target\count
ryService]
[INFO] Processing war project
[INFO] Copying webapp resources [C:\mvn\countryService\src\main\webapp]
[INFO] Webapp assembled in [5137 msecs]
[INFO] Building war: C:\mvn\countryService\target\countryService.war
[INFO] WEB-INF\web.xml already added, skipping
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 16.484 s
[INFO] Finished at: 2017-01-28T09:07:59+05:30
[INFO] Final Memory: 19M/170M
[INFO] ------------------------------------------------------------------------
运行项目
创建源文件和配置文件后,将countryService.war文件导出到Tomcat的webapps文件夹中。
现在,启动Tomcat服务器并确保我们是否可以使用标准浏览器从webapps文件夹访问其他网页。 对URL发出POST请求 - http:// localhost:8080/countryService /并使用任何SOAP客户端发出以下请求。
<x:Envelope xmlns:x = "http://schemas.xmlsoap.org/soap/envelope/"
xmlns:tns = "http://iowiki/schemas">
<x:Header/>
<x:Body>
<tns:getCountryRequest>
<tns:name>United States</tns:name>
</tns:getCountryRequest>
</x:Body>
</x:Envelope>
您将看到以下结果。
<SOAP-ENV:Envelope xmlns:SOAP-ENV = "http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns2:getCountryResponse xmlns:ns2 = "http://iowiki/schemas">
<ns2:country>
<ns2:name>United States</ns2:name>
<ns2:population>46704314</ns2:population>
<ns2:capital>Washington</ns2:capital>
<ns2:currency>USD</ns2:currency>
</ns2:country>
</ns2:getCountryResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Spring WS - Unit Test Server
在本章中,我们将了解如何对使用Spring WS创建的Web应用程序服务进行单元测试。
步 | 描述 |
---|---|
1 | 更新在Spring WS - Write Server章节中创建的项目countryService。 添加src/test/java文件夹。 |
2 | 在-src/test/java/com/iowiki/ws文件夹下创建CustomerEndPointTest.java,然后更新POM.xml,如下所述。 |
3 | 在src/main/resources子文件夹下添加spring-context.xml。 |
4 | 最后一步是为所有源文件和配置文件创建内容并测试应用程序,如下所述。 |
的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.iowiki</groupId>
<artifactId>countryService</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>countryService Spring-WS Application</name>
<url>http://www.springframework.org/spring-ws</url>
<build>
<finalName>countryService</finalName>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-core</artifactId>
<version>2.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-test</artifactId>
<version>2.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.1.2.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>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.5</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
spring-context.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.iowiki"/>
<sws:annotation-driven/>
<bean id = "schema" class = "org.springframework.core.io.ClassPathResource">
<constructor-arg index = "0" value = "countries.xsd" />
</bean>
</beans>
CustomerEndPointTest.java
package com.iowiki.ws;
import javax.xml.transform.Source;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.ws.test.server.MockWebServiceClient;
import org.springframework.xml.transform.StringSource;
import static org.springframework.ws.test.server.RequestCreators.withPayload;
import static org.springframework.ws.test.server.ResponseMatchers.payload;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration( locations = "/spring-context.xml" )
public class CustomerEndPointTest {
@Autowired
private ApplicationContext applicationContext;
private MockWebServiceClient mockClient;
@Before
public void createClient() {
mockClient = MockWebServiceClient.createClient(applicationContext);
GenericApplicationContext ctx = (GenericApplicationContext) applicationContext;
final XmlBeanDefinitionReader definitionReader = new XmlBeanDefinitionReader(ctx);
definitionReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);
definitionReader.setNamespaceAware(true);
}
@Test
public void testCountryEndpoint() throws Exception {
Source requestPayload = new StringSource(
"<getCountryRequest xmlns = 'http://iowiki/schemas'>"+
"<name>United States</name>"+
"</getCountryRequest>");
Source responsePayload = new StringSource(
"<getCountryResponse xmlns='http://iowiki/schemas'>" +
"<country>" +
"<name>United States</name>"+
"<population>46704314</population>"+
"<capital>Washington</capital>"+
"<currency>USD</currency>"+
"</country>"+
"</getCountryResponse>");
mockClient.sendRequest(withPayload(requestPayload)).andExpect(payload(responsePayload));
}
}
构建项目 (Build the Project)
让我们打开命令控制台,转到C:\MVN\countryService目录并执行以下mvn命令。
C:\MVN\countryService>mvn test
Maven将开始构建和测试项目。
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building countryService Spring-WS Application 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ countrySer
vice ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ countryService
---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ co
untryService ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\countryService\src\test\resour
ces
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ country
Service ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ countryService ---
[INFO] Surefire report directory: C:\MVN\countryService\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.iowiki.ws.CustomerEndPointTest
Feb 27, 2017 11:49:30 AM org.springframework.test.context.TestContextManager ret
rieveTestExecutionListeners
INFO: @TestExecutionListeners is not present for class [class com.iowiki
.ws.CustomerEndPointTest]: using defaults.
Feb 27, 2017 11:49:30 AM org.springframework.beans.factory.xml.XmlBeanDefinition
Reader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-context.xml]
Feb 27, 2017 11:49:30 AM org.springframework.context.support.GenericApplicationC
ontext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@b
2eddc0: startup date [Mon Feb 27 11:49:30 IST 2017]; root of context hierarchy
Feb 27, 2017 11:49:31 AM org.springframework.ws.soap.addressing.server.Annotatio
nActionEndpointMapping afterPropertiesSet
INFO: Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
Feb 27, 2017 11:49:31 AM org.springframework.ws.soap.saaj.SaajSoapMessageFactory
afterPropertiesSet
INFO: Creating SAAJ 1.3 MessageFactory with SOAP 1.1 Protocol
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.386 sec
Feb 27, 2017 11:49:31 AM org.springframework.context.support.GenericApplicationC
ontext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext@b2ed
dc0: startup date [Mon Feb 27 11:49:30 IST 2017]; root of context hierarchy
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 3.517 s
[INFO] Finished at: 2017-02-27T11:49:31+05:30
[INFO] Final Memory: 11M/109M
[INFO] ------------------------------------------------------------------------
Spring WS - Writing Client
在本章中,我们将学习如何使用Spring WS为在Spring WS中创建的Web应用程序服务器创建客户端。
步 | 描述 |
---|---|
1 | 按照Spring WS-Writing Server一章中的说明,在com.iowiki包下更新项目countryService。 |
2 | 在com.iowiki包下的com.iowiki.client包和MainApp.java下创建CountryServiceClient.java,如以下步骤所述。 |
CountryServiceClient.java
package com.iowiki.client;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import com.iowiki.GetCountryRequest;
import com.iowiki.GetCountryResponse;
public class CountryServiceClient extends WebServiceGatewaySupport {
public GetCountryResponse getCountryDetails(String country){
String uri = "http://localhost:8080/countryService/";
GetCountryRequest request = new GetCountryRequest();
request.setName(country);
GetCountryResponse response =(GetCountryResponse) getWebServiceTemplate()
.marshalSendAndReceive(uri, request);
return response;
}
}
MainApp.java
package com.iowiki;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import com.iowiki.client.CountryServiceClient;
public class MainApp {
public static void main(String[] args) {
CountryServiceClient client = new CountryServiceClient();
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.iowiki");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
GetCountryResponse response = client.getCountryDetails("United States");
System.out.println("Country : " + response.getCountry().getName());
System.out.println("Capital : " + response.getCountry().getCapital());
System.out.println("Population : " + response.getCountry().getPopulation());
System.out.println("Currency : " + response.getCountry().getCurrency());
}
}
启动Web服务
启动Tomcat服务器并确保我们可以使用标准浏览器从webapps文件夹访问其他网页。
测试Web服务客户端
右键单击Eclipse下应用程序中的MainApp.java,并使用run as Java Application命令。 如果应用程序一切正常,它将打印以下消息。
Country : United States
Capital : Washington
Population : 46704314
Currency : USD
在这里,我们为基于SOAP的Web服务创建了一个Client - CountryServiceClient.java 。 MainApp使用CountryServiceClient对Web服务进行命中,发出post请求并获取数据。
Spring WS - Unit Test Client
在本章中,我们将学习如何对Spring WS中创建的客户端进行单元测试-为Spring WS创建的Web应用程序服务器编写客户端 -使用Spring WS 编写服务器 。
步 | 描述 |
---|---|
1 | 按照Spring WS-Writing Server一章中的说明,在com.iowiki包下更新项目countryService。 |
2 | 在文件夹SRC→Test→Java下的com.iowiki包下创建CountryServiceClientTest.java,如下面给出的步骤中所述。 |
CountryServiceClientTest.java
package com.iowiki;
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import com.iowiki.client.CountryServiceClient;
public class CountryServiceClientTest {
CountryServiceClient client;
@Before
public void setUp() throws Exception {
client = new CountryServiceClient();
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath("com.iowiki");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
}
@Test
public void test() {
GetCountryResponse response = client.getCountryDetails("United States");
Country expectedCountry = new Country();
expectedCountry.setCapital("Washington");
Country actualCountry = response.getCountry();
Assert.assertEquals(expectedCountry.getCapital(), actualCountry.getCapital());
}
}
启动Web服务
启动Tomcat服务器并确保我们能够使用标准浏览器从webapps文件夹访问其他网页。
单元测试Web服务客户端
让我们打开命令控制台,转到C:\MVN\countryService目录并执行以下mvn命令。
C:\MVN\countryService>mvn test
Maven将开始构建和测试项目。
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building countryService Spring-WS Application 1.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ countrySer
vice ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] Copying 2 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ countryService
---
[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 10 source files to C:\MVN\countryService\target\classes
[INFO]
[INFO] --- maven-resources-plugin:2.6:testResources (default-testResources) @ co
untryService ---
[WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory C:\MVN\countryService\src\test\resour
ces
[INFO]
[INFO] --- maven-compiler-plugin:3.1:testCompile (default-testCompile) @ country
Service ---
[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 2 source files to C:\MVN\countryService\target\test-classes
[INFO]
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ countryService ---
[INFO] Surefire report directory: C:\MVN\countryService\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.iowiki.CountryServiceClientTest
Feb 27, 2017 8:45:26 PM org.springframework.ws.soap.saaj.SaajSoapMessageFactory
afterPropertiesSet
INFO: Creating SAAJ 1.3 MessageFactory with SOAP 1.1 Protocol
Feb 27, 2017 8:45:26 PM org.springframework.oxm.jaxb.Jaxb2Marshaller createJaxbC
ontextFromContextPath
INFO: Creating JAXBContext with context path [com.iowiki]
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.457 sec
Running com.iowiki.ws.CustomerEndPointTest
Feb 27, 2017 8:45:27 PM org.springframework.test.context.TestContextManager retr
ieveTestExecutionListeners
INFO: @TestExecutionListeners is not present for class [class com.iowiki
.ws.CustomerEndPointTest]: using defaults.
Feb 27, 2017 8:45:27 PM org.springframework.beans.factory.xml.XmlBeanDefinitionR
eader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring-context.xml]
Feb 27, 2017 8:45:27 PM org.springframework.context.support.GenericApplicationCo
ntext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericApplicationContext@5
17c642: startup date [Mon Feb 27 20:45:27 IST 2017]; root of context hierarchy
Feb 27, 2017 8:45:28 PM org.springframework.ws.soap.addressing.server.Annotation
ActionEndpointMapping afterPropertiesSet
INFO: Supporting [WS-Addressing August 2004, WS-Addressing 1.0]
Feb 27, 2017 8:45:28 PM org.springframework.ws.soap.saaj.SaajSoapMessageFactory
afterPropertiesSet
INFO: Creating SAAJ 1.3 MessageFactory with SOAP 1.1 Protocol
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.243 sec
Feb 27, 2017 8:45:28 PM org.springframework.context.support.GenericApplicationCo
ntext doClose
INFO: Closing org.springframework.context.support.GenericApplicationContext@517c
642: startup date [Mon Feb 27 20:45:27 IST 2017]; root of context hierarchy
Results :
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 5.686 s
[INFO] Finished at: 2017-02-27T20:45:28+05:30
[INFO] Final Memory: 17M/173M
[INFO] ------------------------------------------------------------------------