1、简介java
Web 开发常常会遇到跨域问题,解决方案有:jsonp,iframe,CORS 等等web
1.一、CORS与JSONP相比spring
一、JSONP只能实现GET请求,而CORS支持全部类型的HTTP请求。json
二、使用CORS,开发者能够使用普通的XMLHttpRequest发起请求和得到数据,比起JSONP 有更好的错误处理。api
三、JSONP主要被老的浏览器支持,它们每每不支持CORS,而绝大多数现代浏览器都已经支持了CORS浏览器支持状况跨域
Chrome 3+浏览器
Firefox 3.5+app
Opera 12+cors
Safari 4+ide
Internet Explorer 8+
2、实现CORS
说明:在springMVC中能够配置全局的规则,也能够使用@CrossOrigin注解进行细粒度的配置
2.一、全局配置
方式一:注册bean
package com.example.demo.utils.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * Created by DELL on 2017/6/18. */ @Configuration public class CustomCorsConfiguration { @Bean public WebMvcConfigurer corsConfigurer() { return new WebMvcConfigurerAdapter() { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**").allowedOrigins("http://localhost:8080"); } }; } }
说明:表示对于/api请求下的因此资源,容许http://localhost:8080访问
方式二:继承WebMvcConfigurerAdapter
package com.example.demo.utils.configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 跨域请求处理 * @Author: 我爱大金子 * @Description: 跨域请求处理 * @Date: Created in 10:12 2017/6/18 */ @Configuration public class CustomCorsConfiguration2 extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**").allowedOrigins("http://localhost:8080"); } }
说明:表示对于/api请求下的因此资源,容许http://localhost:8080访问
2.二、细粒度配置
在controller中加入@CrossOrigin注解,如:@CrossOrigin(origins = "http://localhost:8080")