Web Service 教程与实例 从零基础到实战开发 详解SOAP与RESTful架构设计 常见报错解决方案与代码示例

引言:Web Service 的核心概念与重要性
Web Service(网络服务)是一种基于网络的、分布式的、自描述的软件系统,它允许不同平台、不同编程语言编写的应用程序之间进行互操作。在现代软件开发中,Web Service 扮演着至关重要的角色,它是实现系统集成、微服务架构和云原生应用的基础技术。
为什么需要 Web Service?
想象一个场景:一家电商公司使用 Java 开发的订单管理系统,需要与第三方支付平台(可能使用 Python)进行集成,同时还要向移动端 App(使用 Swift 或 Kotlin)提供商品数据。如果没有标准化的通信协议,每个系统都需要为每个合作伙伴开发专门的接口,这将导致巨大的开发和维护成本。
Web Service 通过标准化的协议解决了这个问题:
平台无关性
:Java 系统可以与 .NET 系统通信
语言无关性
:Python 客户端可以调用 PHP 服务
网络可达性
:通过 HTTP/HTTPS 协议,可以跨越防火墙和网络边界
标准化接口
:使用 WSDL、OpenAPI 等标准描述接口
Web Service 的主要类型
目前主流的 Web Service 架构主要有两种:
SOAP (Simple Object Access Protocol)
:基于 XML 的协议,强调严格的类型定义和安全性
RESTful (Representational State Transfer)
:基于 HTTP 的架构风格,强调资源和状态转移
接下来的内容将从零基础开始,详细讲解这两种架构的设计原理、实战开发和常见问题解决方案。
第一部分:SOAP Web Service 详解
1.1 SOAP 基础概念
SOAP 是一个基于 XML 的协议,用于在 Web 上交换结构化信息。它定义了消息的格式、传输方式和处理规则。SOAP 的核心特点包括:
XML 格式
:所有消息都是格式良好的 XML 文档
协议独立
:可以在 HTTP、SMTP、TCP 等多种协议上传输
严格的类型系统
:使用 XSD (XML Schema Definition) 定义数据类型
内置错误处理
:通过 Fault 元素处理错误
安全性强
:支持 WS-Security 等企业级安全标准
1.2 SOAP 消息结构
一个完整的 SOAP 消息包含以下部分:





admin
password123





10
20




soap:Server
Internal Server Error


1.3 SOAP 实战开发:Java 示例
1.3.1 服务端开发(使用 JAX-WS)
我们将创建一个简单的计算器服务,支持加法和乘法运算。
步骤 1:定义服务接口
// CalculatorService.java
package com.example.soap;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
public interface CalculatorService {

@WebMethod
int add(@WebParam(name = “a”) int a, @WebParam(name = “b”) int b);

@WebMethod
int multiply(@WebParam(name = “a”) int a, @WebParam(name = “b”) int b);

@WebMethod
double divide(@WebParam(name = “a”) double a, @WebParam(name = “b”) double b) throws DivisionByZeroException;
}
步骤 2:实现服务接口
// CalculatorServiceImpl.java
package com.example.soap;

import javax.jws.WebService;

@WebService(endpointInterface = “com.example.soap.CalculatorService”)
public class CalculatorServiceImpl implements CalculatorService {

@Override
public int add(int a, int b) {
System.out.println(“Adding ” + a + ” and ” + b);
return a + b;
}

@Override
public int multiply(int a, int b) {
System.out.println(“Multiplying ” + a + ” and ” + b);
return a * b;
}

@Override
public double divide(double a, double b) throws DivisionByZeroException {
if (b == 0) {
throw new DivisionByZeroException(“Cannot divide by zero”);
}
return a / b;
}
}
步骤 3:自定义异常类
// DivisionByZeroException.java
package com.example.soap;

public class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}
}
步骤 4:发布服务
// ServicePublisher.java
package com.example.soap;

import javax.xml.ws.Endpoint;

public class ServicePublisher {
public static void main(String[] args) {
String address = “http://localhost:8080/calculator”;
Endpoint endpoint = Endpoint.publish(address, new CalculatorServiceImpl());
System.out.println(“SOAP Service published at: ” + address);
System.out.println(“WSDL available at: ” + address + “?wsdl”);

// 保持服务运行
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
endpoint.stop();
}
}
}
1.3.2 客户端开发
使用 wsimport 生成客户端代码
# 生成客户端存根代码
wsimport -keep -p com.example.soap.client http://localhost:8080/calculator?wsdl
客户端调用代码
// CalculatorClient.java
package com.example.soap.client;

public class CalculatorClient {
public static void main(String[] args) {
// 创建服务实例
CalculatorService_Service service = new CalculatorService_Service();
CalculatorService port = service.getCalculatorServicePort();

try {
// 调用远程方法
int sum = port.add(10, 20);
System.out.println(“10 + 20 = ” + sum);

int product = port.multiply(5, 6);
System.out.println(“5 * 6 = ” + product);

double result = port.divide(10.0, 2.0);
System.out.println(“10.0 / 2.0 = ” + result);

} catch (DivisionByZeroException e) {
System.err.println(“Error: ” + e.getMessage());
}
}
}
1.4 SOAP 的 WSDL 文件详解
WSDL (Web Services Description Language) 是描述 SOAP 服务的 XML 文档。我们的计算器服务生成的 WSDL 如下:









































1.5 SOAP 常见报错解决方案
错误 1:WSDL 访问被拒绝(403 Forbidden)
问题描述
:客户端无法访问
?wsdl
地址,返回 403 错误。
原因分析
:
服务器配置了 WSDL 访问限制
防火墙或安全组规则阻止
URL 路径错误
解决方案
:
// 在服务发布时添加权限控制
@WebService
public class SecureCalculatorService {

@WebMethod
public String getWsdl() {
// 返回 WSDL 内容
return “WSDL content here”;
}
}

// 或者在 Tomcat 中配置 web.xml
/*


WSDL
*.wsdl


user


*/
错误 2:命名空间不匹配
问题描述
:客户端调用时出现 “Message not understood” 错误。
原因
:客户端和服务器的命名空间定义不一致。
解决方案
:
// 确保 @WebService 注解中的 targetNamespace 明确指定
@WebService(
targetNamespace = “http://example.com/calculator”,
portName = “CalculatorPort”,
serviceName = “CalculatorService”
)
public class CalculatorServiceImpl implements CalculatorService {
// 实现代码
}
错误 3:数据类型转换错误
问题描述
:服务器返回的数据类型与客户端期望的不匹配。
解决方案
:
// 使用包装类型避免空指针
@WebMethod
public Double divide(@WebParam(name = “a”) Double a,
@WebParam(name = “b”) Double b)
throws DivisionByZeroException {
if (a == null || b == null) {
throw new IllegalArgumentException(“Parameters cannot be null”);
}
if (b == 0) {
throw new DivisionByZeroException(“Cannot divide by zero”);
}
return a / b;
}
错误 4:超时问题
问题描述
:长时间运行的操作导致客户端超时。
解决方案
:
// 客户端设置超时
CalculatorService_Service service = new CalculatorService_Service();
CalculatorService port = service.getCalculatorServicePort();

// 设置超时时间(毫秒)
BindingProvider bp = (BindingProvider) port;
bp.getRequestContext().put(BindingProviderProperties.REQUEST_TIMEOUT, 30000); // 30秒
bp.getRequestContext().put(BindingProviderProperties.CONNECT_TIMEOUT, 10000); // 10秒
第二部分:RESTful Web Service 详解
2.1 REST 架构风格基础
REST (Representational State Transfer) 是由 Roy Fielding 在 2000 年提出的架构风格,它不是协议,而是一组约束和原则。RESTful 服务基于 HTTP 协议,使用标准的 HTTP 方法操作资源。
REST 的核心原则:
资源(Resource)
:一切皆资源,每个资源都有唯一的 URI
表述(Representation)
:资源可以有多种表述形式(JSON、XML、HTML 等)
状态转移(State Transfer)
:通过 HTTP 方法改变资源状态
无状态(Stateless)
:每个请求包含处理所需的所有信息
统一接口(Uniform Interface)
:使用标准的 HTTP 方法
2.2 HTTP 方法与 CRUD 操作
HTTP 方法
CRUD 操作
示例 URI
描述
GET
Read
GET /users/123
获取用户 123 的信息
POST
Create
POST /users
创建新用户
PUT
Update/Replace
PUT /users/123
完全替换用户 123
PATCH
Partial Update
PATCH /users/123
部分更新用户 123
DELETE
Delete
DELETE /users/123
删除用户 123
2.3 RESTful 实战开发:Spring Boot 示例
2.3.1 项目结构
restful-demo/
├── src/
│ └── main/
│ ├── java/
│ │ └── com/
│ │ └── example/
│ │ └── restful/
│ │ ├── model/
│ │ │ ├── User.java
│ │ │ └── ApiResponse.java
│ │ ├── controller/
│ │ │ └── UserController.java
│ │ ├── service/
│ │ │ └── UserService.java
│ │ └── RestfulApplication.java
│ └── resources/
│ └── application.properties
└── pom.xml
2.3.2 实体类定义
// User.java
package com.example.restful.model;

import java.time.LocalDateTime;

public class User {
private Long id;
private String username;
private String email;
private String firstName;
private String lastName;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;

// 构造函数
public User() {}

public User(Long id, String username, String email, String firstName, String lastName) {
this.id = id;
this.username = username;
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.createdAt = LocalDateTime.now();
this.updatedAt = LocalDateTime.now();
}

// Getter 和 Setter
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }

public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }

public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }

public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }

public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }

public LocalDateTime getCreatedAt() { return createdAt; }
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }

public LocalDateTime getUpdatedAt() { return updatedAt; }
public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }
}
// ApiResponse.java – 统一响应格式
package com.example.restful.model;

import java.time.LocalDateTime;

public class ApiResponse {
private boolean success;
private String message;
private T data;
private LocalDateTime timestamp;
private Integer statusCode;

public ApiResponse() {
this.timestamp = LocalDateTime.now();
}

// 静态工厂方法
public static ApiResponse success(T data) {
ApiResponse response = new ApiResponse<>();
response.success = true;
response.message = “Operation successful”;
response.data = data;
response.statusCode = 200;
return response;
}

public static ApiResponse error(String message, Integer statusCode) {
ApiResponse response = new ApiResponse<>();
response.success = false;
response.message = message;
response.statusCode = statusCode;
return response;
}

// Getter 和 Setter
public boolean isSuccess() { return success; }
public void setSuccess(boolean success) { this.success = success; }

public String getMessage() { return message; }
public void setMessage(String message) { this.message = message; }

public T getData() { return data; }
public void setData(T data) { this.data = data; }

public LocalDateTime getTimestamp() { return timestamp; }
public void setTimestamp(LocalDateTime timestamp) { this.timestamp = timestamp; }

public Integer getStatusCode() { return statusCode; }
public void setStatusCode(Integer statusCode) { this.statusCode = statusCode; }
}
2.3.3 Service 层
// UserService.java
package com.example.restful.service;

import com.example.restful.model.User;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

@Service
public class UserService {
private final ConcurrentHashMap userStore = new ConcurrentHashMap<>();
private final AtomicLong idGenerator = new AtomicLong(1);

public UserService() {
// 初始化一些测试数据
User user1 = new User(1L, “john_doe”, “john@example.com”, “John”, “Doe”);
User user2 = new User(2L, “jane_smith”, “jane@example.com”, “Jane”, “Smith”);
userStore.put(1L, user1);
userStore.put(2L, user2);
idGenerator.set(3L);
}

// GET /users – 获取所有用户
public List getAllUsers() {
return new ArrayList<>(userStore.values());
}

// GET /users/{id} – 获取单个用户
public Optional getUserById(Long id) {
return Optional.ofNullable(userStore.get(id));
}

// POST /users – 创建用户
public User createUser(User user) {
Long newId = idGenerator.getAndIncrement();
user.setId(newId);
user.setCreatedAt(LocalDateTime.now());
user.setUpdatedAt(LocalDateTime.now());
userStore.put(newId, user);
return user;
}

// PUT /users/{id} – 完全更新用户
public Optional updateUser(Long id, User user) {
if (!userStore.containsKey(id)) {
return Optional.empty();
}
user.setId(id);
user.setCreatedAt(userStore.get(id).getCreatedAt());
user.setUpdatedAt(LocalDateTime.now());
userStore.put(id, user);
return Optional.of(user);
}

// PATCH /users/{id} – 部分更新用户
public Optional patchUser(Long id, User user) {
if (!userStore.containsKey(id)) {
return Optional.empty();
}
User existing = userStore.get(id);

if (user.getUsername() != null) existing.setUsername(user.getUsername());
if (user.getEmail() != null) existing.setEmail(user.getEmail());
if (user.getFirstName() != null) existing.setFirstName(user.getFirstName());
if (user.getLastName() != null) existing.setLastName(user.getLastName());

existing.setUpdatedAt(LocalDateTime.now());
userStore.put(id, existing);
return Optional.of(existing);
}

// DELETE /users/{id} – 删除用户
public boolean deleteUser(Long id) {
return userStore.remove(id) != null;
}
}
2.3.4 Controller 层
// UserController.java
package com.example.restful.controller;

import com.example.restful.model.ApiResponse;
import com.example.restful.model.User;
import com.example.restful.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping(“/api/v1/users”)
public class UserController {

private final UserService userService;

@Autowired
public UserController(UserService userService) {
this.userService = userService;
}

// GET /api/v1/users – 获取所有用户
@GetMapping
public ResponseEntity>> getAllUsers() {
List users = userService.getAllUsers();
return ResponseEntity.ok(ApiResponse.success(users));
}

// GET /api/v1/users/{id} – 获取单个用户
@GetMapping(“/{id}”)
public ResponseEntity> getUserById(@PathVariable Long id) {
Optional user = userService.getUserById(id);
if (user.isPresent()) {
return ResponseEntity.ok(ApiResponse.success(user.get()));
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiResponse.error(“User not found with id: ” + id, 404));
}
}

// POST /api/v1/users – 创建用户
@PostMapping
public ResponseEntity> createUser(@RequestBody User user) {
// 验证输入
if (user.getUsername() == null || user.getEmail() == null) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(“Username and email are required”, 400));
}

User createdUser = userService.createUser(user);
return ResponseEntity.status(HttpStatus.CREATED)
.body(ApiResponse.success(createdUser));
}

// PUT /api/v1/users/{id} – 完全更新用户
@PutMapping(“/{id}”)
public ResponseEntity> updateUser(@PathVariable Long id,
@RequestBody User user) {
Optional updatedUser = userService.updateUser(id, user);
if (updatedUser.isPresent()) {
return ResponseEntity.ok(ApiResponse.success(updatedUser.get()));
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiResponse.error(“User not found with id: ” + id, 404));
}
}

// PATCH /api/v1/users/{id} – 部分更新用户
@PatchMapping(“/{id}”)
public ResponseEntity> patchUser(@PathVariable Long id,
@RequestBody User user) {
Optional patchedUser = userService.patchUser(id, user);
if (patchedUser.isPresent()) {
return ResponseEntity.ok(ApiResponse.success(patchedUser.get()));
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiResponse.error(“User not found with id: ” + id, 404));
}
}

// DELETE /api/v1/users/{id} – 删除用户
@DeleteMapping(“/{id}”)
public ResponseEntity> deleteUser(@PathVariable Long id) {
boolean deleted = userService.deleteUser(id);
if (deleted) {
return ResponseEntity.ok(ApiResponse.success(null));
} else {
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiResponse.error(“User not found with id: ” + id, 404));
}
}
}
2.3.5 主应用类
// RestfulApplication.java
package com.example.restful;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RestfulApplication {
public static void main(String[] args) {
SpringApplication.run(RestfulApplication.class, args);
}
}
2.3.6 配置文件
# application.properties
server.port=8080
spring.application.name=restful-demo

# 日志配置
logging.level.com.example.restful=DEBUG
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss} – %msg%n

# JSON 响应配置
spring.jackson.serialization.write-dates-as-timestamps=false
spring.jackson.time-zone=UTC
2.3.7 Maven 依赖 (pom.xml)

4.0.0

com.example
restful-demo
1.0.0 jar org.springframework.boot
spring-boot-starter-parent
2.7.0
11




org.springframework.boot
spring-boot-starter-web



org.springframework.boot
spring-boot-starter-test
test

org.springframework.boot
spring-boot-maven-plugin
2.4 RESTful API 测试
2.4.1 使用 curl 测试
# 1. 获取所有用户
curl -X GET http://localhost:8080/api/v1/users

# 2. 获取单个用户
curl -X GET http://localhost:8080/api/v1/users/1

# 3. 创建用户
curl -X POST http://localhost:8080/api/v1/users \
-H “Content-Type: application/json” \
-d ‘{
“username”: “alice”,
“email”: “alice@example.com”,
“firstName”: “Alice”,
“lastName”: “Wonder”
}’

# 4. 完全更新用户
curl -X PUT http://localhost:8080/api/v1/users/1 \
-H “Content-Type: application/json” \
-d ‘{
“username”: “john_updated”,
“email”: “john.updated@example.com”,
“firstName”: “John”,
“lastName”: “Updated”
}’

# 5. 部分更新用户
curl -X PATCH http://localhost:8080/api/v1/users/1 \
-H “Content-Type: application/json” \
-d ‘{
“email”: “john.new@example.com”
}’

# 6. 删除用户
curl -X DELETE http://localhost:8080/api/v1/users/1
2.4.2 使用 Postman 测试
Postman 是一个强大的 API 测试工具,以下是使用步骤:
创建 Collection
:新建一个名为 “User API” 的集合
添加请求
:
GET All Users:
GET http://localhost:8080/api/v1/users
Get User By ID:
GET http://localhost:8080/api/v1/users/1
Create User:
POST http://localhost:8080/api/v1/users
Body: raw JSON
Update User:
PUT http://localhost:8080/api/v1/users/1
Delete User:
DELETE http://localhost:8080/api/v1/users/1
使用环境变量
:
创建环境
Local
设置变量
base_url
=
http://localhost:8080/api/v1
在请求中使用
{{base_url}}/users
2.5 RESTful 常见报错解决方案
错误 1:HTTP 415 Unsupported Media Type
问题描述
:发送 POST/PUT 请求时返回 415 错误。
原因
:Content-Type 不正确或服务器无法处理请求体格式。
解决方案
:
// 确保 Controller 能够处理 JSON
@RestController
@RequestMapping(“/api/v1/users”)
public class UserController {
// …

// 明确指定 consumes 和 produces
@PostMapping(consumes = “application/json”, produces = “application/json”)
public ResponseEntity> createUser(@RequestBody User user) {
// …
}
}
客户端修正
:
# 确保添加正确的 Content-Type 头
curl -X POST http://localhost:8080/api/v1/users \
-H “Content-Type: application/json” \ # 必须添加
-d ‘{“username”:”test”,”email”:”test@example.com”}’
错误 2:HTTP 400 Bad Request
问题描述
:请求参数或体无法被正确解析。
原因
:
JSON 格式错误
必填字段缺失
数据类型不匹配
解决方案
:
// 添加全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity> handleValidationExceptions(
MethodArgumentNotValidException ex) {
String errorMessage = ex.getBindingResult().getAllErrors().stream()
.map(error -> error.getDefaultMessage())
.collect(Collectors.joining(“, “));

return ResponseEntity.badRequest()
.body(ApiResponse.error(errorMessage, 400));
}

@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity> handleJsonParseError(
HttpMessageNotReadableException ex) {
return ResponseEntity.badRequest()
.body(ApiResponse.error(“Invalid JSON format: ” + ex.getMostSpecificCause().getMessage(), 400));
}
}
实体类添加验证注解
:
import javax.validation.constraints.*;

public class User {
@NotNull(message = “Username cannot be null”)
@Size(min = 3, max = 20, message = “Username must be between 3 and 20 characters”)
private String username;

@NotNull(message = “Email cannot be null”)
@Email(message = “Email should be valid”)
private String email;

// …
}
错误 3:HTTP 404 Not Found
问题描述
:请求的资源不存在。
原因
:
URL 路径错误
资源 ID 不存在
路径参数不匹配
解决方案
:
// 使用统一的 404 处理
@GetMapping(“/{id}”)
public ResponseEntity> getUserById(@PathVariable Long id) {
Optional user = userService.getUserById(id);
return user.map(u -> ResponseEntity.ok(ApiResponse.success(u)))
.orElseGet(() -> ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(ApiResponse.error(“User not found with id: ” + id, 404)));
}
错误 4:HTTP 500 Internal Server Error
问题描述
:服务器内部错误。
原因
:
空指针异常
数据库连接失败
业务逻辑错误
解决方案
:
// 全局异常处理
@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(Exception.class)
public ResponseEntity> handleGenericException(Exception ex) {
// 记录日志
log.error(“Unexpected error: “, ex);

// 返回友好的错误信息
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ApiResponse.error(“Internal server error occurred”, 500));
}

@ExceptionHandler(NullPointerException.class)
public ResponseEntity> handleNullPointerException(NullPointerException ex) {
log.error(“Null pointer error: “, ex);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(ApiResponse.error(“Data integrity error”, 500));
}
}
错误 5:跨域问题 (CORS)
问题描述
:浏览器控制台显示 CORS 错误。
原因
:前端应用与后端 API 不在同一个域。
解决方案
:
// 全局 CORS 配置
@Configuration
public class CorsConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping(“/api/**”)
.allowedOrigins(“http://localhost:3000”, “http://localhost:8080”)
.allowedMethods(“GET”, “POST”, “PUT”, “PATCH”, “DELETE”, “OPTIONS”)
.allowedHeaders(“*”)
.allowCredentials(true)
.maxAge(3600);
}
}

// 或者在 Controller 级别配置
@CrossOrigin(origins = “http://localhost:3000”,
methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE})
@RestController
@RequestMapping(“/api/v1/users”)
public class UserController {
// …
}
第三部分:SOAP vs RESTful 对比与选择指南
3.1 核心对比
特性
SOAP
RESTful
协议类型
协议 (Protocol)
架构风格 (Architectural Style)
数据格式
XML (严格)
JSON/XML/HTML (灵活)
传输协议
HTTP, SMTP, TCP 等
主要 HTTP/HTTPS
状态管理
可维护状态
无状态
安全性
WS-Security (企业级)
HTTPS + OAuth/JWT
性能
较重 (XML 解析开销)
较轻 (JSON 解析快)
学习曲线
较陡峭
较平缓
工具支持
WSDL, UDDI
OpenAPI/Swagger
缓存支持
弱
强 (HTTP 缓存)
浏览器友好
差
好
3.2 选择指南
选择 SOAP 的场景:
企业级应用集成
需要严格的类型安全和契约
银行、金融系统
需要 ACID 事务支持
安全性要求极高
需要 WS-Security 标准
需要数字签名和加密
合规性要求严格
需要可靠的消息传递
需要 WS-ReliableMessaging
需要消息队列保证
已有 SOAP 基础设施
企业已投资 SOAP 网关、ESB
选择 RESTful 的场景:
移动应用和前端应用
需要轻量级数据传输
需要快速开发迭代
公共 API
需要广泛的可访问性
需要良好的缓存机制
微服务架构
服务间轻量级通信
需要快速扩展
资源导向的应用
CRUD 操作为主
需要清晰的资源层次
3.3 混合架构模式
在实际项目中,可以采用混合架构:
// 示例:内部使用 SOAP,外部使用 REST
// 内部系统集成
@WebService
public class InternalPaymentService {
// 供内部 ERP 系统调用
}

// 外部 API
@RestController
@RequestMapping(“/api/v1/payments”)
public class ExternalPaymentController {
// 供移动端和第三方调用
}
第四部分:高级主题与最佳实践
4.1 安全最佳实践
SOAP 安全
// 使用 WS-Security
@WebService
@Policy(uri = “security-policy.xml”)
public class SecureCalculatorService {
// …
}
security-policy.xml
:


























RESTful 安全
// JWT 认证示例
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {

String header = request.getHeader(“Authorization”);

if (header != null && header.startsWith(“Bearer “)) {
String token = header.substring(7);
try {
Claims claims = jwtUtil.validateToken(token);
String username = claims.getSubject();

// 设置认证信息
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(username, null, null);
SecurityContextHolder.getContext().setAuthentication(authentication);

} catch (JwtException e) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write(“{\”error\”:\”Invalid token\”}”);
return;
}
}

filterChain.doFilter(request, response);
}
}

// JWT 工具类
@Component
public class JwtUtil {
@Value(“${jwt.secret}”)
private String secret;

@Value(“${jwt.expiration}”)
private Long expiration;

public String generateToken(String username) {
return Jwts.builder()
.setSubject(username)
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + expiration * 1000))
.signWith(SignatureAlgorithm.HS256, secret)
.compact();
}

public Claims validateToken(String token) {
return Jwts.parser()
.setSigningKey(secret)
.parseClaimsJws(token)
.getBody();
}
}
4.2 版本控制策略
RESTful 版本控制
// URI 版本控制(推荐)
@RestController
@RequestMapping(“/api/v1/users”)
public class UserControllerV1 {
// v1 实现
}

@RestController
@RequestMapping(“/api/v2/users”)
public class UserControllerV2 {
// v2 实现,支持部分更新等新功能
}

// Header 版本控制
@RestController
@RequestMapping(“/api/users”)
public class UserController {

@GetMapping(produces = “application/vnd.company.app-v1+json”)
public ResponseEntity getUsersV1() {
// v1 实现
}

@GetMapping(produces = “application/vnd.company.app-v2+json”)
public ResponseEntity getUsersV2() {
// v2 实现
}
}
SOAP 版本控制
// 使用命名空间版本控制
@WebService(targetNamespace = “http://example.com/calculator/v1”)
public interface CalculatorServiceV1 {
// v1 方法
}

@WebService(targetNamespace = “http://example.com/calculator/v2”)
public interface CalculatorServiceV2 {
// v2 方法,支持更多操作
}
4.3 性能优化
RESTful 性能优化
// 1. 分页查询
@GetMapping
public ResponseEntity>> getUsers(
@RequestParam(defaultValue = “0”) int page,
@RequestParam(defaultValue = “10”) int size,
@RequestParam(required = false) String sort) {

Pageable pageable = PageRequest.of(page, size, Sort.by(sort != null ? sort : “id”));
Page userPage = userService.findAll(pageable);

return ResponseEntity.ok(ApiResponse.success(userPage));
}

// 2. 响应缓存
@GetMapping(“/{id}”)
@Cacheable(value = “users”, key = “#id”)
public ResponseEntity> getUserById(@PathVariable Long id) {
// …
}

// 3. 异步处理
@PostMapping
public CompletableFuture>> createUserAsync(@RequestBody User user) {
return CompletableFuture.supplyAsync(() -> {
User created = userService.createUser(user);
return ResponseEntity.status(HttpStatus.CREATED)
.body(ApiResponse.success(created));
});
}
SOAP 性能优化
// 使用 MTOM 优化二进制传输
@MTOM
@WebService
public interface FileService {
@WebMethod
void uploadFile(@WebParam(name = “data”) DataHandler data);
}

// 启用缓存
@WebService
public class CachedCalculatorService {
private final Cache cache = CacheBuilder.newBuilder()
.maximumSize(1000)
.expireAfterWrite(10, TimeUnit.MINUTES)
.build();

@WebMethod
public int add(int a, int b) {
int key = Objects.hash(a, b);
try {
return cache.get(key, () -> a + b);
} catch (ExecutionException e) {
return a + b;
}
}
}
4.4 监控与日志
// RESTful 请求日志
@Component
public class RequestLoggingFilter implements Filter {

private static final Logger log = LoggerFactory.getLogger(RequestLoggingFilter.class);

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {

HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;

long startTime = System.currentTimeMillis();

// 包装响应以记录响应体
ContentCachingResponseWrapper wrappedResponse = new ContentCachingResponseWrapper(httpResponse);

try {
chain.doFilter(request, wrappedResponse);
} finally {
long duration = System.currentTimeMillis() – startTime;

// 记录请求响应日志
log.info(“{} {} {} – {}ms”,
httpRequest.getMethod(),
httpRequest.getRequestURI(),
httpResponse.getStatus(),
duration);

// 复制响应体
wrappedResponse.copyBodyToResponse();
}
}
}

// SOAP 消息日志
@WebService
public class LoggedCalculatorService implements CalculatorService {

@Override
public int add(int a, int b) {
log.info(“SOAP call: add({}, {})”, a, b);
int result = a + b;
log.info(“SOAP result: {}”, result);
return result;
}
}
第五部分:实战项目:混合架构的订单处理系统
5.1 项目需求
创建一个订单处理系统,满足以下需求:
内部 ERP 系统使用 SOAP 与订单服务集成
移动端 App 使用 RESTful API 查询订单
支付网关使用 SOAP 协议
客户端使用 RESTful API 提交订单
5.2 系统架构
┌─────────────────────────────────────────────────────────────┐
│ 客户端层 │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ 移动端 App │ │ Web 前端 │ │ ERP 系统 │ │
│ │ (REST) │ │ (REST) │ │ (SOAP) │ │
│ └──────┬───────┘ └──────┬───────┘ └──────┬───────┘ │
│ │ │ │ │
└─────────┼──────────────────┼──────────────────┼─────────────┘
│ │ │
┌─────────▼──────────────────▼──────────────────▼─────────────┐
│ API 网关 / 路由层 │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Spring Cloud Gateway / API Gateway │ │
│ │ – 路由 REST 请求到 Order REST Service │ │
│ │ – 路由 SOAP 请求到 Order SOAP Service │ │
│ │ – 认证授权、限流、监控 │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌─────────▼────────────────────────────────────────────────────┐
│ 业务服务层 │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ Order REST │ │ Order SOAP │ │
│ │ Service │ │ Service │ │
│ │ (Spring Boot) │ │ (JAX-WS) │ │
│ └────────┬─────────┘ └────────┬─────────┘ │
│ │ │ │
│ └───────────┬───────────────┘ │
│ ▼ │
│ ┌──────────────────────┐ │
│ │ Order Service Core │ │
│ │ (业务逻辑、数据访问) │ │
│ └──────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
┌─────────▼────────────────────────────────────────────────────┐
│ 数据存储层 │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ MySQL 数据库 │ │ Redis 缓存 │ │
│ └──────────────────┘ └──────────────────┘ │
└─────────────────────────────────────────────────────────────┘
5.3 核心代码实现
5.3.1 共享实体类
// Order.java
package com.example.order.model;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

public class Order {
private Long id;
private String orderNumber;
private Long customerId;
private BigDecimal totalAmount;
private OrderStatus status;
private LocalDateTime createdAt;
private LocalDateTime updatedAt;
private List items;

// 枚举:订单状态
public enum OrderStatus {
PENDING, // 待处理
CONFIRMED, // 已确认
PROCESSING, // 处理中
SHIPPED, // 已发货
COMPLETED, // 已完成
CANCELLED // 已取消
}

// 构造函数、Getter/Setter 省略
}

// OrderItem.java
package com.example.order.model;

import java.math.BigDecimal;

public class OrderItem {
private Long productId;
private String productName;
private int quantity;
private BigDecimal unitPrice;
private BigDecimal subtotal;

// 构造函数、Getter/Setter 省略
}
5.3.2 SOAP 服务(供 ERP 系统使用)
// OrderSoapService.java
package com.example.order.soap;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import java.util.List;

@WebService
@SOAPBinding(style = SOAPBinding.Style.DOCUMENT)
public interface OrderSoapService {

@WebMethod
Order createOrderFromERP(@WebParam(name = “order”) Order order);

@WebMethod
Order getOrderDetails(@WebParam(name = “orderNumber”) String orderNumber);

@WebMethod
List getOrdersByCustomer(@WebParam(name = “customerId”) Long customerId);

@WebMethod
Order updateOrderStatus(@WebParam(name = “orderNumber”) String orderNumber,
@WebParam(name = “newStatus”) Order.OrderStatus newStatus);

@WebMethod
boolean cancelOrder(@WebParam(name = “orderNumber”) String orderNumber);
}

// OrderSoapServiceImpl.java
package com.example.order.soap;

import com.example.order.model.Order;
import com.example.order.service.OrderCoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jws.WebService;
import java.util.List;

@WebService(endpointInterface = “com.example.order.soap.OrderSoapService”)
@Component
public class OrderSoapServiceImpl implements OrderSoapService {

@Autowired
private OrderCoreService orderCoreService;

@Override
public Order createOrderFromERP(Order order) {
// ERP 系统创建的订单直接标记为已确认
order.setStatus(Order.OrderStatus.CONFIRMED);
return orderCoreService.createOrder(order);
}

@Override
public Order getOrderDetails(String orderNumber) {
return orderCoreService.findByOrderNumber(orderNumber)
.orElseThrow(() -> new RuntimeException(“Order not found: ” + orderNumber));
}

@Override
public List getOrdersByCustomer(Long customerId) {
return orderCoreService.findByCustomerId(customerId);
}

@Override
public Order updateOrderStatus(String orderNumber, Order.OrderStatus newStatus) {
return orderCoreService.updateOrderStatus(orderNumber, newStatus);
}

@Override
public boolean cancelOrder(String orderNumber) {
return orderCoreService.cancelOrder(orderNumber);
}
}
5.3.3 RESTful 服务(供移动端使用)
// OrderRestController.java
package com.example.order.rest;

import com.example.order.model.Order;
import com.example.order.service.OrderCoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(“/api/v1/orders”)
public class OrderRestController {

@Autowired
private OrderCoreService orderCoreService;

// 创建订单(移动端提交)
@PostMapping
public ResponseEntity createOrder(@RequestBody Order order) {
// 移动端创建的订单初始状态为 PENDING
order.setStatus(Order.OrderStatus.PENDING);
Order created = orderCoreService.createOrder(order);
return ResponseEntity.ok(created);
}

// 查询订单详情
@GetMapping(“/{orderNumber}”)
public ResponseEntity getOrder(@PathVariable String orderNumber) {
return orderCoreService.findByOrderNumber(orderNumber)
.map(ResponseEntity::ok)
.orElse(ResponseEntity.notFound().build());
}

// 查询客户订单列表
@GetMapping(“/customer/{customerId}”)
public ResponseEntity> getCustomerOrders(@PathVariable Long customerId) {
List orders = orderCoreService.findByCustomerId(customerId);
return ResponseEntity.ok(orders);
}

// 客户取消订单
@DeleteMapping(“/{orderNumber}”)
public ResponseEntity cancelOrder(@PathVariable String orderNumber) {
boolean cancelled = orderCoreService.cancelOrder(orderNumber);
return cancelled ? ResponseEntity.ok().build() : ResponseEntity.notFound().build();
}
}
5.3.4 核心业务服务
// OrderCoreService.java
package com.example.order.service;

import com.example.order.model.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class OrderCoreService {

@Autowired
private OrderRepository orderRepository;

@Autowired
private RedisTemplate redisTemplate;

// 创建订单
public Order createOrder(Order order) {
// 生成订单号
String orderNumber = generateOrderNumber();
order.setOrderNumber(orderNumber);

// 计算总额
BigDecimal total = order.getItems().stream()
.map(item -> item.getUnitPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
order.setTotalAmount(total);

// 保存到数据库
Order saved = orderRepository.save(order);

// 缓存到 Redis(5分钟)
redisTemplate.opsForValue().set(“order:” + orderNumber, saved, 5, TimeUnit.MINUTES);

return saved;
}

// 查询订单(带缓存)
public Optional findByOrderNumber(String orderNumber) {
// 先查 Redis
Order order = redisTemplate.opsForValue().get(“order:” + orderNumber);
if (order != null) {
return Optional.of(order);
}

// 再查数据库
Optional dbOrder = orderRepository.findByOrderNumber(orderNumber);

// 如果找到,缓存到 Redis
dbOrder.ifPresent(o -> redisTemplate.opsForValue().set(“order:” + orderNumber, o, 5, TimeUnit.MINUTES));

return dbOrder;
}

// 查询客户订单
public List findByCustomerId(Long customerId) {
return orderRepository.findByCustomerId(customerId);
}

// 更新订单状态
public Order updateOrderStatus(String orderNumber, Order.OrderStatus newStatus) {
Order order = findByOrderNumber(orderNumber)
.orElseThrow(() -> new RuntimeException(“Order not found”));

order.setStatus(newStatus);
order.setUpdatedAt(java.time.LocalDateTime.now());

Order updated = orderRepository.save(order);

// 更新缓存
redisTemplate.opsForValue().set(“order:” + orderNumber, updated, 5, TimeUnit.MINUTES);

return updated;
}

// 取消订单
public boolean cancelOrder(String orderNumber) {
Optional orderOpt = findByOrderNumber(orderNumber);
if (orderOpt.isEmpty()) {
return false;
}

Order order = orderOpt.get();

// 只有 PENDING 或 CONFIRMED 状态可以取消
if (order.getStatus() != Order.OrderStatus.PENDING &&
order.getStatus() != Order.OrderStatus.CONFIRMED) {
return false;
}

order.setStatus(Order.OrderStatus.CANCELLED);
order.setUpdatedAt(java.time.LocalDateTime.now());
orderRepository.save(order);

// 删除缓存
redisTemplate.delete(“order:” + orderNumber);

return true;
}

// 生成订单号
private String generateOrderNumber() {
return “ORD” + System.currentTimeMillis() + (int)(Math.random() * 1000);
}
}
5.3.5 SOAP 服务发布配置
// SoapConfig.java
package com.example.order.config;

import com.example.order.soap.OrderSoapServiceImpl;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;

@EnableWs
@Configuration
public class SoapConfig extends WsConfigurerAdapter {

@Bean
public ServletRegistrationBean messageDispatcherServlet(
ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
return new ServletRegistrationBean<>(servlet, “/soap/*”);
}

@Bean(name = “orders”)
public DefaultWsdl11Definition defaultWsdl11Definition(
SimpleXsdSchema orderSchema) {
DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
definition.setPortTypeName(“OrderPort”);
definition.setServiceName(“OrderService”);
definition.setTargetNamespace(“http://example.com/order/soap”);
definition.setSchema(orderSchema);
return definition;
}

@Bean
public SimpleXsdSchema orderSchema() {
return new SimpleXsdSchema(new ClassPathResource(“order.xsd”));
}
}
order.xsd
:








































5.4 测试与验证
5.4.1 SOAP 客户端测试(ERP 系统)
// ERPClient.java
public class ERPClient {
public static void main(String[] args) {
OrderService_Service service = new OrderService_Service();
OrderService port = service.getOrderServicePort();

// 创建订单
Order order = new Order();
order.setCustomerId(1001L);
order.setTotalAmount(new BigDecimal(“299.99”));
order.setStatus(OrderStatus.CONFIRMED);

OrderItem item1 = new OrderItem();
item1.setProductId(1L);
item1.setProductName(“Laptop”);
item1.setQuantity(1);
item1.setUnitPrice(new BigDecimal(“299.99”));
order.getItems().add(item1);

Order created = port.createOrderFromERP(order);
System.out.println(“ERP Created Order: ” + created.getOrderNumber());

// 查询订单
Order found = port.getOrderDetails(created.getOrderNumber());
System.out.println(“Found Order: ” + found.getStatus());
}
}
5.4.2 RESTful 客户端测试(移动端)
// 移动端 JavaScript 示例
class OrderAPI {
constructor(baseURL = ‘http://localhost:8080/api/v1’) {
this.baseURL = baseURL;
}

// 创建订单
async createOrder(orderData) {
const response = await fetch(`${this.baseURL}/orders`, {
method: ‘POST’,
headers: {
‘Content-Type’: ‘application/json’,
‘Authorization’: `Bearer ${this.getAuthToken()}`
},
body: JSON.stringify(orderData)
});

if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}

return await response.json();
}

// 查询订单
async getOrder(orderNumber) {
const response = await fetch(`${this.baseURL}/orders/${orderNumber}`, {
headers: {
‘Authorization’: `Bearer ${this.getAuthToken()}`
}
});

if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}

return await response.json();
}

// 取消订单
async cancelOrder(orderNumber) {
const response = await fetch(`${this.baseURL}/orders/${orderNumber}`, {
method: ‘DELETE’,
headers: {
‘Authorization’: `Bearer ${this.getAuthToken()}`
}
});

return response.ok;
}

getAuthToken() {
return localStorage.getItem(‘authToken’);
}
}

// 使用示例
const orderAPI = new OrderAPI();

// 创建订单
orderAPI.createOrder({
customerId: 1001,
items: [
{ productId: 1, productName: “Laptop”, quantity: 1, unitPrice: 299.99 },
{ productId: 2, productName: “Mouse”, quantity: 2, unitPrice: 19.99 }
]
}).then(order => {
console.log(‘Order created:’, order.orderNumber);
return orderAPI.getOrder(order.orderNumber);
}).then(order => {
console.log(‘Order details:’, order);
}).catch(error => {
console.error(‘Error:’, error);
});
第六部分:常见问题与解决方案汇总
6.1 SOAP 常见问题
Q1: 如何处理 SOAP 消息中的附件?
A
: 使用 MTOM (Message Transmission Optimization Mechanism)
@MTOM
@WebService
public interface FileService {
@WebMethod
void uploadFile(@WebParam(name = “filename”) String filename,
@WebParam(name = “data”) DataHandler data);

@WebMethod
DataHandler downloadFile(@WebParam(name = “filename”) String filename);
}
Q2: SOAP 服务如何实现认证?
A
: 使用 WS-Security 或在 Header 中传递 Token
@WebService
public class SecureService {

@WebMethod
public String getData(@WebParam(name = “authToken”) String token) {
if (!validateToken(token)) {
throw new WebServiceException(“Authentication failed”);
}
return “Secure data”;
}

private boolean validateToken(String token) {
// 验证逻辑
return token != null && token.startsWith(“VALID_”);
}
}
Q3: SOAP 服务性能优化?
A
:
启用连接池
使用异步处理
缓存频繁访问的数据
压缩消息体
// 异步 SOAP 服务
@WebService
public class AsyncOrderService {

@WebMethod
public Future createOrderAsync(Order order) {
return CompletableFuture.supplyAsync(() -> {
// 耗时操作
return processOrder(order);
});
}
}
6.2 RESTful 常见问题
Q1: 如何处理分页和大量数据?
A
: 使用分页查询和流式响应
@GetMapping(“/stream”)
public ResponseEntity streamOrders() {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_TYPE, “application/json”)
.body(outputStream -> {
JsonGenerator generator = new ObjectMapper().createGenerator(outputStream);
generator.writeStartArray();

orderRepository.findAll().forEach(order -> {
try {
generator.writeObject(order);
} catch (IOException e) {
throw new RuntimeException(e);
}
});

generator.writeEndArray();
generator.close();
});
}
Q2: 如何实现 API 版本兼容?
A
: 使用内容协商或 URI 版本控制
// 支持多版本响应
@GetMapping(produces = {“application/json”, “application/vnd.app-v1+json”})
public ResponseEntity getOrders(@RequestHeader(value = “Accept”, required = false) String accept) {
if (accept != null && accept.contains(“vnd.app-v2+json”)) {
return ResponseEntity.ok(getOrdersV2());
}
return ResponseEntity.ok(getOrdersV1());
}
Q3: 如何处理并发更新?
A
: 使用乐观锁或版本号
@Entity
public class Order {
@Id
private Long id;

@Version
private Long version; // 乐观锁版本号

// …
}

// 更新时检查版本
@PatchMapping(“/{id}”)
public ResponseEntity patchOrder(@PathVariable Long id,
@RequestBody Order updates,
@RequestParam Long version) {
Order existing = orderRepository.findById(id)
.orElseThrow(() -> new NotFoundException(“Order not found”));

if (!existing.getVersion().equals(version)) {
throw new ConflictException(“Order has been modified by another user”);
}

// 应用更新
// …

return ResponseEntity.ok(updated);
}
6.3 跨域与安全问题
Q1: 如何处理复杂的 CORS 场景?
A
: 使用代理或配置详细 CORS 策略
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOrigins(Arrays.asList(
“http://localhost:3000”,
“https://app.example.com”,
“https://admin.example.com”
));
config.setAllowedMethods(Arrays.asList(
“GET”, “POST”, “PUT”, “PATCH”, “DELETE”, “OPTIONS”
));
config.setAllowedHeaders(Arrays.asList(“*”));
config.setMaxAge(3600L);
source.registerCorsConfiguration(“/**”, config);
return new CorsFilter(source);
}
}
Q2: 如何防止 CSRF 攻击?
A
: RESTful API 中使用 Token 认证,SOAP 中使用 WS-Security
// RESTful CSRF 防护
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable() // API 通常禁用 CSRF,使用 Token
.authorizeRequests()
.antMatchers(“/api/public/**”).permitAll()
.anyRequest().authenticated()
.and()
.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
第七部分:总结与展望
7.1 核心要点回顾
SOAP 适合
:企业级集成、高安全性要求、严格契约、事务性操作
RESTful 适合
:移动应用、公共 API、微服务、资源导向操作
选择原则
:根据业务需求、团队技能、现有基础设施、性能要求综合考虑
混合架构
:在复杂系统中,可以同时使用两种架构,发挥各自优势
7.2 未来趋势
GraphQL
:作为 RESTful 的补充,提供更灵活的查询能力
gRPC
:高性能 RPC 框架,适合微服务内部通信
Serverless
:无服务器架构下的 Web Service
API Gateway
:统一的 API 管理和路由
OpenAPI/Swagger
:API 文档和代码生成标准
7.3 学习建议
从 RESTful 开始
:更容易上手,应用更广泛
理解协议差异
:深入理解 SOAP 和 REST 的设计哲学
实践项目
:通过实际项目巩固知识
关注安全
:始终将安全性放在首位
持续学习
:关注新技术和最佳实践
7.4 推荐资源
SOAP
:
JAX-WS 官方文档
WS-* 系列规范
Apache CXF 框架
RESTful
:
Richardson 成熟度模型
Spring Boot 官方文档
REST API 设计指南
工具
:
Postman (API 测试)
SoapUI (SOAP 测试)
Swagger/OpenAPI (API 文档)
Wireshark (网络抓包分析)
通过本教程的学习,您应该已经掌握了 SOAP 和 RESTful Web Service 的核心概念、开发流程和最佳实践。记住,技术的选择应该基于实际业务需求,而不是盲目追求新技术。在实际项目中,不断积累经验,形成自己的技术判断标准。