Cors解决跨域问题之注解方式

SpringMVC4.2开始增加了cross解决方案,这里讲解的是通过在controller中添加注解@CrossOrigin的方式

  1. 查看@CrossOrigin的源码可以了解到该注解默认集成了跨域配置的相关配置,只需要在这个注解中加入一些参数即可
package org.springframework.web.bind.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;

@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 = false;
    /** @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;
}
  1. 如果使用默认的配置那么可以看出来元注解中是默认允许所有域名,请求头,请求方式,cookie,
  2. 如果需要指定跨域的域名或者其它参数可以在注解中添加,例如.其它参数也可添加
@CrossOrigin(value = "http://www.twgfs.online",maxAge = 30,methods=RequestMethod.GET)
发布了19 篇原创文章 · 获赞 7 · 访问量 6625

猜你喜欢

转载自blog.csdn.net/William_TWG/article/details/104976086
今日推荐