Avant-propos: CorsFilter / WebMvcConfigurer / @CrossOrigin nécessite SpringMVC 4.2 ou supérieur pour prendre en charge, correspondant à SpringBoot 1.3 ou supérieur, ces fonctionnalités CORS sont prises en charge. Cependant, les amis qui utilisent Spring MVC 4.2 et inférieurs n'ont pas à paniquer. Il est également possible d'utiliser directement la méthode 4 pour autoriser l'accès inter-domaines CORS en ajoutant manuellement des en-têtes de réponse.
Le premier point: problèmes interdomaines, solutions back-end, il y a quatre manières comme suit .
Méthode 1: renvoyer un nouveau 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;
@Configuration
public class CorsConfig {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setMaxAge(3600L);
corsConfiguration.setAllowCredentials(true);
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig());
return new CorsFilter(source);
}
}
Méthode 2: réécrire WebMvcConfigurer
@Configuration
public class WebMvcConfg implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的路径
registry.addMapping("/**")
//设置允许跨域请求的域名
//当**Credentials为true时,**Origin不能为星号,需为具体的ip地址【如果接口不带cookie,ip无需设成具体ip】
.allowedOrigins("http://localhost:9527", "http://127.0.0.1:9527", "http://127.0.0.1:8082", "http://127.0.0.1:8083")
//是否允许证书 不再默认开启
.allowCredentials(true)
//设置允许的方法
.allowedMethods("*")
//跨域允许时间
.maxAge(3600);
}
}
Méthode 3: utiliser des annotations (@CrossOrigin)
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/admin/sysLog")
@CrossOrigin
public class SysLogController {
}
Méthode 4: définir manuellement l'en-tête de réponse (HttpServletResponse)
De cette manière, vous pouvez l'ajouter manuellement au contrôleur, au récepteur, au filtre et à toute autre logique spécifiques.
@RequestMapping("/test")
@ResponseBody
public String test(){
response.addHeader("Access-Control-Allow-Origin", "http://localhost:8080");
return "success";
}
Résumé : Voici quatre façons de configurer la solution de backend inter-domaines cors. L'essence est similaire à la dernière pour définir l'en-tête de réponse, mais chaque package implémente une logique d'encapsulation différente.