在Spring MVC中处理跨域请求(CORS,Cross-Origin Resource Sharing)通常涉及到配置HTTP响应头,以允许来自不同源的请求。Spring MVC提供了多种方式来配置CORS,包括全局配置和局部配置。
- 使用@CrossOrigin注解
在控制器的方法上使用@CrossOrigin注解是最简单的方法之一。
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@CrossOrigin(origins = "http://example.com", maxAge = 3600)
@GetMapping("/data")
public MyData getData() {
return new MyData("Some Data");
}
}
- 配置WebMvcConfigurer
如果你想要全局配置CORS,可以通过实现WebMvcConfigurer接口并重写addCorsMappings方法来实现。
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("/**") // 匹配所有路径
.allowedOrigins("http://example.com") // 允许的源
.allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的方法
.allowedHeaders("*") // 允许的头部
.allowCredentials(true) // 是否发送cookies
.maxAge(3600); // 预检请求的缓存时间(秒)
}
}
- 使用GlobalCorsConfigurationSource和CorsFilter
如果你想要更细粒度的控制或者需要在非Spring MVC环境中应用CORS,可以使用GlobalCorsConfigurationSource和CorsFilter。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Arrays;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.setAllowedOrigins(Arrays.asList("http://example.com")); // 允许的源列表
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE")); // 允许的方法列表
config.setAllowedHeaders(Arrays.asList("*")); // 允许的头部列表,使用*表示接受所有头部信息
source.registerCorsConfiguration("/**", config); // 对所有路径应用此配置
return new CorsFilter(source);
}
}
- 使用@CrossOrigin在全局配置中启用默认配置(不推荐)
虽然不推荐在生产环境中使用全局的@CrossOrigin注解(因为它可能会影响到所有的接口),但在开发阶段或者在测试环境中,可以这样做:
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.context.annotation.*;
import org.springframework.*;
import java.*; // 注意:这里的导入只是为了示例,实际开发中应避免使用通配符导入所有包。
import static java.*; // 同上。
import javax.*; // 同上。
import org.*; // 同上。注意:尽量避免使用通配符导入所有包。正确的做法是只导入需要的包。例如:import org.springframework.*。这里的写法仅为示例,实际开发中请避免。正确的做法是:import org.springframework.*; import javax.*; import java.*; import java.*; import static java.*; import static javax.*; import static org.*; 这样写只是为了示例,实际开发中请避免使用通配符导入所有包。正确的做法是:只导入需要的包。例如:import org.*; 但请注意,这里的写法只是为了示例,实际开发中请