要在Java中创建自定义CORS过滤器,请遵循以下步骤:
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
CORSFilter.java
的新Java类,并实现javax.servlet.Filter
接口: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.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
@WebFilter(asyncSupported = true, urlPatterns = { "/*" })
public class CORSFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
// 设置CORS相关的HTTP头
httpResponse.setHeader("Access-Control-Allow-Origin", "*");
httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
httpResponse.setHeader("Access-Control-Max-Age", "3600");
httpResponse.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
在这个例子中,我们设置了以下CORS相关的HTTP头:
Access-Control-Allow-Origin
: 允许所有来源访问。可以将其更改为特定的域名或使用*
允许所有来源。Access-Control-Allow-Methods
: 允许的HTTP方法列表。Access-Control-Max-Age
: 预检请求(preflight request)的结果被缓存的时间(以秒为单位)。Access-Control-Allow-Headers
: 允许的自定义请求头列表。web.xml
文件中添加以下内容: <filter-name>CORSFilter</filter-name>
<filter-class>com.example.CORSFilter</filter-class>
</filter><filter-mapping>
<filter-name>CORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
现在,您已经成功创建了一个自定义CORS过滤器,它将允许跨域访问您的Java Web应用程序。根据需要调整CORS相关的HTTP头以满足您的需求。