import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class CorsFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
boolean isOpenAllowDomain = false;//是否开启域名列表,默认不开启,自己改成true就开启了
if (isOpenAllowDomain) {
String[] allowDomain = { "http://192.168.0.77:8888",
"http://localhost:8080", "http://127.0.0.1:8080", "http://localhost" };
Set<String> allowedOrigins = new HashSet<String>(Arrays.asList(allowDomain));
String originHeader = request.getHeader("Origin");
System.out.println("-------------------"+originHeader);
if (!originHeader.startsWith("http") || allowedOrigins.contains(originHeader)) {
addAllowedOriginHeader(request, response);
}
}else{
addAllowedOriginHeader(request, response);
}
filterChain.doFilter(request, response);
}
public void addAllowedOriginHeader(HttpServletRequest request, HttpServletResponse response) {
response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type, Accept");
response.setHeader("Access-Control-Allow-Credentials", "true");
}
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE,OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "X-Requested-With,Origin,Content-Type, Accept");
response.setHeader("Access-Control-Allow-Credentials", "true");
}
}
javaEE跨域过滤器
最新推荐文章于 2023-03-29 15:30:08 发布