java跨域解决

 

 

 

import java.util.ArrayList;
import java.util.List;
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.CorsRegistration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class CorsConfig
  extends WebMvcConfigurerAdapter
{
  public void addCorsMappings(CorsRegistry registry)
  {
    registry.addMapping("/**").allowedOrigins(new String[] { "*" }).allowCredentials(true).allowedMethods(new String[] { "GET", "HEAD", "POST", "DELETE", "PUT", "OPTIONS" }).maxAge(3600L);
  }
  
  private CorsConfiguration buildConfig()
  {
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    List<String> list = new ArrayList();
    list.add("*");
    corsConfiguration.setAllowedOrigins(list);
    
    corsConfiguration.addAllowedOrigin("*");
    corsConfiguration.addAllowedHeader("*");
    corsConfiguration.addAllowedMethod("*");
    return corsConfiguration;
  }
  
  @Bean
  public CorsFilter corsFilter()
  {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", buildConfig());
    return new CorsFilter(source);
  }
}

 

posted @ 2018-08-14 14:53  这个名字想了很久~  阅读(251)  评论(0编辑  收藏  举报