1. 程式人生 > >SpringBoot整合SwaggerUI自動生成介面文件

SpringBoot整合SwaggerUI自動生成介面文件

SpringBoot整合SwaggerUI自動生成介面文件

一、在pom.xml檔案裡新增SpringBoot的引用配置,程式碼如下:

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

二、在com.course包下新增config包,config包下新增SwaggerConfig配置類,程式碼如下:

package com.course.config;

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.WebMvcConfigurationSupport;
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;

@Configuration
@EnableSwagger2
//固定寫法
public class SwaggerConfig extends WebMvcConfigurationSupport {

    //2.6.1版本配置
    @Bean
    public Docket api(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                //v1取的是註解裡的value值
                .pathMapping("v1")
                .select()
                //"/.*"是通過正則匹配方法的路徑
                .paths(PathSelectors.regex("/.*"))
                .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder().title("UserManager service API")
                .contact("
[email protected]
") .description("this is UserManager service API") .version("1.0") .build(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/source/**").addResourceLocations("classpath:/static/"); //新增swagger-ui訪問 registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }

四、在com.course.server包下修改MyGetMethod類和MyPostMethod類

package com.course.server;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

//@RestController表示我是需要被掃描的類
@RestController
//介面文件註解
@Api(value = "v1",description = "這是我全部的get方法")

public class MyGetMethod {

    //設定訪問路徑和請求方法
    @RequestMapping(value = "/getCookies",method = RequestMethod.GET)
    //介面文件描述
    @ApiOperation(value = "通過這個方法可以獲取到cookies",httpMethod = "Get")
    //HttpServerletRequest 裝請求資訊的類
    //HttpServerletResponse  裝響應資訊的類
    public String getCookies(HttpServletResponse response){

        Cookie cookie = new Cookie("login","true");
        response.addCookie(cookie);
        return "恭喜你獲得cookies成功2";
    }

    /**
     * 要求客戶端攜帶cookies訪問
     * 這是一個需要攜帶cookies資訊才能訪問的get請求
     */
    @RequestMapping(value = "/get/with/cookies",method = RequestMethod.GET)
    //介面文件描述
    @ApiOperation(value = "要求客戶端攜帶cookies訪問",httpMethod = "Get")
    //HttpServerletRequest 裝請求資訊的類
    //HttpServerletResponse  裝響應資訊的類
    public String getWithCookies(HttpServletRequest request){
        //獲取cookies
        Cookie[] cookies = request.getCookies();
        //判斷cookies是否為空
        if (Objects.isNull(cookies)){
            return "你必須攜帶cookies資訊來訪問";
        }
        //判斷cookies是否正確
        for (Cookie cookie : cookies){
            if (cookie.getName().equals("login") &&
                    cookie.getValue().equals("true"))
                return "訪問成功";
        }
        return "你必須攜帶正確的cookies資訊來訪問";
    }

    /**
     * 開發一個需要攜帶引數才能訪問的get請求
     * 第一種實現方式 url: key=value&key=value
     * 我們來模擬獲取商品列表
     */

    @RequestMapping(value = "/get/with/param",method =RequestMethod.GET )
    //介面文件描述
    @ApiOperation(value = "需要攜帶引數才能訪問的get請求1",httpMethod = "Get")
    //@RequestParam註解設定開始位置和結束位置
    public Map<String,Integer> getlist(@RequestParam Integer start,
                                       @RequestParam Integer end){
        //定義商品列表
        Map<String,Integer> myList = new HashMap<>();
        //填入商品
        myList.put("鞋",400);
        myList.put("乾脆面",1);
        myList.put("襯衫",300);

        return  myList;
    }

    /**
     * 第二種需要攜帶引數訪問的get請求
     * url:ip:port/get/with/param/10/20
     */

    @RequestMapping(value = "/get/with/param/{start}/{end}")
    //介面文件描述
    @ApiOperation(value = "需要攜帶引數才能訪問的get請求2",httpMethod = "Get")
    public Map myGetList(@PathVariable Integer start,
                         @PathVariable Integer end){

        Map<String,Integer> myList = new HashMap<>();

        myList.put("鞋",400);
        myList.put("乾脆面",1);
        myList.put("襯衫",300);

        return  myList;
    }
    }
package com.course.server;

import com.course.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.servlet.http.Cookie;


import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
//介面文件註解
@Api(value = "v1",description = "這是我全部的post請求")
//訪問地址前要加/v1
@RequestMapping("/v1")
public class MyPostMethod {

    //這個變數是用來裝我們cookies資訊的
    private static Cookie cookie;

    //使用者登入成功獲取到cookies,如何再訪問其他介面獲取到列表

    @RequestMapping(value = "/login",method = RequestMethod.POST)
    //介面文件描述
    @ApiOperation(value = "登陸介面,成功後獲取cookies資訊",httpMethod = "post")
    public String login(HttpServletResponse response,
                        @RequestParam(value = "userName",required = true) String userName,
                        @RequestParam(value = "password",required = true) String password){
        if (userName.equals("zhangsan")&&password.equals("123456")){
             cookie = new Cookie("login","true");
            response.addCookie(cookie);
            return "恭喜你登陸成功";
        }
        return "使用者名稱或者密碼錯誤!";
    }


    @RequestMapping(value = "/getUserList",method = RequestMethod.POST)
    //介面文件描述
    @ApiOperation(value = "獲取使用者列表",httpMethod = "POST")
    public String getUserList(HttpServletRequest request,
        @RequestBody User u){

        //宣告物件
        User user;
        //獲取cookies
        Cookie[] cookies = request.getCookies();
        //驗證cookies是否合法
        for (Cookie c : cookies){
            if (c.getName().equals("login")
                    && c.getValue().equals("true")
                    && u.getUserName().equals("zhangsan")
                    && u.getPassword().equals("123456")
            ){
                user = new User();
                user.setName("lisi");
                user.setAge("18");
                user.setSex("man");
                return user.toString();
            }

        }
        return "引數不合法";
    }
}

五、啟動Application類,在瀏覽器輸入http://127.0.0.1:8081/swagger-ui.html
在這裡插入圖片描述