1. 程式人生 > >實現跨域的三種方式

實現跨域的三種方式

  1、CorsFilter       過濾器

  2、<mvc:cors>    Bean   在srping-web中配置

  3、@CorssOrigin   註解

 

CorsFilter的實現 

 

 1 package com.wgc.jsonp.filter;
 2 
 3 import org.springframework.web.cors.CorsConfiguration;
 4 import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
5 import org.springframework.web.filter.CorsFilter; 6 7 import javax.servlet.annotation.WebFilter; 8 import java.util.Arrays; 9 import java.util.Collections; 10 // 視為一個過濾器配置可以在web.xml配置,也可以直接使用註解 11 @WebFilter("/*") 12 public class MyCorsFilter extends CorsFilter { 13 public MyCorsFilter() {
14 super(configurationSource()); 15 } 16 17 private static UrlBasedCorsConfigurationSource configurationSource() { 18 19 UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); 20 CorsConfiguration configuration = new CorsConfiguration(); 21 // 設定允許訪問的網路
22 configuration.setAllowedOrigins(Collections.singletonList("http://192.168.1.133:8081")); 23 // 設定允許訪問的方法 24 configuration.setAllowedMethods(Arrays.asList(new String[]{"GET", "POST"})); 25 // 設定頭部資訊Access-Control-Allow-Origin是必須寫的 26 configuration.setAllowedHeaders(Collections.singletonList("Access-Control-Allow-Origin")); 27 // 設定是否從伺服器獲取cookie 28 configuration.setAllowCredentials(true); 29 // 設定準備響應前快取持續的最大時間 30 configuration.setMaxAge(Long.valueOf(3600)); 31 // 註冊configuration是那個方法或類上訪問的 32 source.registerCorsConfiguration("/mvc", configuration); 33 // 可以建立多個Configuration 34 return source; 35 } 36 37 }

 

 

 

 

<mvc:cors> 的實現:

 1 <mvc:cors>
 2        <!-- service方法是應用-->
 3        <mvc:mapping path="/mvc"
 4                     allowed-origins="http://192.168.1.133:8081"
 5                     allowed-methods="GET,POST"
 6                     allowed-headers="Access-Control-Allow-Origin"
 7                     allow-credentials="true"/>
 8        <!-- service類上應用-->
 9         <mvc:mapping path="/mvc/**"
10                      allowed-origins="http://192.168.1.133:8081, http://domain2.com"
11                      allowed-methods="GET,POST"
12                      allowed-headers="Access-Control-Allow-Origin"
13                      exposed-headers="header1, header2"
14                      allow-credentials="true"
15                      max-age="123"   />
16   </mvc:cors>                                                

 

@CorssOrigin的實現:

package com.wgc.jsonp.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@RestController
/*
*   將跨域設定在類上,那麼所有的 mapping 都會使用這個策略
*   如果不加引數,那麼將會使用配置中的預設引數
* */
/* @CrossOrigin */
public class JSONPController {
    @RequestMapping("/cors")
    public String demo(HttpServletResponse response, String callback) {
        return callback + "('sdfdsf')";
    }

    @RequestMapping("/jsonpdata")
    public String demo1(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "http://192.168.1.178:8081");
        return "susses";
    }

    @RequestMapping("/mvc")
    /*
    * origins:能訪問的網路ip
    * methods:允許什麼方法可以訪問
    * allowedHeaders:頭部資訊,這裡一定要寫上Access-Control-Allow-Origin
    * 如果還有其他頭部資訊可以使用逗號隔開; 如: {"Content-Type", "Access-Control-Allow-Origin"}
    * allowCredentials:cookie是否返回到伺服器,true是返回
    *maxAge:準備響應前快取持續的最大時間
    * */
    @CrossOrigin(origins = {"http://192.168.1.133:8081", "http://domain2.com"},
                methods = {RequestMethod.GET, RequestMethod.POST},
                allowedHeaders = {"Access-Control-Allow-Origin"},
                allowCredentials = "true",
                maxAge = 123445)
    public String demo2() {
        return  "hello, word";
    }

}

 

前臺程式碼:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>跨域</title>
    </head>
    <body>
        <script src="axios.js">
            
        </script>
        <!-- <button onclick="send()">java-web跨域傳送</button> -->
        <button onclick="send_mvc()">mvc 跨域</button>
        <script src="axios.js"></script>
        <script>
            function send() {
                axios({
                    method: 'get',
                    url: 'http://localhost:8080/test'
                }).then(res => console.log(res));
            }
            function send_mvc() {
                axios({
                    method: 'get',
                    url: 'http://localhost:8080/mvc'
                }).then(res => console.log(res.data));
            }
        </script>
    </body>
</html>