- 在web项目中添加一个filter。
- 重写doFilter(ServletRequest request,ServletResponse response,FilterChain chain)方法:
HttpServletResponse res=(HttpServletResponse) response;
res.addHeader("Access-Control-Allow-Origin","http://localhost:端口号");
res.addHeader("Access-Control-Allow-Mtehods","GET/POST/..");
chain.doFilter(request,response);
- 如果想允许所有的地址,更改以下代码:
HttpServletRequest res=(HttpServletRequest)request;
String origin= res.getHeader("Origin");
res.addHeader("Access-Control-Allow-Origin",origin);
- 如果允许所有方法,更改如下代码:
res.addHeader("Access-Control-Allow-Mtehods","*");