将Access-Control-Allow-Origin添加到Web服务

时间:2016-02-27 17:04:01

标签: spring spring-mvc cors spring-restcontroller

我有一个像以下的网络服务:

@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'缺失)。

如何添加此标题?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

如果您使用的是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

答案 2 :(得分:0)

我认为您的代码可能需要使用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中提及。

希望这有帮助!