提问者:小点点

向Web服务添加Access-Control-Allow-Origin


我有一个网络服务,比如:

@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的“访问控制允许原点”标题)。

如何添加此标题?


共3个答案

匿名用户

您应该添加一个过滤器,将“访问控制允许源”设置为接受域“localhost:8081”(*for all)。

最有可能的是,你会在这里找到你的答案 核心过滤器不起作用

更多说明:

首先创建一个过滤器类

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模式

匿名用户

如果您使用的是 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过滤器。类似于这样。

匿名用户

我认为你的代码可能需要使用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";
    }
}

这将允许所有的起源,这可能对你的需求来说是足够的,也可能是不够的。

作为参考,我在这篇文章中找到了上述内容,并在Spring博客中提到了这一点。

希望这有帮助!