Java 无法使springfox招摇过市的ui与SpringMVC一起工作

Java 无法使springfox招摇过市的ui与SpringMVC一起工作,java,maven,spring-mvc,swagger,swagger-ui,Java,Maven,Spring Mvc,Swagger,Swagger Ui,我花了几天时间寻找解决方案,但一直找不到,大多数例子都是关于SpringBoot和gradle的,我只使用SpringMVC和maven 如果我删除springfox swagger ui依赖项,应用程序将正常运行,并按预期返回JSON http:\\localhost:8080\restful\v2\api docs?group=restful api 由于某种原因,我的spring应用程序无法通过swagger-ui.html,如果我设置index.html,它会给出相同的响应 我尝试补充:

我花了几天时间寻找解决方案,但一直找不到,大多数例子都是关于SpringBoot和gradle的,我只使用SpringMVC和maven

如果我删除springfox swagger ui依赖项,应用程序将正常运行,并按预期返回JSON http:\\localhost:8080\restful\v2\api docs?group=restful api

由于某种原因,我的spring应用程序无法通过swagger-ui.html,如果我设置index.html,它会给出相同的响应

我尝试补充:

  • web.xml中的欢迎列表文件
  • 资源处理程序
  • 默认Servlet处理
  • 没有一个奏效

    应用程序配置 招摇过市配置 我的守则如下:

    web.xml
    我不知道新版本的swagger有多不同,但我使用的是1.0.2版。我还使用了
    swagger-spring-mvc-ui-0.4.jar
    来获取swagger API jsp文件和css

    Maven依赖关系

        <dependency>
            <groupId>com.mangofactory</groupId>
            <artifactId>swagger-springmvc</artifactId>
            <version>1.0.2</version>
        </dependency>
    
    我的休息控制器

    @RestController
    @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public class CommonUtilityServices {
    
        @Autowired
        private CommonUtilityService commonUtilityService;
    
        @ApiOperation(value = "Is Unique", notes = "This service checks if a value is already present in DB or not.<br>Below is the sample JSON object. <br> <pre><code class=\"json\">{<span class=\"attribute\"><span class=\"attribute\">\"dbField\"</span></span> : <span class=\"value\"><span class=\"string\"><span class=\"value\"><span class=\"string\">\"organization.name\"</span></span></span></span>, <span class=\"attribute\"><span class=\"attribute\">\"fieldValue\" : <span class=\"value\"><span class=\"string\"><span class=\"value\"><span class=\"string\">\"novopay\"</span></span></span></span>}</code></pre><br>'dbField' accepts value 'tableDB.DBField' format.<br>'fieldValue' is the value needs to be check for uniqueness.")
        @ApiResponses(value = {
                @ApiResponse(code = 202, message = "Request Accepted"),
                @ApiResponse(code = 400, message = "Bad Request") })
        @RequestMapping(value = "/isUnique", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
        public @ResponseBody ResponseEntity<Boolean> isUnique(
                HttpServletRequest request, @RequestBody String jsonStr) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                Map<?, ?> myMap = mapper.readValue(jsonStr.toString(),
                        HashMap.class);
                String dbField = (String) myMap.get("dbField");
                String fieldValue = (String) myMap.get("fieldValue");
                String whereClause = (String) myMap.get("whereClause");
                return new ResponseEntity<Boolean>(
                        commonUtilityService
                                .isValueAlreadyInDB(dbField, fieldValue, whereClause),
                        HttpStatus.ACCEPTED);
            } catch (IOException | RuntimeException e) {
                return new ResponseEntity<Boolean>(HttpStatus.BAD_REQUEST);
            }
        }}
    

    请注意,我在web.xml文件中没有任何更改,并且正在使用spring注释/component scan加载SwagggerConfig类,通过将以下内容添加到AppConfig中进行修复

     <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency>
    

    尽管问题的作者没有使用SpringBoot,但我还是决定在这里发表文章来帮助其他使用SpringBoot的人。 对于使用Spring5.0.0.M5的我,使用SpringSecurity和SpringBoot 它通过在my pom.xml中添加这两个依赖项来工作:

    @SpringBootApplication
    @EnableSwagger2
    public class SpringBootApp extends WebMvcConfigurerAdapter {
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build();
        }
    
        [...]
    }
    
    在此之后,api文档将在我的应用程序根目录上提供,它恰好是/:


    通过这种方式,您甚至不需要此处所述的单独的swagger配置:

    我遇到了这个错误,因为
    springfox-swagger 2
    springfox swagger ui
    之间的版本不匹配,两个依赖项的版本必须相同

    
    伊奥·斯普林福克斯
    springfox-Swagger 2
    2.6.1
    伊奥·斯普林福克斯
    springfox招摇过市用户界面
    2.6.1
    
    我知道这并没有太大帮助,但您的配置似乎非常密集,为了简化配置,您应该尝试使用
    AbstractAnnotationConfigDispatcherServletInitializer的子类,而不是web.xml。它使所有这些xml配置文件消失。其次,您应该能够使用
    WebMVCConfigureAdapter
    注册一些过滤器等,并且所有contextConfigLocation都应该转换为bean导入。通过将以下内容添加到AppConfig中进行修复<代码>@Override public void addResourceHandler(ResourceHandlerRegistry注册表){registry.addResourceHandler(“swagger ui.html”).addResourceLocations(“classpath:/META-INF/resources/”;registry.addResourceHandler(“/webjars/**”).addResourceLocations(“classpath:/META-INF/resources/webjars/”)}
    大多数教程都没有提到这一点,因为它们使用SpringBoot。请参阅以获取参考。您挽救了我的一天,我使用Spring Boot并在更改
    Spring.mvc.static path pattern
    后遇到了问题。这在Spring Boot 2.2.2 Upgrade for me中的一个项目中为我解决了问题。swagger ui依赖项不匹配,从swagger ui依赖项中删除对象为我解决了问题。像这样
    io.springfox-springfox-swagger用户界面
        <dependency>
            <groupId>com.mangofactory</groupId>
            <artifactId>swagger-springmvc</artifactId>
            <version>1.0.2</version>
        </dependency>
    
    import static org.ajar.swaggermvcui.SwaggerSpringMvcUi.WEB_JAR_RESOURCE_LOCATION;
    import static org.ajar.swaggermvcui.SwaggerSpringMvcUi.WEB_JAR_RESOURCE_PATTERNS;
    import static org.ajar.swaggermvcui.SwaggerSpringMvcUi.WEB_JAR_VIEW_RESOLVER_PREFIX;
    import static org.ajar.swaggermvcui.SwaggerSpringMvcUi.WEB_JAR_VIEW_RESOLVER_SUFFIX;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Bean;
    import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
    import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    
    import com.mangofactory.swagger.configuration.SpringSwaggerConfig;
    import com.mangofactory.swagger.models.dto.ApiInfo;
    import com.mangofactory.swagger.plugin.EnableSwagger;
    import com.mangofactory.swagger.plugin.SwaggerSpringMvcPlugin;
    
    @EnableSwagger
    public class SwaggerConfig extends WebMvcConfigurerAdapter {
        private SpringSwaggerConfig springSwaggerConfig;
    
        @Autowired
        public void setSpringSwaggerConfig(SpringSwaggerConfig springSwaggerConfig) {
            this.springSwaggerConfig = springSwaggerConfig;
        }
    
        @Bean
        public SwaggerSpringMvcPlugin customImplementation() {
            this.springSwaggerConfig.defaultSwaggerPathProvider()
                    .setApiResourcePrefix("api");
            return new SwaggerSpringMvcPlugin(this.springSwaggerConfig)
                    .apiInfo(apiInfo());// .includePatterns(".*swagger.*");
        }
    
        private ApiInfo apiInfo() {
            ApiInfo apiInfo = new ApiInfo("My APIs",
                    "RESTful APIs available under My Portal", "#",
                    "deepankarsirt@gmail.com", "License Information", "#");
            return apiInfo;
        }
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler(WEB_JAR_RESOURCE_PATTERNS)
                    .addResourceLocations(WEB_JAR_RESOURCE_LOCATION)
                    .setCachePeriod(0);
        }
    
        @Bean
        public InternalResourceViewResolver getInternalResourceViewResolver() {
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix(WEB_JAR_VIEW_RESOLVER_PREFIX);
            resolver.setSuffix(WEB_JAR_VIEW_RESOLVER_SUFFIX);
            return resolver;
        }
    
        @Override
        public void configureDefaultServletHandling(
                DefaultServletHandlerConfigurer configurer) {
            configurer.enable();
        }
    }
    
    @RestController
    @RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public class CommonUtilityServices {
    
        @Autowired
        private CommonUtilityService commonUtilityService;
    
        @ApiOperation(value = "Is Unique", notes = "This service checks if a value is already present in DB or not.<br>Below is the sample JSON object. <br> <pre><code class=\"json\">{<span class=\"attribute\"><span class=\"attribute\">\"dbField\"</span></span> : <span class=\"value\"><span class=\"string\"><span class=\"value\"><span class=\"string\">\"organization.name\"</span></span></span></span>, <span class=\"attribute\"><span class=\"attribute\">\"fieldValue\" : <span class=\"value\"><span class=\"string\"><span class=\"value\"><span class=\"string\">\"novopay\"</span></span></span></span>}</code></pre><br>'dbField' accepts value 'tableDB.DBField' format.<br>'fieldValue' is the value needs to be check for uniqueness.")
        @ApiResponses(value = {
                @ApiResponse(code = 202, message = "Request Accepted"),
                @ApiResponse(code = 400, message = "Bad Request") })
        @RequestMapping(value = "/isUnique", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
        public @ResponseBody ResponseEntity<Boolean> isUnique(
                HttpServletRequest request, @RequestBody String jsonStr) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                Map<?, ?> myMap = mapper.readValue(jsonStr.toString(),
                        HashMap.class);
                String dbField = (String) myMap.get("dbField");
                String fieldValue = (String) myMap.get("fieldValue");
                String whereClause = (String) myMap.get("whereClause");
                return new ResponseEntity<Boolean>(
                        commonUtilityService
                                .isValueAlreadyInDB(dbField, fieldValue, whereClause),
                        HttpStatus.ACCEPTED);
            } catch (IOException | RuntimeException e) {
                return new ResponseEntity<Boolean>(HttpStatus.BAD_REQUEST);
            }
        }}
    
    <script type="text/javascript">
    $(function() {
        window.swaggerUi = new SwaggerUi({
            url: "/portal/api/api-docs", //New URL
            dom_id: "swagger-ui-container",
            supportedSubmitMethods: ['get', 'post', 'put', 'delete'],
            onComplete: function(swaggerApi, swaggerUi) {
                log("Loaded SwaggerUI");
    
    @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/");
    }
    
     <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency>
    
    @SpringBootApplication
    @EnableSwagger2
    public class SpringBootApp extends WebMvcConfigurerAdapter {
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build();
        }
    
        [...]
    }
    
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.6.1</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.6.1</version>
    </dependency>