Spring Boot 2.7.x中@GetMapping("/**")拦截Swagger页面的解决咨询
解决Swagger页面被全局GET端点拦截的方案
方法1:在全局GET端点中直接排除Swagger路径
在你的全局GET处理方法里,先判断请求路径是否属于Swagger相关路径,若是则抛出NoHandlerFoundException,让Spring自动转发到Swagger的处理器:
@GetMapping("/**") public String handleAllGet(HttpServletRequest request) { String requestUri = request.getRequestURI(); // 排除Swagger UI和API文档的核心路径 if (requestUri.startsWith("/swagger-ui/") || requestUri.startsWith("/v3/api-docs/")) { throw new NoHandlerFoundException(request.getMethod(), requestUri, new ServletServerHttpRequest(request).getHeaders()); } // 你的业务逻辑实现 return "your-response"; }
方法2:使用RouterFunction定义路由并排除Swagger路径
如果要基于RouterFunction实现,可自定义路由规则,优先处理非Swagger的GET请求,Swagger路径则返回404,让Spring去匹配springdoc自带的路由:
@Configuration @Order(Ordered.LOWEST_PRECEDENCE) // 设置最低优先级,确保Swagger路由先被匹配 public class CustomRouterConfig { @Bean public RouterFunction<ServerResponse> globalGetRouter() { return RouterFunctions.route() .GET("/**", request -> { String path = request.path(); if (!path.startsWith("/swagger-ui/") && !path.startsWith("/v3/api-docs/")) { return ServerResponse.ok().body("Global GET Response"); } // 放行Swagger路径,交给springdoc处理 return ServerResponse.notFound().build(); }) .build(); } }
方法3:配置WebMvc路径匹配器排除Swagger路径
通过实现WebMvcConfigurer,自定义路径匹配器并排除Swagger相关路径,让全局端点不匹配这些路径:
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void configurePathMatch(PathMatchConfigurer configurer) { AntPathMatcher pathMatcher = new AntPathMatcher(); // 添加Swagger路径到排除列表 pathMatcher.setExcludedPatterns(List.of("/swagger-ui/**", "/v3/api-docs/**")); configurer.setPathMatcher(pathMatcher); } }
注意事项
- Spring Boot 2.7.x搭配springdoc-openapi-ui:1.6.13时,Swagger的核心路径为
/swagger-ui/**(UI页面)和/v3/api-docs/**(API文档接口),确保排除这两个路径即可。 - 优先推荐方法1,实现简单且无需额外配置类,对现有代码侵入最小。
内容的提问来源于stack exchange,提问作者JPG
相关产品推荐
相关产品推荐

