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的配置
@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));
    }
});

转载于:https://my.oschina.net/dengfuwei/blog/1585094

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值