一、对于先后端分离的项目来讲,若是前端项目与后端项目部署在两个不一样的域下,那么势必会引发跨域问题的出现。html
针对跨域问题,咱们可能第一个想到的解决方案就是jsonp,而且之前处理跨域问题我基本也是这么处理。前端
可是jsonp方式也一样有不足,无论是对于前端仍是后端来讲,写法与咱们日常的ajax写法不一样,一样后端也须要做出相应的更改。而且,jsonp方式只能经过get请求方式来传递参数,固然也还有其它的不足之处,web
jQuery ajax方式以jsonp类型发起跨域请求,其原理跟<script>脚本请求同样,所以使用jsonp时也只能使用GET方式发起跨域请求。跨域请求须要服务端配合,设置callback,才能完成跨域请求。ajax
针对于此,我并无急着使用jsonp的方式来解决跨域问题,去网上找寻其它方式,也就是本文主要所要讲的,在springboot中经过cors协议解决跨域问题。spring
二、Cors协议json
H5中的新特性:Cross-Origin Resource Sharing(跨域资源共享)。经过它,咱们的开发者(主要指后端开发者)能够决定资源是否能被跨域访问。后端
cors是一个w3c标准,它容许浏览器(目前ie8如下还不能被支持)像咱们不一样源的服务器发出xmlHttpRequest请求,咱们能够继续使用ajax进行请求访问。跨域
具体关于cors协议的文章 ,能够参考http://www.ruanyifeng.com/blog/2016/04/cors.html 这篇文章,讲的至关不错。浏览器
三、springboot中解决方案springboot
a. 建立一个filter解决跨域。
@Component public class SimpleCORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, HEAD"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) {} public void destroy() {} }
b. 基于WebMvcConfigurerAdapter配置加入Cors的跨域
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class CorsConfig extends WebMvcConfigurerAdapter { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowCredentials(true) .allowedMethods("GET", "POST", "DELETE", "PUT") .maxAge(3600); } }
@CrossOrigin(origins = "http://192.168.1.10:8080", maxAge = 3600) @RequestMapping("rest_index") @RestController public class IndexController{
若是你想作到更细致也可使用@CrossOrigin这个注解在controller类中使用。
这样就能够指定该controller中全部方法都能处理来自http:19.168.1.10:8080中的请求。
第一种Filter的方案也支持springmvc。
第二种经常使用于springboot。