1.使用@CrossOrigin注解
1.1 假设项目二的端口号为8081,项目一的端口号为8080,项目二想要访问项目一的接口,可以在项目一中使用注解解决跨域问题
1.2 @CrossOrigin既可以加在单个方法上也可以加在类上面
package com.yl.cors01.controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@CrossOrigin(value = "http://localhost:8081",maxAge = 1500)
@GetMapping("/hello")
public String hello() {
return "hello corso1";
}
}
2.实现WebMvcConfigurer接口重写addCorsMappings方法
package com.yl.cors01.config;
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 org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedHeaders("*")
.allowedMethods("*")
.allowedOrigins("http://localhost:8081")
.maxAge(1900);
}
}
3.提供一个CorsFilter实例并且注册到容器中
package com.yl.cors01.config;
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 org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Bean
CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.addAllowedOrigin("http://localhost:8081");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**",config);
return new CorsFilter(source);
}
}