Swagger UI 與SpringMVC的整合

關於 Swagger

Swagger能成爲最受歡迎的REST APIs文檔生成工具之一,有如下幾個緣由:javascript

  • Swagger 能夠生成一個具備互動性的API控制檯,開發者能夠用來快速學習和嘗試API。
  • Swagger 能夠生成客戶端SDK代碼用於各類不一樣的平臺上的實現。
  • Swagger 文件能夠在許多不一樣的平臺上從代碼註釋中自動生成。
  • Swagger 有一個強大的社區,裏面有許多強悍的貢獻者。

Swagger 文檔提供了一個方法,使咱們能夠用指定的 JSON 或者 YAML 摘要來描述你的 API,包括了好比 names、order 等 API 信息。html

你能夠經過一個文本編輯器來編輯 Swagger 文件,或者你也能夠從你的代碼註釋中自動生成。各類工具均可以使用 Swagger 文件來生成互動的 API 文檔。java

Swagger 、SwaggerUI與SpringMVC的整合

1.Maven引入web

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.5.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.5.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-staticdocs</artifactId>
    <version>2.5.0</version>
</dependency>
<dependency>  
    <groupId>org.hibernate</groupId>  
    <artifactId>hibernate-validator</artifactId>  
    <version>5.2.4.Final</version>  
</dependency>

 

2.配置webconfig.xmlspring

將 DispatcherServlet 的 url-pattern 改成 /json

<servlet>
    <servlet-name>springMvc</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>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

 

3.在spring-mvc.xml中添加自動掃描api

<mvc:annotation-driven  />
    
    <!-- 自動掃描(自動注入) -->
     <context:component-scan base-package="com.xhl.swagger.api"/>
     <mvc:default-servlet-handler/>

 

4.新建Swagger配置類spring-mvc

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

import com.google.common.base.Predicates;

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

@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
    
     @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2).select()
                    .apis(Predicates.not(RequestHandlerSelectors.basePackage("org.springframework.boot")))
                    .build();
        }
     
        @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/");
        }
}

 

5.建測試的Controller和常量mvc

public interface Constants {
    /****** 系統標識符 開始 *********/
    /**
    * 錯誤 描述
    */
    String MSG_ERROR = "error";
    /**
    * 成功 描述
    */
    String MSG_SUCCESS = "OK";
    
    /****** 系統狀態碼 開始 ******/
    /**
    * 請求失敗
    */
    int ERROR = 100;
    /**
    * 請求成功
    */
    int SUCCESS = 200;
}
import java.io.Serializable;

import com.fasterxml.jackson.annotation.JsonInclude;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Result<T> implements Serializable {

    private static final long serialVersionUID = 1L;
    
    /** 正常狀態爲0或200 **/
    @ApiModelProperty(value = "狀態代碼", name = "狀態代碼")
    private int code;
    
    /** 是code異常時,返回的錯誤信息(app直接顯示) **/
    @ApiModelProperty(value = "錯誤碼描述", name = "錯誤碼描述")
    private String message;
    
    /** 返回的數據對象 **/
    @ApiModelProperty(value = "數據對象", name = "數據對象")
    private T data;
    
    /** 是code正常時的提示(不爲空,app直接展現) **/
    @ApiModelProperty(value = "code正常時的提示信息", name = "code正常時的提示信息")
    private String toast = "";
    
    /** response中容許 空值,不容許 NULL值出現 **/
    @ApiModelProperty(value = "響應流信息", name = "響應流信息")
    private String response = "";
    
    public Result() {
    }
    
    public Result(int code,String message) {
        this.code = code;
        this.message = message;
    }

    public Result(int code,String message,T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
    
    public Result(int code,String message,T data,String toast,String response) {
        this.code = code;
        this.message = message;
        this.data = data;
        this.toast = toast;
        this.response = response;
    }
    
    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getToast() {
        return toast;
    }

    public void setToast(String toast) {
        this.toast = toast;
    }

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }
   @Override
    public String toString() {
        return "Result{" +
                "code=" + code +
                ", message='" + message + '\'' +
                ", data=" + data + '\'' +
                ", toast=" + toast + '\'' +
                ", response=" + response + 
                '}';
    }
}
@ApiModel(value = "用戶信息")
public class UserVo {
    @ApiModelProperty(value = "用戶id", required = true)
    private String userId;
    @ApiModelProperty(value = "暱稱", required = true)
    private String userName;
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
}
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.qdingnet.pcloud.api.common.utils.StringUtils;
import com.qdingnet.pcloud.api.swagger.constants.Constants;
import com.qdingnet.pcloud.api.swagger.constants.Result;
import com.qdingnet.pcloud.api.swagger.vo.UserVo;

import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

@RestController
@RequestMapping("/api/json/user")
public class SwaggerController {

    
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ApiOperation(value = "添加用戶", notes = "增長用戶")
    public Result<UserVo> add(@ApiParam(name = "token", value = "token",required = true) @RequestParam(name = "token", required = true) String token,
                              @ApiParam(name = "userName",value = "用戶暱稱",required = true)@RequestParam(name = "userName",required = true)String userName,
                              @ApiParam(name = "mobile",value = "手機",required = true)@RequestParam(name = "mobile",required = true)String mobile,
                              @ApiParam(required = true, name = "email", value = "郵箱") @RequestParam(name = "email", required = true) String email ) {
        UserVo userVo = new UserVo();
        userVo.setUserId(StringUtils.getUUID());
        userVo.setUserName(userName);
        return new Result<UserVo>(Constants.SUCCESS,Constants.MSG_SUCCESS,userVo);
    }
    
    @RequestMapping(value = "/getUser", method = RequestMethod.GET)
    @ApiOperation(value = "測試獲取用戶", notes = "測試獲取用戶")
    public Result<UserVo> getUser() {
        UserVo userVo = new UserVo();
        userVo.setUserId(StringUtils.getUUID());
        userVo.setUserName("測試獲取用戶");
        return new Result<UserVo>(Constants.SUCCESS,Constants.MSG_SUCCESS,userVo);
    }
}

 

6.測試運行app

首先經過:http://localhost:8080/工程名/api/json/user/getUser.do  能夠訪問:

{"code":200,"message":"OK","data":{"userId":"d1239dc4e4164662af754c64e42762cd","userName":"測試獲取用戶"},"toast":"","response":""}

其次經過:http://localhost:8080/工程名/v2/api-docs 能夠查看具體的接口描述信息:

最後經過:http://localhost:8080/工程名/swagger-ui.html 進行訪問和測試:

7.若是請求須要帶參數的話,Swagger能夠直接顯示出能夠輸入請求參數的入口和描述:

請求結果:

Try it out 

相關文章
相關標籤/搜索