• spring cors的三种方式


    @CrossOrigin 注解

    如果想要对某一接口配置 CORS,可以在方法上添加 @CrossOrigin 注解 :

    @CrossOrigin(origins = "http://localhost:3000", allowCredentials = "true")
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String greetings() {
        return "{"project":"just a test"}";
    }
    

    如果想对一系列接口添加 CORS 配置,可以在类上添加注解,对该类声明所有接口都有效:

    @CrossOrigin(origins = {"http://localhost:9000", "null"})
    @RestController
    @SpringBootApplication
    public class SpringBootCorsTestApplication {
        
    }
    

    全局配置类

    由于WebMvcConfigurerAdapter类被弃用,新的实现是:

    @Configuration
    public class WebMvcConfg implements WebMvcConfigurer {
      //省略
    }
    @Configuration
    public class WebMvcConfg extends WebMvcConfigurationSupport {
      //省略
    }
    

    所以配置类可以这样写:

    @Configuration
    public class WebMvcConfig  implements WebMvcConfigurer{
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("http://localhost.com")
                    .allowedMethods("GET", "POST")
                    .allowedHeaders()
                    .allowCredentials(true);
        }
    }
    

    也可以这样写:

    @Configuration
    public class WebMvcConfig {
        @Bean
        public WebMvcConfigurationSupport corsBeanConfigurer() {
            return new WebMvcConfigurationSupport() {
                @Override
                protected void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**")
                            .allowedOrigins("http://localhost.com")
                            .allowedMethods("GET", "POST", "PUT", "DELETE")
                            .allowedHeaders()
                            .allowCredentials(true);
                }
            };
        }
    }
    

    过滤器

    过滤器添加头

    @Configuration
    public class MyConfiguration {
    
    	@Bean
    	public FilterRegistrationBean corsFilter() {
    		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    		CorsConfiguration config = new CorsConfiguration();
    		config.setAllowCredentials(true);
    		config.addAllowedOrigin("http://domain1.com");
    		config.addAllowedHeader("*");
    		config.addAllowedMethod("*");
    		source.registerCorsConfiguration("/**", config);
    		FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    		bean.setOrder(0);
    		return bean;
    	}
    }
    
  • 相关阅读:
    在Chrome浏览器中保存的密码有多安全?
    进程上下文切换 – 残酷的性能杀手(上)
    进程上下文切换 – 残酷的性能杀手(下)
    javascript推荐书籍
    使用Visual Studio 利用WinGDB编译和远程调试嵌入式Linux的程序
    Source Insight 3.X 标签插件v1.0发布
    QQ空间自动发广告解决方法
    Java---实力弹弹球,弹弹弹
    HDOJ 2027 统计元音
    Java---计算机贷款支付额计算(用对话框实现)
  • 原文地址:https://www.cnblogs.com/arrayblog/p/14196787.html
Copyright © 2020-2023  润新知