springBoot 访问 swagger-ui.html 报错

v2版本
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
​​​​​​​<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>
jar包结构

默认情况下就是访问静态资源
http://localhost:8080/swagger-ui.html

假设要打开js则地址是
http://localhost:8084/webjars/springfox-swagger-ui/springfox.js(包的层级不一样, idea中的截图不明显) 
===============================================================

v3版本

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-core</artifactId>
    <version>1.1.49</version>
</dependency>
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.1.45</version>
</dependency>

查看ui包中源码
SwaggerConfig.java 中配置了静态资源的访问

SwaggerWelcome.java 中配置了url重定向

​​​​​​​

DEFAULT_SWAGGER_UI_PATH的值是

所以 v3版本用地址
http://localhost:8080/swagger-ui.html​
其实是自动重定向到
​​​​​​​​http://localhost:8080/swagger-ui/index.html

项目里面的 接口json数据则是从OpenApiResource.java 中获取的

 

===============================================================

在接手一个老系统时想添加 swagger-ui 发现访问 http://localhost:8080/swagger-ui.html 一直报错

javax.servlet.ServletException: Could not resolve view with name 'redirect:/swagger-ui/index.html?url=/v3/api-docs&validatorUrl=' in servlet with name 'dispatcherServlet'

错误提示的是没有视图
​​​​​​​如果直接访问http://localhost:8080/swagger-ui/index.html 则正常

最终定位到是老系统中有配置了   WebMvcConfigurationSupport  这个配置类会让   springMvc的自动装配类失效 WebMvcAutoConfiguration

所以有3种解决方案:

1.实现WebMvcConfigurer接口, 把原本继承WebMvcConfigurationSupport的代码, 调整下即可

2.用一个新的项目去启动  swagger-ui,  把老系统的 http://项目地址:端口/v3/api-docs 地址填进去

3.如果不想多启动1个项目, 且不需要原系统WebMvcConfigurationSupport中的配置时,  则可以覆盖掉原有的WebMvcConfigurationSupport

/**
 * WebMvcConfigurationSupport 只能存在一个, 当前的会覆盖其他的
 *
 */
@Configuration
public class WebMvcConfigOverride extends WebMvcConfigurationSupport {
​
    @Bean
    public InternalResourceViewResolver viewResolver(){
        return new InternalResourceViewResolver();// 用于解析重定向 redirect:
    }
    
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("/webjars/").resourceChain(false);
    }
}

参考

继承WebMvcConfigurationSupport后自动配置不生效的问题及如何配置拦截器_fmwind的博客-CSDN博客_webmvcconfigurationsupport

记springboot重定向时报错:javax.servlet.ServletException: Could not resolve view with name ‘redirect:https:*_凹凸曼蓝博one的博客-CSDN博客

WebMvcConfigurerAdapter已过时,使用WebMvcConfigurationSupport或者WebMvcConfigurer来代替 - 就这个名字好 - 博客园

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值