spring boot跨域处理

简介:

使用spring boot开发web应用时,有时会需要对跨域访问进行处理。本文包含了服务端跨域和客户端跨域的处理,对于json数据的处理包含了fastjson和jackson两种方式

一. 客户端跨域

对于客户端跨域,原理这里就不做详解,大家熟知的应该是jquery jsonp请求。这种方式会在请求的url上增加一个callback参数(表示请求返回后的回调js函数,参数名可以配置),服务端返回的数据实际是一段js,而js的内容就是执行这个回调js函数,服务端返回的数据就是这个回调js函数的参数,只是jquery内部已有处理,所以使用起来就和普通的ajax json请求没有什么差别,但是服务端返回的数据就需要按约定进行处理。比如一个ajax jsonp的请求中,callback参数的值是a,服务端需要返回数据data,那么服务端返回的结果就应该是a(data)。因此可以在服务端对Controller请求做统一处理,在普通http请求返回结果的基础上,获取callback参数的值拼接成jsonp需要返回的结果

  1. jackson支持jsonp的配置
  • spring boot的json序列化默认使用的是jackson;@ControllerAdvice是spring3.2提供的一个增强控制器的注解,AbstractJsonpResponseBodyAdvice 是spring mvc提供的针对jsonp请求的处理。spring boot只需增加如下配置即可支持jackson对jsonp的支持。并且增加了此配置之后,只有当请求中包含callback参数时才会被当做跨域请求处理,否则跟同源请求处理一样。
@Configuration
@ControllerAdvice  
public class JsonpSupportAdvice extends AbstractJsonpResponseBodyAdvice {  
    public JsonpSupportAdvice() {  
        //参数包含callback的时候 使用jsonp的反馈形式  
        super("callback");  
    }  
}  
  1. fastjson支持jsonp的配置
  • 现在有很多json序列化是使用fastjson的,而fastjson也提供了对于jsonp的支持,配置如下:
@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
    //配置使用fastjson作为转换器,注意是FastJsonpHttpMessageConverter4而不是FastJsonHttpMessageConverter4
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(new FastJsonpHttpMessageConverter4());
    }
}

//配置fastjson的ResponseBodyAdvice
@Bean
public FastJsonpResponseBodyAdvice fastJsonpResponseBodyAdvice() {
    return new FastJsonpResponseBodyAdvice("callback");
}

注意

  • 由于jackson和fastjson是两种不同的序列化,所以两者不能混用,即如果配置fastjson作为消息转换器,就只能使用fastjson的ResponseBodyAdvice

二. 服务端跨域

客户端跨域的请求只能是get方式请求,更多适用于提供一些公开的api,比如网上提供的获取天气、手机号归属地等接口。而很多项目是因为做前后端分离需要使用跨域,这时候就更适合用服务端跨域,客户端就可以像同源请求一样正常使用,spring boot默认使用jackson,本身提供了对于跨域的支持,配置如下:

  1. jackson服务端支持跨域
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(HttpMethod.GET.toString());
    }
    
}
  1. 使用fastjson时,配置服务端支持跨域,除了前面使用默认jackson的配置之外,还需要配置fastjson的SupportedMediaTypes,默认是*,请求会报错
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // FastJsonHttpMessageConverter4默认的mediaType是*/*,restTemplate请求不允许请求头信息中的ContentType为*,所以需要修改mediaType
        FastJsonHttpMessageConverter4 fastJsonHttpMessageConverter4 = new FastJsonHttpMessageConverter4();
        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        // fastJsonHttpMessageConverter4.getSupportedMediaTypes()方法获取的list不允许修改,所以只能使用set方法进行修改
        fastJsonHttpMessageConverter4.setSupportedMediaTypes(supportedMediaTypes);
        converters.add(fastJsonHttpMessageConverter4);
        // converters.add(new FastJsonHttpMessageConverter4());
    }
}
  • 前端请求示例(注意dataType是json,不是jsonp)
$.ajax({
    url: 'http://jsonp.itopener1.com:8081/jsonp/user/2',
    type: 'get',
    dataType: 'json',
    success: function(data){
        console.log(JSON.stringify(data));
    },
    error: function(err){
        console.log(JSON.stringify(err));
    }
});
目录
相关文章
|
28天前
|
Java 应用服务中间件 Maven
SpringBoot 项目瘦身指南
SpringBoot 项目瘦身指南
41 0
|
2月前
|
Java
springboot+cors跨域处理
springboot+cors跨域处理
26 0
|
3月前
|
前端开发 Java 应用服务中间件
解决跨域问题的8种方法,含网关、Nginx和SpringBoot~
解决跨域问题的8种方法,含网关、Nginx和SpringBoot~
180 0
解决跨域问题的8种方法,含网关、Nginx和SpringBoot~
|
3月前
|
Java Spring
springboot跨域配置
springboot跨域配置
33 0
|
16天前
|
Java
Springboot文件下载跨域问题解决方案
Springboot文件下载跨域问题解决方案
|
4月前
|
缓存 前端开发 Java
13:SpringBoot跨域解决方案-Java Spring
13:SpringBoot跨域解决方案-Java Spring
74 0
|
7天前
|
安全 Java 应用服务中间件
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
24 0
江帅帅:Spring Boot 底层级探索系列 03 - 简单配置
|
9天前
|
XML Java C++
【Spring系列】Sping VS Sping Boot区别与联系
【4月更文挑战第2天】Spring系列第一课:Spring Boot 能力介绍及简单实践
【Spring系列】Sping VS Sping Boot区别与联系
|
16天前
|
Java
SpringBoot 配置解决跨域问题
SpringBoot 配置解决跨域问题
|
1月前
|
安全 前端开发 JavaScript
spring boot3解决跨域的几种方式
spring boot3解决跨域的几种方式
60 3