我正在尝试使用过滤器来允许跨服务器访问我的服务器方法,所以我正在做的是在过滤器中添加标头。我在某处读到了我应该使用HttpServletResponseWrapper所以我可以在它们被发送到客户端之前添加标题,但是我无法使其工作。这就是我尝试过的:
的web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" >
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>com.novatronic.web.filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/api/*</url-pattern>
</filter-mapping>
</web-app>
这是网址:http://localhost:8080/hbo-web/api/public/login
这是我的doFilter方法:
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
HttpServletResponse response = (HttpServletResponse) servletResponse;
HboResponseWrapper responseWrapper = new HboResponseWrapper(response);
responseWrapper.addHeader("Access-Control-Allow-Origin", "http://localhost:43040");
responseWrapper.addHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE");
responseWrapper.addHeader("Access-Control-Max-Age", "3600");
responseWrapper.addHeader("Access-Control-Allow-Credentials", "true");
responseWrapper.setHeader("Access-Control-Allow-Headers", "Content-Type, Accept, Accept-Encoding, Cache-Control, Host, Pragma, Referer, User-Agent");
filterChain.doFilter(servletRequest, responseWrapper);
}
我的包装:
package com.novatronic.web.util;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
public class HboResponseWrapper extends HttpServletResponseWrapper {
public HboResponseWrapper(HttpServletResponse httpServletResponse)
{
super(httpServletResponse);
}
}
然而我收到了CORS错误:
XMLHttpRequest cannot load http://localhost:8080/hbo-web/api/public/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:43040' is therefore not allowed access.
可能是什么问题?