前言
只是簡單的配置實現了cors,並沒有講任何東西。(有興趣的可看: CORS 跨域 實現思路及相關解決方案)
github: https://github.com/vergilyn/SpringBootDemo
代碼位置:
origin:表示服務端程序(默認為:127.0.0.1:8080)。其中有CorsFilter,且allow-origina配置為http://127.0.0.1:8081。
client_a/client_b:分別是客戶端。其中client_a的端口號是8081,client_b的端口號是8082.

@SpringBootApplication public class CorsOriginApplication { public final static String CORS_ADDRESS = "127.0.0.1"; public static void main(String[] args) { SpringApplication.run(CorsOriginApplication.class,args); } }
@Controller @RequestMapping("/cors") public class CorsOriginController { /** * 如果CrosFilter中配置有Access-Control-Allow-Origin, 則CrossOrigin無效。 * 否則, 以@CrossOrigin為准。 * @return */ @CrossOrigin(origins = "http://127.0.0.1:8082") @RequestMapping("/get") @ResponseBody public Map<String,Object> get(){ return Constant.map; } }
@Configuration @WebFilter(urlPatterns = "/cors") public class CorsFilter extends OncePerRequestFilter { private final static String ALLOWORIGIN_CORS_A = "http://127.0.0.1:8081"; private final static String ALLOWORIGIN_CORS_b = "http://127.0.0.1:8082"; @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // Access-Control-Allow-Origin: 指定授權訪問的域 response.addHeader("Access-Control-Allow-Origin", ALLOWORIGIN_CORS_A); //此優先級高於@CrossOrigin配置 // Access-Control-Allow-Methods: 授權請求的方法(GET, POST, PUT, DELETE,OPTIONS等) response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Max-Age", "1800");//30 min filterChain.doFilter(request, response); } }
注意:
如果在CorsFilter中配置有"Access-Control-Allow-Origin", 則controller中方法注解@CrossOrigin失效。(即filter的優先級高於@CrossOrigin方法注解)
Cors A:
@SpringBootApplication @Controller public class CorsAApplication implements EmbeddedServletContainerCustomizer { private static int CORS_A_PORT = 8081; public static void main(String[] args) { SpringApplication app = new SpringApplication(CorsAApplication.class); app.run(args); } @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.setPort(CORS_A_PORT); } @RequestMapping("corsA") public String index(Model model){ model.addAttribute("port",CORS_A_PORT); model.addAttribute("address", CorsOriginApplication.CORS_ADDRESS); return "cors/corsA_index"; } }
corsA_index.html:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <script type="text/javascript" src="./static/common/jquery-2.1.4.js"></script> <title>cors client_a</title> <script type="text/javascript"> /*<![CDATA[*/ function corsFilter() { var url = "http://localhost:8080/cors/get"; $.ajax({ type: 'get', url: url, data: {}, success: function (r) { $("#result").text(JSON.stringify(r)); }, error: function (err) { console.info(err); alert('error!'); } }); } /*]]>*/ </script> </head> <body> <h4>cors client_a</h4> <p th:text="'server.address: ' + ${address}"/> <p th:text="'server.port: ' + ${port}"/> <p>cors配置: allowOrigin = "http://127.0.0.1:8081", 所以此頁面可以得到結果!</p> <input type="button" value="request" onclick="corsFilter()"/><br/> <h5>結果:</h5> <p id="result"></p> </body> </html>
Cors B:
@SpringBootApplication @Controller public class CorsBApplication implements EmbeddedServletContainerCustomizer { private static int CORS_B_PORT = 8082; public static void main(String[] args) { SpringApplication app = new SpringApplication(CorsBApplication.class); app.run(args); } @Override public void customize(ConfigurableEmbeddedServletContainer container) { container.setPort(CORS_B_PORT); } @RequestMapping("corsB") public String index(Model model){ model.addAttribute("port",CORS_B_PORT); model.addAttribute("address", CorsOriginApplication.CORS_ADDRESS); return "cors/corsB_index"; } }
corsB_index.html:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> <script type="text/javascript" src="./static/common/jquery-2.1.4.js"></script> <title>cors client_b</title> <script type="text/javascript"> /*<![CDATA[*/ function corsFilter() { var url = "http://localhost:8080/cors/get"; $.ajax({ type: 'get', url: url, data: {}, success: function (r) { $("#result").text(JSON.stringify(r)); }, error: function (err) { console.info(err); $("#errMsg").css("display","block"); alert('error!'); } }); } /*]]>*/ </script> </head> <body> <h4>cors client_b</h4> <p th:text="'server.address: ' + ${address}"/> <p th:text="'server.port: ' + ${port}"/> <p>cors配置: allowOrigin = "http://127.0.0.1:8081", 所以此頁面<font color="red">無法得到結果!</font></p> <input type="button" value="request" onclick="corsFilter()"/><br/> <h5>結果:</h5> <p id="result"></p> <h5>錯誤描述:</h5> <p id="errMsg" style="display: none"> 已攔截跨源請求:同源策略禁止讀取位於 http://localhost:8080/cors/get 的遠程資源。(原因:CORS 頭 'Access-Control-Allow-Origin' 不匹配 'http://127.0.0.1:8081')。 </p> </body> </html>
結果演示:
1. 127.0.0.1:8081/corsA可以正確的請求"http://localhost:8080/cors/get"並正確得到返回的結果。
2. 127.0.0.1:8082/corsB可以正確的請求"http://localhost:8080/cors/get"但無法正確得到請求結果。