【Spring】后端解决跨域问题

什么是跨域?
跨域,指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器对JavaScript施加的安全限制。

举个栗子:
http://www.123.com/index.html 的同源检测结果
URL-结果-原因
http://www.123.com/server.PHP 成功
http://www.456.com/server.php 失败 主域名不同
http://def.123.com/server.php 失败 子域名不同
http://www.123.com:8081/server.php 失败 端口不同
https://www.123.com/server.php 失败 协议不同

解决办法

JSONP 配合前端
JSONP的最基本的原理是:动态添加一个script标签,而script标签的src属性是没有跨域的限制的。

后端配合可以新建一个类:

package com.company.api.controller;

import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.AbstractJsonpResponseBodyAdvice;

import java.nio.charset.Charset;

@ControllerAdvice(basePackages = "com.company.api.controller")
public class JsonpAdvice extends AbstractJsonpResponseBodyAdvice {

    @Override
    protected MediaType getContentType(MediaType contentType, ServerHttpRequest request, ServerHttpResponse response) {
        return new MediaType("application", "javascript", Charset.forName("utf-8"));
    }

    public JsonpAdvice() {
        super("callback");
    }

}

添加这个类后,baseController中配置路径中的controller都支持跨域请求,缺点是仅支持Get请求。

Spring 注解

Controller增加@CrossOrigin,被注解的Controller具备接受跨域请求的功能。默认情况下,它使方法具备接受所有域,所有请求消息头的请求。当然也可以自己配置接受的域、请求头、方法和是否允许cookie,下面的例子中,我们仅接受百度发送来的跨域请求。

@RestController
@CrossOrigin(origins = "http://www.baidu.com,https://www.baidu.com")
public class CrossController {
    ...
}

Spring WebMvcConfigurerAdapter

用WebMvcConfigurerAdapter增加配置,同样可以自定义接受的域、请求头、方法、是否允许cookie,
下面的栗子中,我们接受一切。

package com.haonanren.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 * Created by zjief on 17-3-27.
 */
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*");
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值