spring boot跨域处理

来源:互联网 发布:鲍伊猎刀淘宝有卖嘛 编辑:程序博客网 时间:2024/05/21 18:58

使用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的支持,配置如下:
@Configurationpublic class WebMvcConfigurer extends WebMvcConfigurerAdapter {    //配置使用fastjson作为转换器,注意是FastJsonpHttpMessageConverter4而不是FastJsonHttpMessageConverter4    @Override    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {        converters.add(new FastJsonpHttpMessageConverter4());    }}//配置fastjson的ResponseBodyAdvice@Beanpublic FastJsonpResponseBodyAdvice fastJsonpResponseBodyAdvice() {    return new FastJsonpResponseBodyAdvice("callback");}

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


二. 服务端跨域

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

  1. jackson服务端支持跨域
@Configurationpublic class WebMvcConfiguration extends WebMvcConfigurerAdapter {    @Override    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(HttpMethod.GET.toString());    }}
  1. 使用fastjson时,配置服务端支持跨域,除了前面使用默认jackson的配置之外,还需要配置fastjson的SupportedMediaTypes,默认是*,请求会报错
@Configurationpublic 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));    }});
原创粉丝点击