SpringBoot跨域问题解决的两种后端方法

何为跨域:只要协议、域名、端口有任何一个不同,都被当作是不同的域。

跨域问题导致403: 表示资源不可用。服务器理解客户的请求,但拒绝处理它,通常由于服务器上文件或目录的权限设置导致的WEB访问错误。

跨域资源共享(CORS)

CORS(Cross-Origin Resource Sharing)跨域资源共享,定义了必须在访问跨域资源时,浏览器与服务器应该如何沟通。CORS背后的基本思想就是使用自定义的HTTP头部让浏览器与服务器进行沟通,从而决定请求或响应是应该成功还是失败。

服务器端对于CORS的支持,主要就是通过设置Access-Control-Allow-Origin来进行的。如果浏览器检测到相应的设置,就可以允许Ajax进行跨域的访问。
 

介绍SpringBoot的两种解决方法

方法一:拦截器Interceptor添加响应头Access-Control-Allow-Origin

1.1 创建MyInterceptor拦截器实现HandlerInterceptor接口,在preHandle()方法中设置响应头,记住该方法返回值必须为true

package com.mlj.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {

    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        // TODO Auto-generated method stub
    }

    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        // TODO Auto-generated method stub
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {

        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
        System.err.println("------------------>:已完成跨域处理");
        return true;
    }
}

1.2 在WebMvcConfigurer的实现类中注册MyInterceptor拦截器

talk is shit, show you the code

package com.mlj.config;

import com.mlj.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

    //解决跨域方式一
    //在WebMvcConfigurer配置类中注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }

    //解决跨域方式二
//    @Override
//    public void addCorsMappings(CorsRegistry registry) {
//        //所有请求都允许跨域,使用这种配置方法就不能在 interceptor 中再配置 header 了
//        registry.addMapping("/**")
//                .allowCredentials(true)
//                .allowedOrigins("*")
//                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
//                .allowedHeaders("*")
//                .maxAge(3600);
//    }
}

2.直接在WebMvcConfigurer配置类中重写 addCorsMappings(CorsRegistry registry)  也是解决跨域问题

//必须加上@Configuration,才能被springboot扫描自动配置
@Configuration
public class MvcConfig implements WebMvcConfigurer {

    //解决跨域方式二
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //所有请求都允许跨域,使用这种配置方法就不能在 interceptor 中再配置 header 了
        registry.addMapping("/**")
                .allowCredentials(true)
                .allowedOrigins("*")
                .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                .allowedHeaders("*")
                .maxAge(3600);
    }
}

猜你喜欢

转载自blog.csdn.net/mmmmmlj/article/details/109240199