Spring mvc 跨域解决方案

什么是跨域

一句话:同一个ip、同一个网络协议、同一个端口,三者都满足就是同一个域,否则就是跨域。

为什么非得跨域

基于两个方面:
a. web应用本身是部署在不同的服务器上
b.基于开发的角度 — 前后端分离
web应用本身是部署在不同的服务器上,对应的域名也就有所不同
比如百度。
主域名:https://www.baidu.com/
二级域名:http://image.baidu.com/, http://music.baidu.com/,http://wenku.baidu.com/
需要在不同的域之间,通过ajax方式互相请求,是非常常见的需求。

spring使用jsonp解决跨域

Spring 4中增加了对jsonp的原生支持,只需要ControllerAdvice就可以开启,方法如下:
首先新建一个Advice类,我们叫做“JsonpAdvice”,然后在里面定义接收jsonp请求的参数key:

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;
/**
* 使用jsonp实现跨域的支持
* @author admin
*/
@ControllerAdvice("cn.isy.web.sso.web")
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {
   public JsonpAdvice() {
       super("callback");
   }
}

@ControllerAdvice(“cn.isy.web.sso.web”)指定作用的包名
supper(“callback”)指定的是url中callback:
http://sso.isy.cn/logout?callback=successCallback

注意:
我们还可以重写AbstractJsonpResponseBodyAdvice中的feforeBodyWriteInternal方法:
做到实现url携带callback就返回jsonp格式,没有就返回正常格式
在这里插入图片描述

controller

controller中的代码正常编写就OK,不用修改任何东西。
只要保证在项目包下即可!

jquery ajax 注意:必须使用jsonp的方式提交请求!
$.ajax({  
     type : "get",  
     async:false,  
     dataType:'jsonp',
     url: 'http://sso.isy.cn/login.json',
     data: $("#loginForm").serialize(),
     crossDomain: true,
     jsonpCallback:"successCallback", 
     xhrFields: {
        withCredentials: true
     },
     success : function(data){ 
                  
     },  
     error:function(data){  
        console.log("登录出错");
        $.we.utils.gotoUrl("/");
      }  
});

使用CORS(跨域资源共享)解决跨域问题

有相关的cors不做过多介绍,不懂的可以自行百度查一下。

主要配置
Access-Control-Allow-Origin:  http://www.YOURDOMAIN.com            // 设置允许请求的域名,多个域名以逗号分隔
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS      // 设置允许请求的方法,多个方法以逗号分隔
Access-Control-Allow-Headers: Authorization                        // 设置允许请求自定义的请求头字段,多个字段以逗号分隔
Access-Control-Allow-Credentials: true                              // 设置是否允许发送 Cookies

使用注解CrossOrigin

在controller类上添加CrossOrigin注解表示当前类中的所有入口函数都
可以实现跨域。也可以指定某个conroller中具体的方法。
在这里插入图片描述

了解一下这个注解的内容:
在这里插入图片描述

jquery ajax的写法

$.ajax({  
    type : "get",  
    url: 'http://sso.isy.cn/login.json',
    data: $("#loginForm").serialize(),
    xhrFields: {
        withCredentials: true //注意这里必须指定否则cookie无法传递过去
    },
    success : function(data){ 
       
    },  
    error:function(data){  
        console.log("登录出错");
        $.we.utils.gotoUrl("/");
    }  
});

注意:这里不用使用jsonp的方式请求普通的ajax即可!,因为浏览器自己可以去做!

拓展:

HTTP请求头:

#请求域
Origin: ”http://localhost:3000“

#这两个属性只出现在预检请求中,即OPTIONS请求
Access-Control-Request-Method: ”POST“
Access-Control-Request-Headers: ”content-type“

HTTP响应头:

#允许向该服务器提交请求的URI,*表示全部允许,在SpringMVC中,如果设成*,会自动转成当前请求头中的Origin
Access-Control-Allow-Origin: ”http://localhost:3000“

#允许访问的头信息
Access-Control-Expose-Headers: "Set-Cookie"

#预检请求的缓存时间(秒),即在这个时间段里,对于相同的跨域请求不会再预检了
Access-Control-Max-Age: ”1800”

#允许Cookie跨域,在做登录校验的时候有用
Access-Control-Allow-Credentials: “true”

#允许提交请求的方法,*表示全部允许
Access-Control-Allow-Methods:GET,POST,PUT,DELETE,PATCH

对于简单跨域和非简单跨域,可以这么理解:

1.简单跨域就是GET,HEAD和POST请求,但是POST请求的"Content-Type"只能是application/x-www-form-urlencoded, multipart/form-data 或 text/plain
2.反之,就是非简单跨域,此跨域有一个预检机制,说直白点,就是会发两次请求,一次OPTIONS请求,一次真正的请求

CorsFilter: 过滤器阶段的CORS

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        // 对响应头进行CORS授权
        MyCorsRegistration corsRegistration = new MyCorsRegistration("/**");
        corsRegistration.allowedOrigins(CrossOrigin.DEFAULT_ORIGINS)
                .allowedMethods(HttpMethod.GET.name(), HttpMethod.HEAD.name(), HttpMethod.POST.name(), HttpMethod.PUT.name())
                .allowedHeaders(CrossOrigin.DEFAULT_ALLOWED_HEADERS)
                .exposedHeaders(HttpHeaders.SET_COOKIE)
                .allowCredentials(CrossOrigin.DEFAULT_ALLOW_CREDENTIALS)
                .maxAge(CrossOrigin.DEFAULT_MAX_AGE);

        // 注册CORS过滤器
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**", corsRegistration.getCorsConfiguration());
        CorsFilter corsFilter = new CorsFilter(configurationSource);
        return new FilterRegistrationBean(corsFilter);
    }
}

转载请注明出处!

猜你喜欢

转载自blog.csdn.net/weixin_42614447/article/details/86677945