tomcat 7.0.59上的我的CORS过滤器如下所示:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>accept, content-type, origin, if-match, if-non-match</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET, HEAD, OPTIONS, POST, DELETE, PUT</param-value>
</init-param>
<init-param>
<param-name>cors.exposed.headers</param-name>
<param-value>ETag, Link</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>http://153.57.146.93,http://localhost:7777,http://localhost:9090</param-value>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
我正在尝试从Chrome中的localhost:9090访问服务器,我得到: No&#39; Access-Control-Allow-Origin&#39;标头出现在请求的资源上。我的CORS过滤器是否设置正确?
答案 0 :(得分:0)
这对我有用。创建一个过滤器类:
public class CORSFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
chain.doFilter(req, res);
}
@Override
public void destroy() {
}
}
然后将您的课程添加到过滤器列表
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>
net.viralpatel.servlet.filters.CORSFilter
</filter-class>
<init-param>
<param-name>test-param</param-name>
<param-value>This parameter is for testing.</param-value>
</init-param>
</filter>
有关该主题的更多文档http://viralpatel.net/blogs/tutorial-java-servlet-filter-example-using-eclipse-apache-tomcat/
希望有所帮助