springmvc, annotation CrossOrigin allows cross-domain and its use cases

 

 

Through testing, we can find that: js cross-domain is the behavior of the browser; the interface "not configured to allow cross-domain" can also be accessed by jquery code, but the browser prohibits the operation of the response result; we directly pass http-client Calling the interface is not restricted by cross-domain; therefore, the main help page of CrossOrigin accesses the interface of non-local domain. see image below

 

(Picture 1)

 

(Figure II)

 

 

References:

http://blog.csdn.net/relucent/article/details/45716325

https://www.zhihu.com/question/19618769

 

test code


<html>
<head>
	<!-- 
    <meta http-equiv="Access-Control-Allow-Origin" content="*">  
	 -->
	<meta charset="UTF-8">
	<script src="http://apps.bdimg.com/libs/jquery/2.1.3/jquery.min.js"></script>
	<script>
	function showMessage(url){
		$.getJSON(
			url,
			function(data){
				alert(data.msg);
			}
		);
	}
	
	function doClick(){
		var url = "http://127.0.0.1:8080/mgr/test/msg";
		showMessage(url);
	}
	
	function doClick0(){
		var url = "http://127.0.0.1:8080/mgr/test/msg0";
		showMessage(url);
	}
	</script>
</head>

<body>
<br/>
<br/>
<input type="button" value="允许跨域" onclick="doClick()"/>
<br/>
<input type="button" value="未允许跨域" onclick="doClick0()"/>
</body>
</html>

 

Service-Terminal:

/**
     * 已配为允许跨域访问
     * @return
     */
    @CrossOrigin(origins = "*",maxAge = 3000)
    @RequestMapping(value = "msg") @ResponseBody public Map<String,Object> getMessage(){
        Map<String,Object> ret = new LinkedHashMap<>();
        ret.put("code", 0);
        ret.put("msg", "msg");
        logger.info("ret:"+ret.toString());
        return ret;
    }

    /**
     * 未配置允许跨域访问
     * @return
     */
    @RequestMapping(value = "msg0") @ResponseBody public Map<String,Object> getMessage0(){
        Map<String,Object> ret = new LinkedHashMap<>();
        ret.put("code", 0);
        ret.put("msg", "msg0");
        logger.info("ret:"+ret.toString());
        return ret;
    }

Note: CrossOrigin requires jdk1.8+, spring 4.2+

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324404833&siteId=291194637