我们在使用SpringBoot集成Swagger2中,访问:http://localhost/swagger-ui.html
问题描述:
No mapping found for HTTP request with URI [/swagger-ui.html] in DispatcherServlet with name ‘dispatcherServlet’
问题截图:
参考文章:
https://www.it610.com/article/1188228427770077184.htm
https://blog.csdn.net/riemann_/article/details/103604937
https://blog.csdn.net/guanfl/article/details/54617045 (Swagger Annotations)
https://blog.csdn.net/qq_27093465/article/details/78972010(mvc)
解决方案
这个错误,是因为静态资源路径映射问题导致。
我们在访问http://localhost/swagger-ui.html时,这个swagger-ui.html相关的所有前端静态文件都在springfox-swagger-ui-2.4.0.jar里面。目录如下:
SpringBoot自动配置本身并不会把/swagger-ui.html这个路径映射到对应的目录META-INF/resources/下面。我们加上这个映射即可。构建一个WebMvcConfig 类,代码如下:
package com.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@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/");
}
}
需要特别说明一下的是,Swagger2.java这个类一定要配置正确。
package com.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class Swagger2 {
/**
* @Description:swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.apis(RequestHandlerSelectors.basePackage("com.demo.controller"))
.paths(PathSelectors.any()).build();
}
/**
* @Description: 构建api文档的信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 设置页面标题
.title("标题")
// 设置联系人
.contact(
new Contact("昵称", "网址链接", "邮箱"))
// 描述
.description("描述信息")
// 定义版本号
.version("版本号").build();
}
}