使用@CrossOrigin实现跨域请求

在Spring MVC4.2之后推出了@CrossOrigin注解来解决跨域问题,而在4.2之前我们都是通过定义注册过滤器的方式来解决跨域与问题的,所以在Spring4.2以后使用@CrossOrigin能一定程度上的简化解决跨域问题的方式。接下来我们就来介绍@CrossOrigin方式以及使用时的一些注意点

@CrossOrigin 会启用CORS  控制器方法CORS配置

因此,RESTful Web服务将在其响应中包含CORS访问控制头,您只需@CrossOrigin向处理程序方法添加注释


src/main/java/hello/GreetingController.java

例子:

  @CrossOrigin(originins =“http:// localhost:9000” 
    @GetMapping( “/ greeting” 公开问候语问候语(@RequestParam(required = false,defaultValue =“World” )字符串名称){
        System.out.println( “==== in greeting ====” );
        return  new Greeting(counter.incrementAndGet(),String.format(template,name));
    }

@CrossOrigin注解是被注解的方法具备接受跨域请求的功能。默认情况下,它使方法具备接受所有域,所有请求消息头的请求。。。。这个例子中,我们仅接受

http://localhost:9000发送来的跨域请求。


Controller类名上方添加@CrossOrigin 注解

通过此方式注解则Controller中的所有通过@RequestMapping注解的方法都可以进行跨域请求。 代码如下:

@CrossOrigin()
@RequestMapping("/demoController")
@Controller
public class DemoController {
	@Autowired
	IDemoService demoService;

	@RequestMapping(value = "/test", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel test(HttpServletRequest request)
			throws Exception {
		return “right”;
	}
}

@RequestMapping注解的方法上添加@CrossOrigin注解

通过此方式注解则只有此方法可以进行跨域请求。 代码如下:

@RequestMapping("/demoController")
@Controller
public class DemoController {
	@Autowired
	IDemoService demoService;

@CrossOrigin()
	@RequestMapping(value = "/test", method = RequestMethod.POST)
	@ResponseBody
	public ResultModel test(HttpServletRequest request)
			throws Exception {
		return “right”;
	}
}

在使用此注解时会发生的一些问题:

1. 注解失效问题

此时调用的方法的@RequestMapping中需要声明请求方式 即增加method=RequestMethod.XXX

2. 添加注解后session失效问题

此时对应的js的ajax中需要添加xhrFields:{withCredentials:true}(每个ajax中都需要加此属性,以保证session一致)如:

$.ajax({
		type: "post",
		url: server.path + '/user/login',
		xhrFields:{withCredentials:true},
		data: {
			username: uName,
			password: pwd
		},
		success: function (msg) {
+		    console.log('登录成功');
		},
		error: function (msg) {
			console.log('请求报错!');
		}
	})

对于附带身份凭证的请求(withCredentials:true),服务器不得设置 Access-Control-Allow-Origin 的值为“”。这是因为请求的首部中携带了 Cookie 信息,如果 Access-Control-Allow-Origin 的值为“”,请求将会失败。而将 Access-Control-Allow-Origin 的值设置为 http://foo.example,则请求将成功执行;其次服务器端需要设置Access-Control-Allow-Credentials: true,否则响应内容不会返回给请求的发起者。


说一下什么是跨域:

 

(站在巨人的肩膀上)

跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器施加的安全限制。

所谓同源是指,域名,协议,端口均相同,不明白没关系,举个栗子:

http://www.123.com/index.html 调用 http://www.123.com/server.php (非跨域)

http://www.123.com/index.html 调用 http://www.456.com/server.php (主域名不同:123/456,跨域)

http://abc.123.com/index.html 调用 http://def.123.com/server.php (子域名不同:abc/def,跨域)

http://www.123.com:8080/index.html 调用 http://www.123.com:8081/server.php (端口不同:8080/8081,跨域)

http://www.123.com/index.html 调用 https://www.123.com/server.php (协议不同:http/https,跨域)

请注意:localhost和127.0.0.1虽然都指向本机,但也属于跨域。

浏览器执行javascript脚本时,会检查这个脚本属于哪个页面,如果不是同源页面,就不会被执行。

详细参考

HTTP访问控制(CORS)详细说明

https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS


你可能感兴趣的:(spring)