Java教程

Java跨域问题解决

本文主要是介绍Java跨域问题解决,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

定义跨域ip 域名

cors.addMapping=/**
cors.allowedOrigins=http://localhost,http://localhost:8080,https://www.baidu.com
cors.allowCredentials=true
cors.allowedMethods=GET,POST,PUT,DELETE,OPTIONS
cors.max_age=3600
  • 读取配置文件
  • @ConfigurationProperties(
        prefix = "cors"
    )
    public class CorsProperties {
        private String addMapping;
        private String[] allowedOrigins;
        private Boolean allowCredentials;
        private String[] allowedMethods;
        private Integer maxAge;
    }
    

  • 配置跨域
  • @Configuration
    @EnableConfigurationProperties({CorsProperties.class})
    public class CorsConfig implements WebMvcConfigurer {
        @Autowired
        private CorsProperties properties;
    
        public CorsConfig() {
        }
    
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping(this.properties.getAddMapping())
                    .allowedOrigins(this.properties.getAllowedOrigins())
                    .allowCredentials(this.properties.getAllowCredentials())
                    .allowedMethods(this.properties.getAllowedMethods())
                    .maxAge((long) this.properties.getMaxAge());
            
        }
    }
    

这篇关于Java跨域问题解决的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!