Spring设置跨域
全局跨域设置
定义bean
@Configuration
public class CorsFilter {
@Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
// .addMapping里面为匹配的地址 .allowed为跨域规则
registry.addMapping("/**").allowedOrigins("*");
registry.addMapping("/**").allowedMethods("*");
registry.addMapping("/**").allowedHeaders("*");
}
};
}
}
注解配置跨域规则
package com.example.restservicecors;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.CrossOrigin;
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!";
private final AtomicLong counter = new AtomicLong();
// origins为当前请求的跨域规则
@CrossOrigin(origins为当前 = "http://localhost:8080")
@GetMapping("/greeting")
public Greeting greeting(@RequestParam(required = false, defaultValue = "World") String name) {
System.out.println("==== get greeting ====");
return new Greeting(counter.incrementAndGet(), String.format(template, name));
}
}
注解变量:
- origins
- methods
- allowedHeaders
- exposedHeaders
- allowCredentials
- maxAge