Springfox 3.0.0如何实现swagger-ui.html重定向至/swagger-ui/
解决方案
SpringFox 3.0.0版本默认将Swagger UI访问路径调整为/swagger-ui/,你可以通过以下几种方案实现旧路径/swagger-ui.html到新路径的自动重定向:
方案1:配置Spring MVC视图控制器(推荐,无额外业务代码)
无需编写业务接口,直接添加Spring MVC配置类即可实现重定向规则:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class SwaggerRedirectConfig implements WebMvcConfigurer { @Override public void addViewControllers(ViewControllerRegistry registry) { // 配置/swagger-ui.html直接重定向到/swagger-ui/ registry.addRedirectViewController("/swagger-ui.html", "/swagger-ui/"); // 如果项目配置了server.servlet.context-path,可修改目标路径为"/{你的上下文路径}/swagger-ui/"避免路径错误 } }
添加配置类后重启项目即可生效。
方案2:自定义重定向Controller(灵活支持扩展逻辑)
如果后续需要添加额外跳转逻辑(比如携带请求参数跳转、权限校验后跳转),可以直接编写专用的重定向接口:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.view.RedirectView; @RestController public class SwaggerRedirectController { @GetMapping("/swagger-ui.html") public RedirectView redirectSwagger() { return new RedirectView("/swagger-ui/"); } }
注意事项
- 如果项目配置了全局拦截器、鉴权过滤器,需要将
/swagger-ui.html和/swagger-ui/**都加入访问白名单,避免重定向流程被拦截。 - 如果你使用的是Spring WebFlux而非Servlet环境,可以通过实现
WebFluxConfigurer接口、重写addViewControllers方法实现相同的重定向效果。
内容的提问来源于stack exchange,提问作者Bob Kuhar
相关产品推荐
相关产品推荐

