Spring Boot - CORS 支持
跨域资源共享 (CORS) 是一种安全概念,允许限制在 Web 浏览器中实现的资源。 它可以防止 JavaScript 代码生成或使用针对不同来源的请求。
例如,您的 Web 应用程序在 8080 端口上运行,并且通过使用 JavaScript,您正试图从 9090 端口使用 RESTful Web 服务。 在这种情况下,您将面临 Web 浏览器上的跨域资源共享安全问题。
处理此问题需要两个要求 −
RESTful Web 服务应该支持跨域资源共享。
RESTful Web 服务应用程序应允许从 8080 端口访问 API。
在本章中,我们将详细了解如何为 RESTful Web 服务应用程序启用跨域请求。
在控制器方法中启用 CORS
我们需要使用控制器方法的 @CrossOrigin 注解来设置 RESTful Web 服务的来源。 这个@CrossOrigin 注解支持特定的 REST API,而不是整个应用程序。
@RequestMapping(value = "/products")
@CrossOrigin(origins = "http://localhost:8080")
public ResponseEntity<Object> getProduct() {
return null;
}
全局 CORS 配置
我们需要定义显示的 @Bean 配置,以便为您的 Spring Boot 应用程序全局设置 CORS 配置支持。
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/products").allowedOrigins("http://localhost:9000");
}
};
}
下面给出了在主 Spring Boot 应用程序中全局设置 CORS 配置的代码。
package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/products").allowedOrigins("http://localhost:8080");
}
};
}
}
现在,您可以创建一个在 8080 端口上运行的 Spring Boot Web 应用程序和可以在 9090 端口上运行的 RESTful Web 服务应用程序。 有关 RESTful Web 服务实现的更多详细信息,您可以参考本教程的标题为使用 RESTful Web 服务的章节。

