SpringMVC4.2开始增加了cross解决方案,这里讲解的是通过在controller中添加注解@CrossOrigin的方式
- 查看@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
String[] DEFAULT_ORIGINS = new String[]{"*"};
@Deprecated
String[] DEFAULT_ALLOWED_HEADERS = new String[]{"*"};
@Deprecated
boolean DEFAULT_ALLOW_CREDENTIALS = false;
@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;
}
- 如果使用默认的配置那么可以看出来元注解中是默认允许所有域名,请求头,请求方式,cookie,
- 如果需要指定跨域的域名或者其它参数可以在注解中添加,例如.其它参数也可添加
@CrossOrigin(value = "http://www.twgfs.online",maxAge = 30,methods=RequestMethod.GET)