例如:a页⾯想获取b页⾯资源,如果a、b页⾯的协议、域名、端⼝、⼦域名不同,所进⾏的访问⾏动都是跨域的,⽽浏览器
为了安全问题⼀般都限制了跨域访问,也就是不允许跨域请求资源。注意:跨域限制访问,其实是浏览器的限制。理解这⼀点
很重要
同源策略:是指协议,域名,端⼝都要相同,其中有⼀个不同都会产⽣跨域;
springboot解决跨域的几种方式方法一、springboot的注解@crossorigin直接在controller方法或者类上增加@crossorigin注解,springmvc使用@crossorigin使用场景要求 jdk1.8+ spring4.2+
@getmapping("/hello")@crossoriginpublic string hello() { return "hello:" + simpledateformat.format(new date());}
方式二:使用corsfilterimport org.springframework.context.annotation.bean;import org.springframework.context.annotation.configuration;import org.springframework.web.cors.corsconfiguration;import org.springframework.web.cors.urlbasedcorsconfigurationsource;import org.springframework.web.filter.corsfilter;@configurationpublic class configconfiguration { @bean public corsfilter corsfilter() { corsconfiguration corsconfiguration = new corsconfiguration(); corsconfiguration.addallowedoriginpattern("*"); corsconfiguration.addallowedheader("*"); corsconfiguration.addallowedmethod("*"); corsconfiguration.setallowcredentials(true); urlbasedcorsconfigurationsource ub = new urlbasedcorsconfigurationsource(); ub.registercorsconfiguration("/**", corsconfiguration); return new corsfilter(ub); }}
方式三:自定义过滤(web filter)的方式@componentpublic class customfilter implements filter { @override public void dofilter(servletrequest servletrequest, servletresponse servletresponse, filterchain filterchain) throws ioexception, servletexception { httpservletresponse res = (httpservletresponse) servletresponse; // 设置允许cookie res.addheader("access-control-allow-credentials", "true"); // 允许http://www.xxx.com域(自行设置,这里只做示例)发起跨域请求 res.addheader("access-control-allow-origin", "*"); // 设置允许跨域请求的方法 res.addheader("access-control-allow-methods", "get, post, delete, put"); // 允许跨域请求包含content-type res.addheader("access-control-allow-headers", "content-type,x-caf-authorization-token,sessiontoken,x-token"); if (((httpservletrequest) servletrequest).getmethod().equals("options")) { servletresponse.getwriter().println("ok"); return; } filterchain.dofilter(servletrequest, servletresponse); }}
方式四:实现webmvcconfigurer中addcorsmappings方法import org.springframework.stereotype.component;import org.springframework.web.servlet.config.annotation.corsregistry;import org.springframework.web.servlet.config.annotation.webmvcconfigurer;@componentpublic class mywebmvcconfigurer implements webmvcconfigurer { @override public void addcorsmappings(corsregistry registry) { registry.addmapping("/**") // 匹配所有的路径 .allowcredentials(true) // 设置允许凭证 .allowedheaders("*") // 设置请求头 .allowedmethods("get", "post", "put", "delete") // 设置允许的方式 .allowedoriginpatterns("*"); }}
方法五:采用nginx做动态代理以上就是springboot解决跨域的方式有哪些的详细内容。
