zoukankan      html  css  js  c++  java
  • Spring MVC 后端接口支持跨域CORS调用

    Spring MVC 从4.2版本开始增加了对CORS的支持,可以全局配置,也可以对类或方法配置;可以通过Java代码,也可以通过xml配置方式。
    对于低版本的Spring MVC 可以通过Filter 往response写http header来实现
    还有一种更省事的办法是在Nginx上加入支持。

    Java配置

    新建一个类,做跨域的配置

    @Configuration
    @EnableWebMvc
    public class CorsConfigureAdapter extends WebMvcConfigurerAdapter {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            super.addCorsMappings(registry);
            registry.addMapping("/**");
        }
    }
    

    在Controller上或方法上使用@CrossOrigin注解

    @CrossOrigin(maxAge = 3600)
    @RestController
    @RequestMapping("/account")
    public class AccountController {
    
        @CrossOrigin("http://domain2.com")
        @RequestMapping("/{id}")
        public Account retrieve(@PathVariable Long id) {
            // ...
        }
    
        @RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
        public void remove(@PathVariable Long id) {
            // ...
        }
    }
    

    基于XML的配置

    <mvc:cors>
        <mvc:mapping path="/**" />
    </mvc:cors>
    

    这个配置和上面JAVA方式的第一种作用一样。
    同样,你可以做更复杂的配置:

    <mvc:cors>
        <mvc:mapping path="/api/**" allowed-origins="http://domain1.com, http://domain2.com" allowed-methods="GET, PUT" allowed-headers="header1, header2, header3" exposed-headers="header1, header2" allow-credentials="false" max-age="123" />
        <mvc:mapping path="/resources/**" allowed-origins="http://domain1.com" />
    </mvc:cors>
    

    SpringMVC 3 支持跨域

    SpringMVC 3不支持以上方法,通过Filter的方式实现。

    @Component
    public class SimpleCORSFilter implements Filter {
    
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            chain.doFilter(req, res);
        }
    
        public void init(FilterConfig filterConfig) {}
        public void destroy() {}
    }
    

    web.xml里配置

    <filter>
        <filter-name>cors</filter-name>
        <filter-class>test.cors.SimpleCORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    

    Nginx支持跨域请求

    需要在配置里添加add_header Access-Control*指令,如:

    location /{
    add_header 'Access-Control-Allow-Origin' 'http://other.subdomain.com';
    add_header 'Access-Control-Allow-Credentials' 'true';
    add_header 'Access-Control-Allow-Methods' 'GET'; 
    ...
    the rest of your configuration here
    ...
    }



    作者:happeace
    链接:https://www.jianshu.com/p/453afeef49c1
     

  • 相关阅读:
    you must restart adb and eclipse的相关解决办法
    配有Tesla K40c的服务器新装Ubuntu16.04并安装CUDA8.0、Anaconda3、Matlab2016a、OPENCV3.1、CuDNN5.1、MXNet
    MXNet在64位Win7下的编译安装
    [Kinect]XBox One Kinect连接Windows
    64位Win7下编译Python3的计算机视觉库:OpenCV
    64位Win7下安装并配置Python3的深度学习库:Theano
    Noah的学习笔记之Python篇:命令行解析
    Noah的学习笔记之Python篇:函数“可变长参数”
    Noah的学习笔记之Python篇:装饰器
    linux下安装MySQL5.6记录
  • 原文地址:https://www.cnblogs.com/xiang--liu/p/9710216.html
Copyright © 2011-2022 走看看