解决跨域问题的方式有很多,这里主要是添加注解的方式和采用添加拦截器的方法:

方法一、spring boot中只用在Controller类上添加一个“@CrossOrigin“注解就可以实现对当前controller的跨域 访问了,当然这个标签也可以加到方法上。

@CrossOrigin
public class CommonController {
}

其他controller类继承以上这个类就可以解决跨域问题。

注意:“@CrossOrigin“注解要求jdk1.8以上版本

方法二、采用添加拦截器的方法

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
private EnvConfig envConfig;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new HandlerInterceptor() {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
boolean isTrue = envConfig.getIsDev();//判断是测试服才需要解决跨域问题
if (isTrue) {
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers",
"Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token");
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception {
}
});
}
}

方法三:@Configuration启动容器+@Bean注册Bean

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;
/**
* @author: zhuhualian
* @date: 2019-12-19 17:13
* @description:
*/
@Configuration
public class CorsConfig {
public CorsConfig() {
// TODO Auto-generated constructor stub
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
//“*”代表全部。”**”代表适配所有接口。
//其中addAllowedOrigin(String origin)方法是追加访问源地址。如果不使用”*”(即允许全部访问源),则可以配置多条访问源来做控制。
corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
return corsConfiguration;
//corsConfiguration.addAllowedOrigin("http://www.aimaonline.cn/");
//corsConfiguration.addAllowedOrigin("http://test.aimaonline.cn/");
}
}