• SpringBoot系列【统一解决跨域】


    注意: CorFilter / WebMvConfigurer / @CrossOrigin 需要 SpringMVC 4.2以上版本才支持,对应springBoot 1.3版本以上。

    1.重写WebMvcConfigurer(全局跨域)

    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.HttpHeaders;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    /**
     * 全局配置,解决跨域
     */
    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**").
                    //允许跨域的域名,可以用*表示允许任何域名使用
                    allowedOrigins("*").
                    //允许任何方法(post、get等)
                    allowedMethods("*").
                    //允许任何请求头
                    allowedHeaders("*").
                    //带上cookie信息
                    allowCredentials(true).
                    //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
                    exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L);
        }
    }

    2.通过实现Fiter接口在请求中添加一些Header来解决跨域的问题

    @Component
    public class CorsFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
            HttpServletResponse res = (HttpServletResponse) response;
            res.addHeader("Access-Control-Allow-Credentials", "true");
            res.addHeader("Access-Control-Allow-Origin", "*");
            res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
            res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN");
            if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
                response.getWriter().println("ok");
                return;
            }
            chain.doFilter(request, response);
        }
        @Override
        public void destroy() {
        }
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    }

    3.使用注解 @CrossOrigin,加在contrlller类上

  • 相关阅读:
    Kendo UI for jQuery电子表格控件可轻松实现Excel导出
    缩短
    google 插件 消息通知
    C#初学者的Hello World代码_艾孜尔江撰
    HTML简易的用户名密码登录页面_艾孜尔江撰
    一次性打开多个网页的工具脚本_艾孜尔江撰
    使用a标签无法跳转到指定网页的解决办法
    Flutter安装+Vscode+夜神模拟器+android SDK
    gitbook 说明
    两个模块之间项目依赖问题
  • 原文地址:https://www.cnblogs.com/hujunwei/p/15854006.html
Copyright © 2020-2023  润新知