Spring Boot RESTful Web Service with CORS 项目教程
项目介绍
本项目基于 Spring Boot 框架,展示了如何创建一个支持跨域资源共享(CORS)的 RESTful Web 服务。CORS 是一种机制,允许服务器指示浏览器从不同的源(域、协议或端口)加载资源。通过本项目,开发者可以学习如何在 Spring Boot 应用中配置 CORS,以便在现代 Web 应用中实现跨域请求。
项目快速启动
1. 环境准备
- Java 17 或更高版本
- Maven 3.x
- Git
2. 克隆项目
git clone https://github.com/spring-guides/gs-rest-service-cors.git
cd gs-rest-service-cors/complete
3. 构建和运行项目
mvn clean install
mvn spring-boot:run
4. 访问服务
启动项目后,可以通过浏览器或 Postman 访问以下 URL 来测试服务:
- 获取问候信息:
http://localhost:8080/greeting
5. 核心代码
GreetingController.java
package com.example.restservicecors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
return new Greeting(String.format(template, name));
}
}
Greeting.java
package com.example.restservicecors;
public class Greeting {
private final String content;
public Greeting(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
WebConfig.java
package com.example.restservicecors;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/greeting")
.allowedOrigins("http://localhost:9000");
}
}
应用案例和最佳实践
应用案例
-
前后端分离应用:在前后端分离的架构中,前端应用通常运行在一个独立的域名或端口上,而后端服务运行在另一个域名或端口上。通过配置 CORS,前端应用可以安全地访问后端服务。
-
微服务架构:在微服务架构中,不同的服务可能运行在不同的域名或端口上。通过配置 CORS,可以实现服务之间的跨域调用。
最佳实践
-
限制允许的源:在配置 CORS 时,应尽量限制允许的源(
allowedOrigins),避免开放过多的域名,以减少安全风险。 -
使用全局配置:对于多个控制器或多个方法需要支持 CORS 的情况,可以使用全局配置,避免在每个控制器或方法中重复配置。
-
设置适当的 CORS 头:根据实际需求,设置适当的 CORS 头,如
Access-Control-Allow-Methods、Access-Control-Allow-Headers等。
典型生态项目
-
Spring Security:Spring Security 提供了更细粒度的 CORS 配置,可以与 Spring Boot 应用无缝集成,提供更强大的安全控制。
-
Spring Data REST:Spring Data REST 可以自动生成 RESTful API,并支持 CORS 配置,适用于快速构建数据驱动的 RESTful 服务。
-
Spring Cloud Gateway:Spring Cloud Gateway 是一个微服务网关,支持 CORS 配置,可以作为微服务架构中的统一入口,处理跨域请求。
通过本教程,您可以快速上手 Spring Boot 的 CORS 配置,并在实际项目中应用这些知识。
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



