Java開發中解決Js的跨域問題

主流方法有JSONP和CORS兩種,這裡記一下後者的方式,理論基礎就是在請求的時候在http請求頭中添加如下屬性:

//指定允許其他域名訪問
Access-Control-Allow-Origin:http://localhost:8989

如果後端用Java開發,在返回請求中可以添加如下屬性

1.在跨域問題中,如果不操作cookie,只需要在後端代碼中添加如下代碼就可以

response.setHeader("Access-Control-Allow-Origin", "http://localhost:8989");
//第二個參數的意思就是說是哪個地址訪問,如果要通配全部,就使用*即可
  • 雖然是加在了response中,但是HTTP是基於TCP(傳輸層協議)的應用層協議,每次請求的時候都會有“三次握手”的過程,所以添加在response中後,會在第一次請求中告知客戶端可以請求。
  • 如果是SpringMVC4.2以上版本的話,一個註解就可以搞定
    *
@CrossOrigin(origins="http://localhost:8080")

這個註解就是對上邊的代碼的封裝,源碼如下:

@Target({ElementType.TYPE, ElementType.METHOD})
@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;
}
  • @Deprecated:若某類或某方法加上該註解之後,表示此方法或類不再建議使用,調用時也會出現刪除線,但並不代表不能用,只是說,不推薦使用,因為還有更好的方法可以調用。

2.如果跨域請求中涉及了對cookie的操作,就要添加一個屬性,代碼和註解分別為

response.setHeader("Access-Control-Allow-Origin", "http://localhost:8989");
response.setHeader("Access-Control-Allow-Credentials", "true");
@CrossOrigin(origins="http://localhost:8989",allowCredentials="true")

本文由博客一文多發平臺 https://openwrite.cn?from=article_bottom 發佈!


分享到:


相關文章: