• SpringBoot设置Access-Control-Allow-Origin跨域


    1、设置filter

    @Component
    @WebFilter(urlPatterns = "/*", filterName = "CorsFilter")
    public class CorsFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            HttpServletRequest reqs = (HttpServletRequest) req;
            String curOrigin = reqs.getHeader("Origin");
            response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
            chain.doFilter(req, res);
        }
    
    
        @Override
        public void init(FilterConfig filterConfig) {
            System.out.println("=======================================================chulaile=================================================");
        }
    
        @Override
        public void destroy() {}
    
    }
    

    2 配置

    @Configuration
    public class CorsConfig  extends WebMvcConfigurerAdapter {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").allowedOrigins("*")
                    .allowedMethods("GET", "HEAD", "POST","PUT", "DELETE", "OPTIONS")
                    .allowCredentials(true).maxAge(3600);
        }
    
    }
    

    3

    @Configuration
    public class XXXXMvcConfigurer implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
                    .allowCredentials(true)
                    .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
                    .maxAge(3600);
        }
    }
    

    4 @CrossOrigin
    原文链接:https://blog.csdn.net/qiuqiu1628480502/java/article/details/85289894

  • 相关阅读:
    【Android】HAL分析
    【qt】QT 的信号与槽机制
    【驱动】DM9000A网卡驱动框架源码分析
    【驱动】LCD驱动(FrameBuffer)分析
    告别我的OI生涯
    诸神的黄昏——北林退役帖合集
    cf592d
    北京林业大学就读体验
    hdu 5442 (ACM-ICPC2015长春网络赛F题)
    JAVA入门[4]-IntelliJ IDEA配置Tomcat
  • 原文地址:https://www.cnblogs.com/leifonlyone/p/12844686.html
Copyright © 2020-2023  润新知