swagger 3.0 学习笔记

引入pom

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

配置

import io.swagger.models.auth.In;
import io.swagger.v3.oas.annotations.Operation;
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.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class SwaggerConfig
{
    /**
     * 安全模式,这里指定token通过Authorization头请求头传递
     */
    private List<SecurityScheme> securitySchemes()
    {
        List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.toValue()));
        apiKeyList.add(new ApiKey("Head", "Head", In.HEADER.toValue()));
        apiKeyList.add(new ApiKey("Query", "Query", In.QUERY.toValue()));
        return apiKeyList;
    }

    /**
     * 安全上下文
     */
    private List<SecurityContext> securityContexts()
    {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .operationSelector(o -> o.requestMappingPattern().matches("/.*"))
                        .build());
        return securityContexts;
    }

    /**
     * 默认的安全上引用
     */
    private List<SecurityReference> defaultAuth()
    {
        AuthorizationScope[] authorizationScopes ={new AuthorizationScope("global", "accessEverything")} ;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        securityReferences.add(new SecurityReference("Head", authorizationScopes));
        securityReferences.add(new SecurityReference("Query", authorizationScopes));
        return securityReferences;
    }

     @Bean
      public Docket swagger3() {
          return new Docket(DocumentationType.OAS_30)
                  .select()
                  .apis(RequestHandlerSelectors.withMethodAnnotation(Operation.class))
                  .paths(PathSelectors.regex("/test.*"))
                  .build()
                  .groupName("swagger3.0")
                  .securitySchemes(securitySchemes())
                  .securityContexts(securityContexts())
                  .apiInfo(apiInfo());
      }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo()
    {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                // 设置标题
                .title("标题:XXX系统_接口文档")
                // 描述
                .description("描述:xxxx.")
                // 作者信息
                .contact(new Contact("作者信息", null, null))
                // 版本
                .version("版本号: >...>")
                .build();
    }
}

可以加上全局请求参数
在这里插入图片描述

对象

ReqSwagger3VO

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.io.Serializable;
import java.util.List;

@Data
@Schema(name="ReqSwagger3VO",description ="swagger3对象" )
public class ReqSwagger3VO implements Serializable {
    private static final long serialVersionUID = 646541L;

    @Schema(description = "字符串",example = "aaaa")
    private String dataStr;

    @Schema(description = "数字",example = "1111")
    private Integer dataInt;

    @Schema(description = "字符数组" )
    private List<String> listStr;

    @Schema(description = "数字数组")
    private List<Integer> listInt;

    @Schema(description = "用户")
    private User user;
    @Schema(description = "用户数组")
    private  List<User> userList;

    @Schema(hidden = true)
    private String hiddenStr;
    private String hiddenNotStr;
}

User

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
//https://www.cnblogs.com/antLaddie/p/17418078.html
@Schema(description ="用户信息" )
@Data
@AllArgsConstructor
public class User {
    @Schema(description = "姓名",example = "张三")
    private String name;
    @Schema(description = "年龄",example = "18", format = "int32")
    private int age;
    @Schema( description = "学生分数属性", format = "double", example = "55.50")
    private Double fraction;
}

控制层

example 赋值问题还没解决


import io.swagger.v3.oas.annotations.Hidden;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.StringWriter;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
@RequestMapping("/test/swagger")
@Tag(name = "接口类描述name",description = "接口类描述desc")
public class SwaggerController {

    @Operation(summary = "get请求")
    @GetMapping("{pathParam}/get")
    public Object get(
            @Parameter(description="reqParam参数描述",  schema = @Schema(allowableValues = {"aaa", "22222"}))
            @RequestParam String reqParam,
            @Parameter(description="pathParam参数描述",example = "111")
            @PathVariable Integer pathParam,
            @Parameter(description="headParam参数描述", schema = @Schema(allowableValues = {"888888"}))
            @RequestHeader Long headParam
    ){
        return null;
    }

    @Operation(summary = "get2请求,example赋值不生效",parameters={
            @Parameter(ref="reqParam",name = "reqParam",description="reqParam参数描述",in= ParameterIn.QUERY,  schema = @Schema(allowableValues = {"aaa", "22222"})),
            @Parameter(ref="pathParam", name = "pathParam",description="pathPatam参数描述",in= ParameterIn.PATH,schema = @Schema(allowableValues = {"11111", "333"})),
            @Parameter(ref="headParam", name = "headParam",description="headParam参数描述",in= ParameterIn.PATH,schema = @Schema(allowableValues = {"11111", "333"}))
    })
    @GetMapping("/2/{pathParam}/get")
    public Object get2(@RequestParam String reqParam,@PathVariable Integer pathParam ,@RequestHeader Long headParam){
        return null;
    }

    @Operation(summary = "post请求")
    @PostMapping("/post")
    public Object post(@RequestBody ReqSwagger3VO reqSwaggerVO){
        return null;
    }


    @Hidden
    @PostMapping("/hidden")
    public Object hidden(@RequestBody ReqSwaggerVO reqSwaggerVO){
        return null;
    }


    @Operation(summary = "文件上传")
    @PostMapping(value = "/upload")
    public Object uploadFile(@RequestParam(value = "file") @RequestPart MultipartFile file){

        return null;
    }

    @Operation(summary = "zip下载")
    @PostMapping(value = "/zip/download")
    public void downloadZip(HttpServletResponse response)throws Exception {

        String fileName ="file.zip";

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);

        for (int i = 0; i < 2; i++) {
            StringWriter sw = new StringWriter();
            sw.append("11111a"+i);
            sw.append("2222c"+i);
            // 添加到zip
            zip.putNextEntry(new ZipEntry(i+"name.txt"));
            IOUtils.write(sw.toString(), zip, "UTF-8");
            IOUtils.close(sw);
            zip.flush();
            zip.closeEntry();
        }

        IOUtils.close(zip);
        byte[] data = outputStream.toByteArray();

        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setHeader("Content-Disposition", "attachment; filename=\""+fileName+"\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }

}

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/71317.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

三级城市展示省市区树

展示效果 数据库展示 业务代码 /*** 省市区树*/VLicenseApiOperation("查询经纬度")ApiImplicitParam(name "FnCity", value "省市区树", dataType "FnCity")GetMapping("/districtlist")public AjaxResult districtlist…

strlen和sizeof的区别

大家好&#xff0c;我是苏貝&#xff0c;本篇博客带大家了解C语言中的sizeof和strlen&#xff08;仅此一篇让你明白它们两的差别&#xff09;&#xff0c;如果大家觉得我写的不错的话&#xff0c;可以给我一个赞&#x1f44d;吗&#xff0c;感谢❤️ 文章目录 strlensizeof 在…

Simulink仿真模块 -Scope

Scope模块的作用是显示仿真过程中生成的信号。它包含在以下库中: 库: Simulink / Commonly Used BlocksSimulink / SinksHDL Coder / Commonly Used BlocksHDL Coder / Sinks 如图所示: Simulink Scope 模块和 DSP System Toolbox™ Time Scope 模块显示时域信号。…

【APITable】教程:创建并运行一个自建小程序

1.进入APITable&#xff0c;在想要创建小程序的看板页面点击右上角的【小程序】&#xff0c;进入小程序编辑页面。 2.创建一个新的小程序区。 点击【 添加小程序】 点击创建小程序&#xff0c;选择模板&#xff0c;输入名字。 3.确定后进入小程序部署引导页面。 4.打开Xshell 7…

春秋云镜 CVE-2022-0410

春秋云镜 CVE-2022-0410 WordPress plugin The WP Visitor Statistics SQLI 靶标介绍 WordPress plugin The WP Visitor Statistics (Real Time Traffic) 5.6 之前存在SQL注入漏洞&#xff0c;该漏洞源于 refUrlDetails AJAX 不会清理和转义 id 参数。 登陆账户&#xff1a;u…

LeetCode 热题 100 JavaScript -- 74. 搜索二维矩阵

给你一个满足下述两条属性的 m x n 整数矩阵&#xff1a; 每行中的整数从左到右按非递减顺序排列。 每行的第一个整数大于前一行的最后一个整数。 给你一个整数 target &#xff0c;如果 target 在矩阵中&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 …

D* 算法完全解析(应该是全网最详细的吧)

花了几天时间学习了下 D* 算法&#xff0c;只能说熟悉了一下流程&#xff0c;远不能说掌握&#xff0c;算法实在是非常巧妙 参考 《制造车间无人搬运系统调度方法研究》 《基于D*Lite算法的移动机器人路径规划研究》 人工智能: 自动寻路算法实现(四、D、D*算法) D* 算法 D*路径…

java 文件/文件夹复制,添加压缩zip

复制文件夹,并压缩成zip 需求&#xff1a;创建A文件夹&#xff0c;把B文件夹复制到A文件夹。然后把A文件夹压缩成zip包 public static void main(String[] args) throws Exception {try {String A "D:\\dev\\program";String B "D:\\program";// 创建临…

iOS- git对单个或者多个文件权限设置,使用pre-commit hook 和shell脚本,拦截校验

前提&#xff1a;最近&#xff0c;由于团队代码规范和安全问题&#xff0c;有一些文件只能是指定用户才能修改。 对比&#xff1a;调查了一下资料&#xff0c;发现好多人都在使用pre-commit技术。于是&#xff0c;就朝着这个方向去研究。于是抽空写了脚本&#xff0c;在提交的…

写一个函数返回参数二进制中 1 的个数(c语言三种实现方法)

&#xff08;本文旨在自己做题时的总结&#xff0c;我会给出不同的解法&#xff0c;后面如果碰到新的题目还会加入其中&#xff0c;等于是我自己的题库。 1.写一个函数返回参数二进制中 1 的个数。 比如&#xff1a; 15 0000 1111 4 个 1 方法一&#xff1a; #include…

form中表单切换,导致 relus 中的事件无法触发,原因:页面切换不要一直切换DOM,会导致问题,需要都显示出来

修改前&#xff0c;因为重复渲染DOM导致绑定rules失效 修改前代码使用 computed 计算出渲染的DOM&#xff0c;影响rules事件<el-formref"form"inline:model"billDetailCopy":rules"rules"size"small"label-position"right&quo…

WebStorm

WebStorm 介绍下载安装Activation 介绍 WebStorm是由JetBrains公司开发的一款集成开发环境&#xff08;IDE&#xff09;&#xff0c;主要专注于前端开发和Web开发。它旨在提供一套强大的工具和功能&#xff0c;以支持开发者在前端项目中编写、调试和维护代码。 JetBrains官网: …

Java中声明,定义,分配内存,初始化,赋值,是啥?

一. 声明&#xff0c;定义和分配内存 在Java中&#xff0c;声明和定义是同一个意思&#xff0c;不做区分。下面这些都是声明&#xff08;定义&#xff09;一个变量。 栈&#xff1a;存放局部变量&#xff08;包括基本数据类型的变量和对象的引用&#xff09; 堆&#xff1a;存…

配置:Terminal和oh-my-posh

目录 命令行安装oh-my-posh查看安装情况配置PowerShell启用oh-my-posh、设置主题配色安装字体Terminal中的配置 命令行安装oh-my-posh Set-ExecutionPolicy Bypass -Scope Process -Force; Invoke-Expression ((New-Object System.Net.WebClient).DownloadString(https://ohmy…

YAPi在线接口文档简单案例(结合Vue前端Demo)

在前后端分离开发中&#xff0c;我们都是基于文档进行开发&#xff0c;那前端人员有时候无法马上拿到后端的数据&#xff0c;该怎么办&#xff1f;我们一般采用mock模拟伪造数据直接进行测试&#xff0c;本篇文章主要介绍YApi在线接口文档的简单使用&#xff0c;并结合Vue的小d…

流量,日志分析--理论

提供资料&#xff1a; Wireshark 基本语法&#xff0c;基本使用方法&#xff0c;及包过虑规则 : https://blog.csdn.net/qq_17457175/article/det ails/53019490 ctf 常见流量分析题目类型 : https://ctf-wiki.org/misc/traffic/introduction/ windows 日志 : https://jone…

IntelliJ IDEA和Android studio怎么去掉usage和作者提示

截止到目前我已经写了 600多道算法题&#xff0c;其中部分已经整理成了pdf文档&#xff0c;目前总共有1000多页&#xff08;并且还会不断的增加&#xff09;&#xff0c;大家可以免费下载 下载链接&#xff1a;https://pan.baidu.com/s/1hjwK0ZeRxYGB8lIkbKuQgQ 提取码&#xf…

5.PyCharm基础使用及快捷键

在前几篇文章中介绍了PyCharm的安装和汉化,本篇文章一起来看一下PyCharm的基本用法和一些快捷键的使用方法。 本篇文章PyCharm的版本为PyCharm2023.2 新建项目和运行 打开工具,在菜单中——文件——新建项目 选择项目的创建位置(注意最好不要使用中文路径和中文名项目名称…

基于Gradio的GPT聊天程序

网上很多别人写的&#xff0c;要用账号也不放心。就自己写了一个基于gradio的聊天界面&#xff0c;部署后可以本地运行。 特点&#xff1a; 可以用openai的&#xff0c;也可以用api2d&#xff0c;其他api可以自己测试一下。使用了langchain的库 可以更改模型&#xff0c;会的…

IO密集型服务提升性能的三种方法

文章目录 批处理缓存多线程总结 大部分的业务系统其实都是IO密集型的系统&#xff0c;比如像我们面向B端提供摄像头服务&#xff0c;很多的接口其实就是将各种各样的数据汇总起来&#xff0c;展示给用户&#xff0c;我们的数据来源包括Redis、Mysql、Hbase、以及依赖的一些服务…