• Spring 跨域问题CORS (Cross Origin Resources Share)


    1、Spring给我们提供了三种跨域方法

    1. CorsFilter 过滤器
    2. CorsConfiguration Bean
    3. @CrossOrigin 注解

    2、CorsFilter 过滤器

    CorsFilter代码如下:

    package com.xiaobai.filter;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebFilter(filterName = "MyFilter")
    public class MyFilter implements Filter {
    
        public void destroy() {
        }
        String allowList [] = null;
    
        @Override
        public void init(FilterConfig config) throws ServletException {
            String origins = config.getInitParameter("allowList");
            if(origins != null){
                if(origins.equals("*")){
                    allowList = new String[]{"*"};
                }else {
                    allowList = origins.split(",");
                }
            }
        }
    
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws ServletException, IOException {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            HttpServletRequest request = (HttpServletRequest) servletRequest;
    
            String origin = request.getHeader("Origin");
            if (origin != null && !origin.isEmpty()) {
                for (String s : allowList) {
                    if (s.equals(origin) || s.equals("*")) {
                        response.setHeader("Access-Control-Allow-Origin", origin);
                    }
                }
            }
            chain.doFilter(request, response);
        }
    }

    web.xml代码如下:

        <filter>
            <filter-name>MyFilter</filter-name>
            <filter-class>com.xiaobai.filter.MyFilter</filter-class>
    
            <init-param>
                <param-name>allowList</param-name>
                <param-value>http://127.0.0.1:8081, http://192.168.2.24:8081</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>MyFilter</filter-name>
            <url-pattern>/aa</url-pattern>
        </filter-mapping>
    

    3、CorsConfiguration Bean

    <mvc:cors>:

    <mvc:cors>
      <mvc:mapping path="/xxx"
                   allowed-origins="http://localhost:7070"
                   allowed-methods="GET, POST"
                   allowed-headers="Accept-Charset, Accept, Content-Type"
                   allow-credentials="true" />
      <mvc:mapping path="/yyy/*"
                   allowed-origins="*"
                   allowed-methods="*"
                   allowed-headers="*" />
    </mvc:cors>
    

    4、@CrossOrigin 注解

    @CrossOrigin 注解本质上也是用来配置 CorsConfiguration。

    @CrossOrigin代码如下:

    @CrossOrigin
    public class CORSController {
        public String cors(@RequestParam(defaultValue = "callback") String callback, HttpServletResponse response) {
            // 最原始的方式,手动写请求头
            response.setHeader("Access-Control-Allow-Origin", "http://192.168.163.1:8081");
            return callback + "('hello')";
        }
    
    
        // 将跨域设置在方法上
        @RequestMapping("/cors")
        @CrossOrigin(origins = {"http://localhost:8080", "http://remotehost:82323"},
                     methods = {RequestMethod.GET, RequestMethod.POST},
                     allowedHeaders = {"Content-Type", "skfjksdjfk"},
                     allowCredentials = "true",
                     maxAge = 1898978
                     )
        @RequestMapping("/rrr")
        public String rrr(@RequestParam(defaultValue = "callback") String callback) {
            return callback + "('rrr')";
        }
    }
    

    5、其实也可以采用全注解的方式

    结合 @ControllerAdvice 使用,进行全局化:

    @Component
    @ControllerAdvice
    @CrossOrigin
    public class CorsAdvice {
    }
    

      

  • 相关阅读:
    用反射的方法获取枚举值(数据字典)
    使用哈希加盐法来为密码加密(补充JAVA的实现)
    Mybatis使用TypeHandler实现数据的加解密转换
    学习Hadoop和Spark的好的资源
    Scala基本语法学习笔记
    Scala & IntelliJ IDEA环境搭建升级版:在JAVA中调用Scala的helloworld
    Scala & IntelliJ IDEA:环境搭建、helloworld
    【转】解决yum安装软件报Couldn't resolve host 'mirrorlist.centos.org问题
    使用nfs映射远程服务器磁盘目录
    MacOS系统升级后,IDEA的SVN不好用的问题
  • 原文地址:https://www.cnblogs.com/Qi1007/p/10030245.html
Copyright © 2020-2023  润新知