天天看點

Springboot整合自定義頁面swaggerUiSpringboot整合自定義頁面swaggerUi

文章目錄

  • Springboot整合自定義頁面swaggerUi
    • pom
    • 重點:配置swagger權限認證下:基于Spring Security
    • 測試
    • 整合效果
    • 報錯記錄

Springboot整合自定義頁面swaggerUi

pom

<dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
            <exclusions>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>swagger-bootstrap-ui</artifactId>
            <version>1.9.6</version>
        </dependency>
           

重點:配置swagger權限認證下:基于Spring Security

SwaggerConfig

package com.shbykj.springboot.util.swaggerUi;

import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Slf4j
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class SwaggerConfig implements WebMvcConfigurer {

    /**
     * 顯示swagger-ui.html文檔展示頁,還必須注入swagger資源:
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    private ApiInfo apiInfo() {
        String name = "VOCs線上監測系統開發組";
        String url = "";
        String email = "[email protected]";
        Contact contact = new Contact(name, url, email);
        return (new ApiInfoBuilder()).title("VOCs線上監測系統 後端接口").description("VOCs線上監測系統 後端接口").termsOfServiceUrl("http://localhost:8086/doc.html").contact(contact).version("1.0").build();
    }

    /**
     * 幫助中心 (不同的子產品這裡分不同的包掃描basePackage)
     * Docket 可以配置多個
     *
     * @return
     */
    @Bean
    public Docket assist() {
        return new Docket(DocumentationType.SWAGGER_2)
//                .globalOperationParameters(setRequestHeaders())
                .apiInfo(this.apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.shbykj.springboot"))
                //加了ApiOperation注解的類,才生成接口文檔
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build()
                .groupName("幫助中心");
    }
    /**
     * 設定請求頭
     *
     * @return
     */
//    private List<Parameter> setRequestHeaders() {
//        ParameterBuilder ticketPar = new ParameterBuilder();
//        List<Parameter> pars = new ArrayList<Parameter>();
//        ticketPar.name("token").description("使用者token")
//                .modelRef(new ModelRef("string")).parameterType("header")
//                .required(false).build(); //header中的ticket參數非必填,傳空也可以
//        pars.add(ticketPar.build());      //根據每個方法名也知道目前方法在設定什麼參數
//        return pars;
//    }
}
           

測試

package com.shbykj.springboot.common.controller.sys;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.shbykj.springboot.common.pojo.sys.Dict;
import com.shbykj.springboot.common.service.sys.SysDictService;
import com.shbykj.springboot.query.BaseQuery;
import com.shbykj.springboot.result.PageUi;
import com.shbykj.springboot.user.service.UserService;
import com.shbykj.springboot.user.vo.UserVo;
import com.shbykj.springboot.util.AjaxResult;
import com.shbykj.springboot.util.SecurityUtil;
import com.shbykj.springboot.util.StringUtils;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.persistence.*;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.lang.reflect.Type;
import java.util.*;

/**
 * @author
 * @date 2020-10-21 16:06
 */
@Api(
        tags = {"資料字典表接口"}
)
@Log4j2
@RestController
public class TestController {
    private final static Map<Integer, DictEntity> dicts = new LinkedHashMap<Integer, DictEntity>();

    {
        dicts.put(1, new DictEntity("1", "字典類型1", "字典名稱", "1588888888", "aaaa", "aaaa", 1L, 1L, new Date(), new
                Date()));
        dicts.put(2, new DictEntity("2", "字典類型2", "字典名稱2", "11111", "BBBB", "AAA", 1L, 1L, new Date(), new
                Date()));


    }


    @ApiOperation("獲字典清單")
    @GetMapping("/api/dict/list")
    public Map<String, Object> userList() {
        Map<String, Object> mapList = new HashMap<>();
        List<DictEntity> dictList = new ArrayList<DictEntity>(dicts.values());
        mapList.put("jsonFlag", 1);
        mapList.put("data", dictList);
        return mapList;
    }

    @ApiOperation("擷取字典詳細")
    @ApiImplicitParams({
            @ApiImplicitParam(
                    name = "id", value = "字典ID", required = true, dataType = "String", paramType = "path"
            )
            , @ApiImplicitParam(
            name = "name",
            value = "字典name",
            dataType = "string",
            paramType = "path"
    ), @ApiImplicitParam(
            name = "code",
            value = "code",
            dataType = "string",
            paramType = "path"
    )
    })
    @GetMapping("/api/dict/{id}")
    public AjaxResult getUser(@PathVariable String id, @RequestParam String name,@RequestParam String code) {
        System.out.println("id:" + id + "  name:" + name+" code :"+code);
        if (!dicts.isEmpty() && dicts.containsKey(id)) {
            return AjaxResult.success(dicts.get(id));
        }
        return AjaxResult.error("字典不存在");
    }
}

@ApiModel("字典實體")
@Data
@NoArgsConstructor
@AllArgsConstructor
class DictEntity extends BaseQuery implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 字典編号
     */
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @ApiModelProperty("字典ID")
    private String id;
    @ApiModelProperty("字典類型")
    private String type;
    /**
     * 字典名稱
     */
    @ApiModelProperty("字典名稱")
    private String name;
    /**
     * 字典值
     */
    @ApiModelProperty("字典值")
    private String value;
    /**
     * 字典代碼
     */
    @ApiModelProperty("字典代碼")
    private String code;
    @ApiModelProperty("字典備注")
    private String remark;
    /**
     * 建立人
     */
    @ApiModelProperty("建立人")
    private Long creater;
    /**
     * 修改人
     */
    @ApiModelProperty("修改人")
    private Long modifier;

    @Column(name = "gmt_create")
    @ApiModelProperty("建立時間")
    private Date gmtCreate;
    @Column(name = "gmt_modified")
    @ApiModelProperty("修改時間")
    private Date gmtModified;


    //hh為12小時制,HH為24小時制;GMT+8 東八區
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getGmtCreate() {
        return gmtCreate;
    }

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    public void setGmtCreate(Date gmtCreate) {
        this.gmtCreate = gmtCreate;
    }

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public Date getGmtModified() {
        return gmtModified;
    }

    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    public void setGmtModified(Date gmtModified) {
        this.gmtModified = gmtModified;
    }

}

           

整合效果

Springboot整合自定義頁面swaggerUiSpringboot整合自定義頁面swaggerUi

1.檢視字典清單

http://localhost:8086/api/dict/list
Springboot整合自定義頁面swaggerUiSpringboot整合自定義頁面swaggerUi

2.檢視字典詳情

http://localhost:8086/api/dict/1?name=%22aaa%22&code=%22bbbb%22
Springboot整合自定義頁面swaggerUiSpringboot整合自定義頁面swaggerUi

報錯記錄

Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:
Springboot整合自定義頁面swaggerUiSpringboot整合自定義頁面swaggerUi

出現的主要原因是:

掃描不到swaggerConfig所在的路徑,是以需要在啟動類的ComponentScan中加入類的路徑

解決方法:

将componentScan裡的路徑改為SwaggerConfig類所在的包的路徑

或者

使用構造器初始化