【问题标题】:Add Access-Control-Allow-Origin to Web Service将 Access-Control-Allow-Origin 添加到 Web 服务
【发布时间】:2016-06-10 21:44:31
【问题描述】:

我有一个类似的网络服务:

@Controller
@RequestMapping("/")
public class ApplicationController {

    @RequestMapping(value="/Changes", method = RequestMethod.GET)
    public String inspect(ModelMap model) {
         model.addAttribute("msg", "example");

         return "index";
    }
}

在链接中:"localhost:8081/ChangesPDF/Changes?..."

我正在尝试通过链接中的 Alfresco 获取此 Web 服务的响应:"localhost:8080/share"。我现在有不同的端口(当我有相同的端口时,这很好用),所以,使用不同的端口我在 Alfresco 中得到错误:

跨域请求被阻止:同源策略不允许读取 http://localhost:8081/ChangesPDF/Changes?... 的远程资源(原因:缺少标头 CORS 'Access-Control-Allow-Origin')。

如何添加此标头?

【问题讨论】:

    标签: spring spring-mvc cors spring-restcontroller


    【解决方案1】:

    您应该添加一个过滤器,将“Access-Control-Allow-Origin”设置为接受域“localhost:8081”(* 表示所有)。

    你很可能会在这里找到答案cores-filter-not-working

    更多解释:

    先创建一个过滤器类

    public class CorsFilter implements Filter {
    
        private static final Logger log = Logger.getAnonymousLogger();
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {}
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            HttpServletRequest request = (HttpServletRequest) servletRequest;
    
            // can be moved to properties
            String[] allowDomain = {"localhost:8080","localhost:8081"};              
    
    
            String originHeader = request.getHeader("host");
    
            for(String domian : allowDomain){
    
                if(originHeader.endsWith(domian))
    
                response.setHeader("Access-Control-Allow-Origin", originHeader);
                break;
            }
            filterChain.doFilter(servletRequest, servletResponse);
    
        }
    
        @Override
        public void destroy() {}
    }
    

    将映射添加到您的 web.xml 类

    <filter>
        <filter-name>cors</filter-name>
        <filter-class>full name of your filter class here</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>cors</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    

    您应该根据您的要求在 web.xml 配置中正确定义 URL pattren

    【讨论】:

    • 但是在我的情况下,我该怎么做呢?我不返回HttpServletResponse response 所以,如果我让response.setHeader 无效。
    • 编辑了我的答案以包括如何设置过滤器
    • url-pattern 是哪个 url?
    • 尝试新的过滤代码,我已将两个域都添加到允许列表中
    • 我正在尝试修改 web.xml,但我在 maven 中得到:[INFO] WEB-INF/web.xml already added, skipping。你知道为什么吗?
    【解决方案2】:

    如果你使用的是 Spring 4.2+,你可以使用@CrossOrigin 注解:

    @Controller
    @RequestMapping("/")
    public class ApplicationController {
    
        @CrossOrigin
        @RequestMapping(value="/Changes", method = RequestMethod.GET)
        public String inspect(ModelMap model) {
             model.addAttribute("msg", "example");
    
             return "index";
        }
    }
    

    否则,您需要在 Spring 应用程序中注册 CORS 过滤器。类似this

    【讨论】:

      【解决方案3】:

      我认为您的代码可能需要使用 Spring 的 @CrossOrigin 注释,例如

      import org.springframework.web.bind.annotation.CrossOrigin;
      
      ....
      
      @Controller
      @RequestMapping("/")
      public class ApplicationController {
      
          @CrossOrigin
          @RequestMapping(value="/Changes", method = RequestMethod.GET)
          public String inspect(ModelMap model) {
              model.addAttribute("msg", "example");
      
              return "index";
          }
      }
      

      这将允许所有来源,这可能足以满足您的需求,也可能不够。

      作为参考,我在this article中找到了上述内容,并在Spring blog here中提到。

      希望这会有所帮助!

      【讨论】:

      • 如果在整个控制器类而不是单个方法上使用@CrossOrigin 注解会发生什么?
      猜你喜欢
      • 1970-01-01
      • 2013-04-08
      • 2018-06-24
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 2020-01-01
      • 2011-07-21
      相关资源
      最近更新 更多