springboot集成cors

1、支持全局的数据跨域

package com.eba.corsconfig;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;


/**
 * Created by Thinkpad on 2018/2/13.
 * 全局CORS配置
 */
@Configuration
public class CORSConfiguration {


    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
// registry.addMapping("/api/**");
                registry.addMapping("/**")
                        .allowedOrigins("http://domain.com", "http://domain2.com")
                        .allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS")
                        .allowCredentials(false).maxAge(3600);
            }
        };
    }

}

2、局部的数据跨域问题  ----自定义注解的数据跨域

package com.eba.corsconfig;


import org.springframework.core.annotation.AliasFor;
import org.springframework.web.bind.annotation.RequestMethod;


import java.lang.annotation.*;


/**
 * Created by Thinkpad on 2018/2/13.
 * 注解方式实现数据跨域,可以在整个controller类上,也可以在某个方法上去
 * @CrossOrigin注解方式 Controller method CORS configuration
 */


/**1、整个controller类上
 * @CrossOrigin(origins = "http://domain2.com",
  maxAge = 3600,
   methods = {RequestMethod.GET, RequestMethod.POST})
  2、某个方法上@CrossOrigin
 */
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CrossOrigin {
    /** @deprecated */
    @Deprecated
    String[] DEFAULT_ORIGINS = new String[]{"*"};
    /** @deprecated */
    @Deprecated
    String[] DEFAULT_ALLOWED_HEADERS = new String[]{"*"};
    /** @deprecated */
    @Deprecated
    boolean DEFAULT_ALLOW_CREDENTIALS = true;
    /** @deprecated */
    @Deprecated
    long DEFAULT_MAX_AGE = 1800L;


    @AliasFor("origins")
    String[] value() default {};


    @AliasFor("value")
    String[] origins() default {};


    String[] allowedHeaders() default {};


    String[] exposedHeaders() default {};


    RequestMethod[] methods() default {};


    String allowCredentials() default "";


    long maxAge() default -1L;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞腾创客

你的鼓励是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值