package filter;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 跨域过滤器
*/
@WebFilter("/*")
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
//设置允许跨域请求应答头
var response = (HttpServletResponse) resp;
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(request,response);
}
}
设置响应头
response.setHeader("Access-Control-Allow-Origin","*");
允许所有域名的请求访问资源
response.setHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
允许使用的HTTP方法,包括GET,POST,PUT,DELETE,OPTIONS
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
允许请求头中包含x-requested-with特定的自定义请求头。