天天看点

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类所在的包的路径

或者

使用构造器初始化