Front-end separation, interface debugging tool--Swagger

table of Contents

 

1. Background

Two, introduction to the use of Swagger

Three, Swagger environment construction


1. Background

When the front and back ends are separated, the back-end personnel often have to independently develop a usable interface by themselves. At this time, api tools such as postman , Swagger , idea plug-ins, etc. are used. Of course, this article mainly introduces the construction and use of Swagger.

Environment: SpringBoot + Swagger2

 

Two, introduction to the use of Swagger

1. Controller-Use Swagger in Controller

Attributes Description
@Api(tags = "xx管理") On the modification class, tags mark the role of this class
@ApiOperation(notes="xx", value="xx") In the modification method, the notes standard method description, the specific function of the value standard method (addition, deletion, modification and investigation)
@ApiResponse(code=xx, message="xx") In the modification method, code responds with a successful status code, and message is a success message

2. DTO transport layer Swagger usage

Attributes Description
@ApiModelProperty(name="xx", value="xx") Modified attribute, attribute description, name object attribute name, value corresponding attribute description
@NotNull(message="xxx cannot be empty") Modified attribute, indicating that the attribute is non-empty, must be lost
@Length(max=xx) Modification attributes, generally characters, indicating the maximum length limit

 

Example description

WordController.java

package com.essm.controller;

import com.essm.entity.WordDO;
import com.essm.remote.WordReqDTO;
import com.essm.remote.WordRspDTO;
import com.essm.service.WordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 单词控制层
 *
 * @author :HUANG ZHI XUE
 * @date :Create in 2020-08-18
 */
@RestController
@Api(tags = "单词管理")
public class WordController {

    @Autowired
    WordService wordService;

    @ApiOperation(notes = "单词管理", value = "单词管理-查询接口")
    @ApiResponse(code = 200, message = "查询成功")
    @PostMapping("/listWordInfo")
    public List<WordRspDTO> listWordInfo(@Validated @RequestBody WordReqDTO reqDto) {
        return wordService.listWordInfo(reqDto);
    }
}

 

WordReqDTO.java
package com.essm.remote;

import io.swagger.annotations.ApiModelProperty;

import javax.validation.constraints.NotNull;

/**
 * 请求通用dto
 *
 * @author :HUANG ZHI XUE
 * @date :Create in 2020-08-18
 */
public class WordReqDTO {

    /** 单词编号 */
    @ApiModelProperty(name = "id", value = "单词编号", required = true)
    @NotNull(message = "单词编号不能为空")
    private Integer id;

    /** 用户编号 */
    private Integer trl;

    /** 单词中文 */
    private String chinese;

    /** 单词英文 */
    private String english;

    /** 单词状态位 */
    private Integer sign;

    public WordReqDTO() {
    }

    public WordReqDTO(Integer id, Integer trl, String chinese, String english, Integer sign) {
        this.id = id;
        this.trl = trl;
        this.chinese = chinese;
        this.english = english;
        this.sign = sign;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getTrl() {
        return trl;
    }

    public void setTrl(Integer trl) {
        this.trl = trl;
    }

    public String getChinese() {
        return chinese;
    }

    public void setChinese(String chinese) {
        this.chinese = chinese;
    }

    public String getEnglish() {
        return english;
    }

    public void setEnglish(String english) {
        this.english = english;
    }

    public Integer getSign() {
        return sign;
    }

    public void setSign(Integer sign) {
        this.sign = sign;
    }

    @Override
    public String toString() {
        return "WordDO{" +
                "id=" + id +
                ", trl=" + trl +
                ", chinese='" + chinese + '\'' +
                ", english='" + english + '\'' +
                ", sign=" + sign +
                '}';
    }
}

 

Three, Swagger environment construction

1. Pom.xml dependency

		<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>

2. Add the swagger configuration file SwaggerConfig.java

package com.essm.config;

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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Swagger配置
 *
 * @author :HUANG ZHI XUE
 * @date :Create in 2020-08-13
 */
@Configuration
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket createApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.essm.controller"))
                .paths(PathSelectors.any())
                .build();

    }
    //设置swagger的一些信息
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger2")
                .description("Restful API接口")
                .version("1.0.1")
                .build();
    }
}

3. If the path is intercepted, the swagger page needs to be released (the own project is relatively old, you can add it according to the actual situation)

Focus on

    /**
     * 添加静态资源文件,外部可以直接访问地址
     *
     * @param registry
     */
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //解决静态资源无法访问
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        // 解决swagger无法访问
        registry.addResourceHandler("/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        // 解决swagger的js文件无法访问
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

All configuration classes:

package com.essm.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.io.IOException;

/**
 * @Description
 * 扩展SpringMVC功能
 * 1、固定页面跳转
 * 2、拦截器
 * @Author xuexue
 * @Date 2020/5/19 19:52
 */
@Configuration
public class EssmMvcConfig implements WebMvcConfigurer {

    @Autowired
    private StaticPagePathFinder staticPagePathFinder;

    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/essm.html").setViewName("index");
        registry.addViewController("/essm").setViewName("index");


        //addViewControllers可以方便的实现一个请求直接映射成视图,而无需书写controller
        //registry.addViewController(
        // "请求路径").setViewName("请求页面文件路径")
        try{
            for(StaticPagePathFinder.PagePaths pagePaths :staticPagePathFinder.findPath()){
                String urlPath = pagePaths.getUrlPath();
                registry.addViewController(urlPath+".html").setViewName(pagePaths.getFilePath());
                if(!urlPath.isEmpty()) {
                    registry.addViewController(urlPath).setViewName(pagePaths.getFilePath());
                }
            }
        }catch(IOException e){
            throw new RuntimeException("Unable to locate static pages:"+e.getMessage(),e);
        }

    }

    /**
     * 登录拦截器
     *
     * @param registry
     */
    public void addInterceptors(InterceptorRegistry registry) {
        String[] excludes = new String[]{"/login.html", "/login", "/essm", "/header.html", "/essm.html", "/static/**"};
        registry.addInterceptor(new MyInterceptor()).
                addPathPatterns("/**").
                excludePathPatterns(excludes);
    }

    /**
     * 添加静态资源文件,外部可以直接访问地址
     *
     * @param registry
     */
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //解决静态资源无法访问
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
        // 解决swagger无法访问
        registry.addResourceHandler("/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        // 解决swagger的js文件无法访问
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

4. Create a WordController under the corresponding scan package

5. Start the project, add /swagger-ui.html to the project address, as shown in the figure

 

 

Guess you like

Origin blog.csdn.net/qq_41055045/article/details/108206106