tomcat项目跨域问题解决方法整理
<!-- 跨域 -->
<filter>
<filter-name>CORSFilter</filter-name>
<filter-class>com.cors.CORSFilter</filter-class>
<init-param>
<param-name>allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
跨域过滤自定义类
package com.test.trundle.cors;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import com.test.trundle.common.StringUtils;
/**
* Servlet Filter implementation class CORSFilter
*/
public class CORSFilter implements Filter {
private static String allowOrigin = "";
private static String allowMethods = "POST,GET,PUT,OPTIONS,DELETE";
private static String maxAge = "3600";
private static String allowHeaders = "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers";
private static String allowCredentials = "true";
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse _response = (HttpServletResponse) response;
_response.setHeader("Access-Control-Allow-Origin", allowOrigin);
_response.setHeader("Access-Control-Allow-Methods", allowMethods);
_response.setHeader("Access-Control-Max-Age", maxAge);
_response.setHeader("Access-Control-Allow-Headers", allowHeaders);
_response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
chain.doFilter(request, _response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
String _allowOrigin = fConfig.getInitParameter("allowOrigin");
if(!StringUtils.isNullOrEmpty(_allowOrigin)){
allowOrigin = _allowOrigin;
}
String _allowMethods = fConfig.getInitParameter("allowMethods");
if(!StringUtils.isNullOrEmpty(_allowMethods)){
allowMethods = _allowMethods;
}
String _maxAge = fConfig.getInitParameter("maxAge");
if(!StringUtils.isNullOrEmpty(_maxAge)){
maxAge = _maxAge;
}
String _allowHeaders = fConfig.getInitParameter("allowHeaders");
if(!StringUtils.isNullOrEmpty(_allowHeaders)){
allowHeaders = _allowHeaders;
}
String _allowCredentials = fConfig.getInitParameter("allowCredentials");
if(!StringUtils.isNullOrEmpty(_allowCredentials)){
allowCredentials = _allowCredentials;
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}