配置过程分为三个步骤
1、项目下web.xml中配置
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2、CorsFilter配置过滤器
package com.ea.p2p.comm.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CORSFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse resp = (HttpServletResponse) servletResponse;
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Access-Control-Allow-Methods", "GET,POST");
resp.addHeader("Access-Control-Allow-Headers", "platform,Origin, X-Requested-With, Content-Type, Accept");
// Just ACCEPT and REPLY OK if OPTIONS
if (request.getMethod().equals("OPTIONS")) {
resp.setStatus(HttpServletResponse.SC_OK);
return;
}
chain.doFilter(request, servletResponse);
}
@Override
public void destroy() {
}
}
3、JS请求部分
function createCORSRequest(method, url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr){
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined"){
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var request= createCORSRequest("get", "your url");
if (request){
request.setRequestHeader('platform',platform);
request.send();
}
标红处为需要注意的header中的参数