美文网首页
SpringBoot 1.X、2.X 解决跨域问题

SpringBoot 1.X、2.X 解决跨域问题

作者: Negen | 来源:发表于2019-03-11 15:01 被阅读0次

什么是跨域

Cors的英文全称是Cross-origin Resource Sharing,意思是跨域资源共享。它允许浏览器向非同源服务器发送XMLHttpRequest请求,能够像访问同源本地服务器一般。Cors需要浏览器和服务器同时支持,现在的主流浏览器(Google/IE/FireFox/360)一般都支持跨域的,所以关键在于服务器端实现跨域问题,才能真正实现跨域通信。
通俗的可以理解为:A 服务器的 js(ajax)想要请求获取 B 服务器的资源数据,而A,B不在同一个域,即出现了跨域的问题。

如何解决?

其实解决方法可以从前端来解决可以从后端来解决,但是我遇到过很多次跨域问题,会先考虑前端解决,但是一般都没有效果,最后妥协,只能从后端来解决跨域问题。

我这里总结了三种解决跨域的方法
1、SpringBoot 1.X
给项目新建一个 CorsConfig 类
详细代码如下:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
        corsConfiguration.addAllowedHeader("*"); // 2允许任何头
        corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }
}

2、SpringBoot 2.x
给项目新建一个 CorsConfig 类
详细代码如下:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //设置允许跨域的路径
        registry.addMapping("/**")
                //设置允许跨域请求的域名
                .allowedOrigins("*")
                //是否允许证书 不再默认开启
                .allowCredentials(true)
                //设置允许的方法
                .allowedMethods("*")
                //跨域允许时间
                .maxAge(3600);
    }
}

3、Filter(过滤器)
这个在 springboot 中创建的 filter 不用写 xml 文件,直接跟上注解就行了。

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
@WebFilter(urlPatterns = "/*", filterName = "validate")
public class ValidateFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp = (HttpServletResponse)response;
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        resp.setHeader("Access-Control-Max-Age", "3600");
        //设置可以接受的请求头
        resp.setHeader("Access-Control-Allow-Headers", "validatecode, content-type, cache-control, postman-token");
    }

    @Override
    public void destroy() {

    }
}

相关文章

网友评论

      本文标题:SpringBoot 1.X、2.X 解决跨域问题

      本文链接:https://www.haomeiwen.com/subject/fyhbpqtx.html