Spring MVC(非Spring Boot)集成Swagger 2后Swagger UI空白页问题
嘿,我来帮你搞定这个Swagger UI空白的问题!既然所有静态资源都返回200了,那大概率是Swagger前端没有正确关联到你的API文档地址,或者是Spring MVC的配置细节有遗漏。结合非Spring Boot环境的特点,给你几个精准的排查方向:
1. 强制指定Swagger UI的API文档路径
Swagger UI默认会请求/v2/api-docs,但你的API文档地址是/myApp/v2/api-odcs(怀疑你可能打错了,应该是api-docs?),所以得手动让UI指向正确的接口。
在你的Swagger配置类里,补充资源映射+自定义控制器传递参数:
@Configuration @EnableSwagger2 public class SwaggerConfig implements WebMvcConfigurer { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.your.controller.package")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("MyApp API") .description("API Documentation") .version("1.0") .build(); } // 配置Swagger静态资源映射 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } // 关键:让Swagger UI加载你的自定义API文档地址 @Controller public static class SwaggerUiForwardController { @GetMapping("/swagger-ui.html") public ModelAndView redirectToSwaggerUi() { ModelAndView mav = new ModelAndView("redirect:/swagger-ui/index.html"); // 这里填你实际的API文档地址,比如你说的/myApp/v2/api-odcs mav.addObject("url", "/myApp/v2/api-odcs"); return mav; } } }
2. 检查浏览器控制台的JS错误
打开F12开发者工具切到Console标签,看看有没有报错:
- 比如提示找不到API文档数据,那大概率是上面的路径没配对
- 如果有
Cannot read xxx的报错,可能是Swagger依赖版本不兼容,或者API文档返回格式有问题(先手动访问/myApp/v2/api-odcs确认返回的是合法JSON)
3. 排除拦截器/过滤器对Swagger资源的拦截
如果你的应用有自定义拦截器或过滤器,一定要让它们放过Swagger相关路径:
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new YourCustomInterceptor()) .excludePathPatterns( "/swagger-ui.html", "/webjars/**", "/myApp/v2/api-odcs" // 你的API文档路径 ); }
4. 确认Swagger依赖版本兼容
非Spring Boot环境下,springfox-swagger2和springfox-swagger-ui版本必须一致,还要和你的Spring MVC版本匹配:
- Spring 4.x 配 springfox 2.9.2 稳得一批
- Spring 5.x 可以试试 springfox 3.0.0(不过3.x有些配置细节不一样,建议先从2.9.2入手)
Maven依赖示例:
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
5. 确保Spring能扫描到Swagger配置类
在你的主Spring配置类里,要把SwaggerConfig所在的包加入扫描范围:
@Configuration @ComponentScan(basePackages = {"com.your.app.root", "com.your.swagger.config.package"}) public class AppRootConfig { // 其他配置 }
先从控制台报错和API路径配置入手,这两个是最常见的原因!
内容的提问来源于stack exchange,提问作者Aminos
相关产品推荐
相关产品推荐

