Java Web中实现设置多个域名跨域访问

添加以下设置可允许所有域名跨域访问:

response.setHeader("Access-Control-Allow-Origin","*");

但在实际应用中,为了安全起见,不应该让所有域名都能跨域请求服务器API,需要设置指定的几个域名可以访问,直接通过以下代码是不能实现的

response.setHeader("Access-Control-Allow-Origin","http://localhost:8000, http://oa.ewsd.cn");

可把需要指定能跨域访问的域名通过数组的方式进行设置,代码如下:

// 允许跨域请求
String[] allowDomain = {"http://localhost:8000", "http://oa.ewsd.cn"};
Set<String> allowedOrigins = new HashSet<String>(Arrays.asList(allowDomain));
String originHeader = request.getHeader("Origin");
if (allowedOrigins.contains(originHeader)) {
    response.setHeader("Access-Control-Allow-Origin", originHeader);
    response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Cookie");
    response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
    response.setHeader("Access-Control-Allow-Credentials", "true");
}

参考:http://blog.csdn.net/zlp_zky/article/details/70213811

posted @ 2017-07-19 10:23  佐佑时代  阅读(2579)  评论(0编辑  收藏  举报