springboot解决跨域配置类
时间: 2023-02-19 19:23:44 浏览: 77
Spring Boot提供了一种简单的方式来解决跨域问题,只需在application.properties文件中添加以下配置即可:
server.cors.enabled=true
server.cors.allowed-origins=*
server.cors.allowed-methods=GET,PUT,POST,DELETE,OPTIONS
server.cors.allowed-headers=*
相关问题
springboot万能跨域配置
在 Spring Boot 中,可以通过配置 WebMvcConfigurer 来实现跨域访问。
具体实现步骤如下:
1. 创建一个配置类 CorsConfig。
```java
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // 允许跨域访问的路径
.allowedOrigins("*") // 允许跨域访问的源
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE") // 允许请求方法
.maxAge(168000) // 预检间隔时间
.allowedHeaders("*") // 允许头部设置
.allowCredentials(true); // 是否发送cookie
}
}
```
2. 在主类上添加注解 @EnableWebMvc。
```java
@SpringBootApplication
@EnableWebMvc
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
这样就完成了跨域访问的配置,允许所有来源的请求访问。如果需要更细粒度的配置,可以根据需要修改 CorsConfig 类中的参数。
springboot的跨域配置
### Spring Boot 中实现跨域资源共享 (CORS) 的方法
#### 方法一:使用 `@CrossOrigin` 注解
在 Controller 类或者具体的方法上使用 `@CrossOrigin` 注解来允许特定源的跨域请求。这种方式适合于细粒度地控制某些接口的跨域行为。
```java
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@CrossOrigin(origins = "http://example.com")
@RestController
public class MyController {
@GetMapping("/greeting")
public String greeting() {
return "Hello, World!";
}
}
```
此代码片段展示了如何通过 `@CrossOrigin` 注解指定允许来自 `http://example.com` 域名下的跨域请求[^2]。
#### 方法二:配置全局 CORS 政策
另一种方式是在应用启动时设置全局的 CORS 政策,适用于整个应用程序范围内的跨域需求。这通常通过创建并注册一个自定义的 WebMvcConfigurer 来完成。
```java
import org.springframework.context.annotation.Bean;
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 CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS");
}
};
}
}
```
上述例子中,在 `/` 路径下所有的 HTTP 请求都将被授予从 `http://example.com` 发起的权利,并限定了可接受的操作类型[^3]。
这两种方案提供了灵活性,可以根据实际项目的需求选择最合适的解决方案。对于简单的场景可以直接采用注解的方式;而对于更复杂的情况,则建议利用全局配置来进行统一管理。
阅读全文
相关推荐













