隐藏

eclipse+Maven+SpringMVC项目集成Swagge+实践

发布:2021/8/25 14:06:40作者:管理员 来源:本站 浏览次数:916

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。

作用:

  •  接口的文档在线自动生成。
  •  功能测试。

下面通过实现一个web项目来演示Swagger的使用。



1. 新建SpringMVC项目

1.1 新建项目


新建基于maven的webapp项目,步骤如下:



创建项目成功后,先解决错误:index.jsp ----error---<html> The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

解决方案:

问题解决

修改javaSE-1.7版本至javaSE-1.8

修改原pom.xml文件内容,导入Springmvc相关依赖包文件,如下红色内容为新增内容:


<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.ejk5</groupId>
  <artifactId>test2</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>test2 Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <spring.framework.version>4.3.6.RELEASE</spring.framework.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <!-- ********************jackson******************************* -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.9</version>
        </dependency>
        <!-- ********************Spring依赖********************* -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
  </dependencies>

  <build>
    <finalName>test2</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>



1.2 配置web.xml和spring-mvc.xml

替换原web.xml文件内容,内容如下:


<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
  <display-name>Archetype Created Web Application</display-name>
    <!-- Spring MVC 核心控制器 DispatcherServlet 配置-->
    <servlet>
        <servlet-name>spring-mvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring-mvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>  

    <!--   配置编码格式过滤器 -->    
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>  
</web-app>




配置spring-mvc.xml

新建原项目中并没有resources资源文件夹,需要我们自己创建resources资源文件夹,步骤如下:


2. 集成Swagger

2.1 添加swagger相关jar包

<!-- swagger2核心依赖 -->
  <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.7.0</version>
  </dependency>

<!-- swagger-ui为项目提供api展示及测试的界面 -->
  <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger-ui</artifactId>
      <version>2.7.0</version>
  </dependency>


此处swagger 的核心依赖使用springfox-swagger2,SpringFox已经可以代替swagger-springmvc, 目前SpringFox同时支持Swagger 1.2 和 2.0。

新的pom.xml,如下:


<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ejk5</groupId>
    <artifactId>test2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>test2 Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
        <spring.framework.version>4.3.6.RELEASE</spring.framework.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- ********************jackson******************************* -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.9</version>
        </dependency>
        <!-- ********************Spring依赖********************* -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.framework.version}</version>
        </dependency>
        <!-- swagger2核心依赖 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>

        <!-- swagger-ui为项目提供api展示及测试的界面 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
    </dependencies>

    <build>
        <finalName>test2</finalName>
        <pluginManagement><!-- lock down plugins versions to avoid using Maven
                defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.1.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.22.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

2.2 添加SwaggerConfig

先创建com.ejk5.test2.config包


再创建一个swagger配置文件类,SwaggerConfig.java


替换SwaggerConfig的内容,如下:

package com.ejk5.test2.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())  //显示所有类
                //.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))  //只显示添加@Api注解的类
                .build()
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("开放接口API")  //粗标题
                .description("HTTP对外开放接口")   //描述
                .version("1.0.0")   //api version
                .termsOfServiceUrl("http://xxx.xxx.com")
                .license("LICENSE")   //链接名称
                .licenseUrl("http://xxx.xxx.com")   //链接地址
                .build();
    }

}

2.3 静态资源访问配置

上面引入的springfox-swagger-ui依赖为我们提供了静态资源访问的支持,通过访问他为我们提供的页面,可以直观的看出项目所开放的接口API。

要想访问该页面,还需要增加访问配置,方法有两种:

2.3.1 在spring-mvc.xml中增加配置

<!-- swagger静态资源访问配置 -->  <mvc:resources mapping="swagger-ui.html" location="classpath:/META-INF/resources/" />  <mvc:resources mapping="/webjars/**" location="classpath:/META-INF/resources/webjars/" />
最终spring-mvc.xml内容为:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 默认的注解映射的支持 ,它会自动注册DefaultAnnotationHandlerMapping 与AnnotationMethodHandlerAdapter -->
    <mvc:annotation-driven />
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>
    <!-- swagger静态资源访问配置 -->
    <mvc:resources mapping="swagger-ui.html"
        location="classpath:/META-INF/resources/" />
    <mvc:resources mapping="/webjars/**"
        location="classpath:/META-INF/resources/webjars/" />

    <!-- enable autowire 向容器自动注册 -->
    <context:annotation-config />

    <!-- 设置使用注解的类所在的jar包 -->
    <context:component-scan
        base-package="com.ejk5.test2" />
    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

</beans>

2.3.2 或者增加配置类WebAppConfig

package com.ejk5.test2.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebAppConfig 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/");
    }

}

3. 测试API接口

3.1 访问“项目地址/swagger-ui.html#/” 查看api

访问 http://localhost:8080/test2/swagger-ui.html#/ 出现如下界面,说明我们的swagger集成项目成功。

在参数中输入信息,可实现对接口的调用


但是单调的页面没有实现swagger作为API文档工具的作用,这需要我们通过注解在接口方法中配置。

3.2 通过注解生成API文档

常用注解如下:

常用注解: 

  • @Api()用于类; 表示标识这个类是swagger的资源 
  • @ApiOperation()用于方法; 表示一个http请求的操作 
  • @ApiParam()用于方法,参数,字段说明; 表示对参数的添加元数据(说明或是否必填等) 
  • @ApiModel()用于类 表示对类进行说明,用于参数用实体类接收 
  • @ApiModelProperty()用于方法,字段 ;表示对model属性的说明或者数据操作更改 
  • @ApiIgnore()用于类,方法,方法参数 ;表示这个方法或者类被忽略 
  • @ApiImplicitParam() 用于方法 ;表示单独的请求参数 
  • @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
@RestController
@RequestMapping(value = { "/product/" })
// 类上加@Api注解
@Api(value = "/ProductController", tags = "接口开放示例")
public class ProductController {


    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    // 方法上加ApiOpreation注解
    @ApiOperation(value = "根据id获取产品信息", notes = "根据id获取产品信息", httpMethod = "GET", response = Product.class)
    public ResponseEntity<Product> get(@PathVariable Long id) {
        Product product = new Product();
        product.setName("空气净化器");
        product.setId(1L);
        product.setProductClass("filters");
        product.setProductId("T12345");
        return ResponseEntity.ok(product);
    }
}

添加注解之后,访问swagger界面如下

3.3 其他方法测试

多增加几个测试方法

@RequestMapping(method = RequestMethod.POST)
    @ApiOperation(value = "添加一个新的产品")
    @ApiResponses(value = { @ApiResponse(code = 405, message = "参数错误") })
    public ResponseEntity<String> add(Product product) {
        return ResponseEntity.ok("SUCCESS");
    }

    @RequestMapping(method = RequestMethod.PUT)
    @ApiOperation(value = "更新一个产品")
    @ApiResponses(value = { @ApiResponse(code = 400, message = "参数错误") })
    public ResponseEntity<String> update(Product product) {
        return ResponseEntity.ok("SUCCESS");
    }

    @RequestMapping(method = RequestMethod.GET)
    @ApiOperation(value = "获取所有产品信息", notes = "获取所有产品信息", httpMethod = "GET", response = Product.class, responseContainer = "List")
    public ResponseEntity<List<Product>> getAllProducts() {
        Product product = new Product();
        product.setName("七级滤芯净水器");
        product.setId(1L);
        product.setProductClass("seven_filters");
        product.setProductId("T12345");
        return ResponseEntity.ok(Arrays.asList(product, product));
    }

swagger界面为不同方法提供不同颜色显示,可在其中对各个接口进行测试

项目结构如下: