專案最近新增了一個ip黑白名單的功能, 發現如果ip過濾的攔截器返回false 後前端會顯示跨域, 嘗試修改MVC配置類別後發現還是不行, 最後在攔截器加了個判斷就可以了
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { // ----------- 加上这个就好了 ----------- if (!(handler instanceof HandlerMethod)) { return true; } }
WebMvcConfigurer 設定類別
@Configuration @RestControllerAdvice public class WebMvcConfig implements WebMvcConfigurer { @Resource private IpFilterInterceptor ipFilterInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { // IP拦截器 registry.addInterceptor(ipFilterInterceptor) .addPathPatterns("/**") .order(5); } @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowCredentials(true) .allowedOriginPatterns("*") .allowedMethods("*") .allowedHeaders("*") .maxAge(3600); } }
修改前的IP攔截器
@Component public class IpFilterInterceptor implements HandlerInterceptor { /** * 是否启用 */ private boolean enable; /** * 是否为白名单 */ private boolean isWhiteList; /** * 过滤器 */ private List<String> filters; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { // 停用 if (!enable) { return true; } String ip = Servlets.getRemoteAddr(request); // 本机不过滤 if (Const.LOCALHOST_IP_V4.equals(ip)) { return true; } // 过滤 boolean contains = false; for (String filter : filters) { if (Strings.isBlank(filter)) { continue; } // 检测 contains = Utils.checkIpIn(ip, filter); if (contains) { break; } } // 结果 boolean pass; if (isWhiteList) { pass = contains; } else { pass = !contains; } // 返回 if (!pass) { response.setContentType(StandardContentType.APPLICATION_JSON); Servlets.transfer(response, HttpWrapper.of(ResultCode.IP_BAN).toJsonString().getBytes()); } return pass; } }
修改後的IP攔截器
@Component public class IpFilterInterceptor implements HandlerInterceptor { /** * 是否启用 */ private boolean enable; /** * 是否为白名单 */ private boolean isWhiteList; /** * 过滤器 */ private List<String> filters; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { // 停用 if (!enable) { return true; } // ----------- 加上这个就好了 ----------- if (!(handler instanceof HandlerMethod)) { return true; } String ip = Servlets.getRemoteAddr(request); // 本机不过滤 if (Const.LOCALHOST_IP_V4.equals(ip)) { return true; } // 过滤 boolean contains = false; for (String filter : filters) { if (Strings.isBlank(filter)) { continue; } // 检测 contains = Utils.checkIpIn(ip, filter); if (contains) { break; } } // 结果 boolean pass; if (isWhiteList) { pass = contains; } else { pass = !contains; } // 返回 if (!pass) { response.setContentType(StandardContentType.APPLICATION_JSON); Servlets.transfer(response, HttpWrapper.of(ResultCode.IP_BAN).toJsonString().getBytes()); } return pass; } }
最後, 問題的原因是出在了攔截器身上需要在preHandle 中判斷handler 的類型必須是HandlerMethod 的話才能通過
以上是SpringBoot攔截器回傳false顯示跨域問題怎麼解決的詳細內容。更多資訊請關注PHP中文網其他相關文章!