在项目实现过程中需要解决跨域的问题,于是参考到文章http://m.blog.csdn.net/article/details?id=53648145中说明:
如果服务端是Java开发的,添加如下设置允许跨域即可。
response.setHeader("Access-Control-Allow-Origin","*");
添加位置可以在下面三处任选一个。
1:可以在过滤器的filter中的dofilter()方法设置。
2:可以在servet的get或者post方法里面设置。
3:可以放在访问的jsp页面第一行。
于是根据所做的项目考虑采用第一种方法:
为了实现多个ip的跨域访问查阅资料写得如下代码,经测试可用。
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) res;
String [] allowDomain= {"http://132.12.11.11:8888","http://123.112.112.12:80","http://123.16.12.23","http://121.12.18.13:10195"};
Set
allowedOrigins= new HashSet
(Arrays.asList(allowDomain));
String originHeader=((HttpServletRequest) req).getHeader("Origin");
if (allowedOrigins.contains(originHeader)){
((HttpServletResponse) res).setHeader("Access-Control-Allow-Origin", originHeader);
((HttpServletResponse) res).setContentType("application/json;charset=UTF-8");
((HttpServletResponse) res).setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
((HttpServletResponse) res).setHeader("Access-Control-Max-Age", "3600");
((HttpServletResponse) res).setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");//表明服务器支持的所有头信息字段
((HttpServletResponse) res).setHeader("Access-Control-Allow-Credentials", "true"); //如果要把Cookie发到服务器,需要指定Access-Control-Allow-Credentials字段为true;
((HttpServletResponse) res).setHeader("XDomainRequestAllowed","1");
}
chain.doFilter(req, res);
return;
}