文章目录

  • 一,配置
    • 1,pom依赖
    • 2,通用配置
  • 二,注解
  • 三,主题
    • 1,默认主题效果
    • 2,添加依赖
    • 3,添加配置
    • 4,启动看效果
  • 四,token验证
    • 方法1,所有接口上添加
    • 方法2,全局统一添加
  • 五,文件
    • 1,配置依赖
    • 2,添加插件,放在pom中build-plugins标签内
    • 3,新建测试类,并运行生成相关文件
    • 4,中文乱码或丢失问题
    • 5,执行命令
  • 六,参考文档
  • 七,Github

一,配置

1,pom依赖

在pom.xml中添加相关依赖

     <properties><swagger.version>2.9.2</swagger.version></properties><dependencies><!-- swagger --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>${swagger.version}</version></dependency><!-- swagger ui springfox --><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>${swagger.version}</version></dependency></dependencies>

2,通用配置

@EnableSwagger2
@Configuration
public class Swagger2Config implements WebMvcConfigurer {@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");registry.addResourceHandler("/swagger/**").addResourceLocations("classpath:/static/swagger/");}//配置content typeprivate static final Set<String> DEFAULT_PRODUCES_AND_CONSUMES =new HashSet<String>(Arrays.asList("application/json"));//,"application/xml",只需要json格式@Beanpublic UiConfiguration uiConfiguration(){return UiConfigurationBuilder.builder()// 隐藏UI上的Models模块:-1为不显示,默认为0显示.defaultModelsExpandDepth(0).build();}@Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).groupName("xmliu")// 不能为中文,否则termsOfServiceUrl打不开.consumes(DEFAULT_PRODUCES_AND_CONSUMES).produces(DEFAULT_PRODUCES_AND_CONSUMES).useDefaultResponseMessages(false)//不使用默认相应code.apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("cn.xmliu.swagger.web")).paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("swagger测试项目").contact(new Contact("liuxunming","liuxunming.com","diyangxia@163.com")).description("swagger测试API接口文档").termsOfServiceUrl("http://www.liuxunming.com/").version("1.0").build();}
}

二,注解

  • Api
  • ApiOperation
  • ApiResponses ApiResponse
  • ApiImplicitParams ApiImplicitParam
  • ApiIgnore
  • ApiModel ApiModelProperty
@Api(tags = "健康API接口")
@Controller
@RequestMapping("/health")
public class HealthController {@Autowiredprivate HealthService healthService;@ApiOperation(value="查询", notes="条件查询",hidden = false)@ApiResponses(value = {@ApiResponse(code = 200, message = "返回所有数据",response = Health.class)})@ApiImplicitParams({@ApiImplicitParam(name="name",value="名字",required=false,paramType="form"),@ApiImplicitParam(name="address",value="住址",required=false,paramType="form"),@ApiImplicitParam(name="level",value="等级",required=false,paramType="form",dataType="Integer")})@GetMapping(value = "allData")@ResponseBodypublic ServerResponse allData(@RequestParam (required = false) String id){List<Health> list = healthService.findList();return ServerResponse.success().put("list",list);}}

三,主题

1,默认主题效果

2,添加依赖

 <!-- swagger ui bootstrap --><dependency><groupId>com.github.xiaoymin</groupId><artifactId>swagger-bootstrap-ui</artifactId><version>1.9.1</version></dependency>

3,添加配置

        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");

4,启动看效果

四,token验证

方法1,所有接口上添加

@Beanpublic Docket createRestApi() {ParameterBuilder ticketPar = new ParameterBuilder();List<Parameter> pars = new ArrayList<Parameter>();ticketPar.name("Authorization").description("token每次请求都需带上,否则无法通过过滤器(登录登出无需),值为登录返回的token值").modelRef(new ModelRef("string")).parameterType("header")//header中的ticket参数非必填,传空也可以.required(false).build();//根据每个方法名也知道当前方法在设置什么参数pars.add(ticketPar.build());return new Docket(DocumentationType.SWAGGER_2).groupName("xmliu")// 不能为中文,否则termsOfServiceUrl打不开.consumes(DEFAULT_PRODUCES_AND_CONSUMES).produces(DEFAULT_PRODUCES_AND_CONSUMES).useDefaultResponseMessages(false)//不使用默认相应code.globalOperationParameters(pars).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("cn.xmliu.swagger.web")).paths(PathSelectors.any()).build();}

每个接口都会要输入一遍token,比较麻烦,推荐使用方法2

方法2,全局统一添加

 @Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).groupName("atab").consumes(DEFAULT_PRODUCES_AND_CONSUMES).produces(DEFAULT_PRODUCES_AND_CONSUMES).useDefaultResponseMessages(false).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("cn.xmliu.swagger.web")).paths(PathSelectors.any()).build().securitySchemes(securitySchemes())    // token验证.securityContexts(securityContexts()); // token验证}
  /*** 安全模式,这里指定token通过Authorization头请求头传递*/private List<SecurityScheme> securitySchemes(){List<SecurityScheme> apiKeyList = new ArrayList<SecurityScheme>();apiKeyList.add(new ApiKey("Authorization", "Authorization", In.HEADER.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 authorizationScope = new AuthorizationScope("global", "accessEverything");AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];authorizationScopes[0] = authorizationScope;List<SecurityReference> securityReferences = new ArrayList<>();securityReferences.add(new SecurityReference("Authorization", authorizationScopes));return securityReferences;}

在swagger右上角有一个 Authorize 按钮,点击后弹出下面弹框,只需要输入一遍token

五,文件

设置maven国内镜像,配置maven环境变量,添加exclusions去掉多余的依赖,生成pdf成功,解决中文乱码问题,原因在于原有jar包中的字体文件对中文支持不友好,加入新的字体文件即可。
生成pdf文件,解决中文丢失
adoc-html-pdf

1,配置依赖

         <dependency><groupId>io.github.swagger2markup</groupId><artifactId>swagger2markup</artifactId><version>1.3.1</version><exclusions><exclusion><groupId>nl.jworks.markdown_to_asciidoc</groupId><artifactId>markdown_to_asciidoc</artifactId></exclusion><exclusion><groupId>ch.netzwerg</groupId><artifactId>paleo-core</artifactId></exclusion></exclusions></dependency>

2,添加插件,放在pom中build-plugins标签内

  <!--此插件生成ASCIIDOC--><plugin><groupId>io.github.swagger2markup</groupId><artifactId>swagger2markup-maven-plugin</artifactId><version>1.2.0</version><configuration><!--此处端口一定要是当前项目启动所用的端口--><swaggerInput>http://localhost:8084/</swaggerInput><outputDir>src/docs/asciidoc/generated</outputDir><config><!-- 除了ASCIIDOC之外,还有MARKDOWN和CONFLUENCE_MARKUP可选 --><swagger2markup.markupLanguage>ASCIIDOC</swagger2markup.markupLanguage></config></configuration></plugin><!--此插件生成HTML和PDF--><plugin><groupId>org.asciidoctor</groupId><artifactId>asciidoctor-maven-plugin</artifactId><version>1.5.3</version><!-- Include Asciidoctor PDF for pdf generation --><dependencies><dependency><groupId>org.asciidoctor</groupId><artifactId>asciidoctorj-pdf</artifactId><version>1.5.0-alpha.16</version></dependency><dependency><groupId>org.jruby</groupId><artifactId>jruby-complete</artifactId><version>1.7.24</version></dependency></dependencies><!-- Configure generic document generation settings --><configuration><sourceDirectory>src/docs/asciidoc/generated</sourceDirectory><sourceHighlighter>coderay</sourceHighlighter><attributes><toc>left</toc></attributes></configuration><!-- Since each execution can only handle one backend, runseparate executions for each desired output type --><executions><execution><id>output-html</id><phase>generate-resources</phase><goals><goal>process-asciidoc</goal></goals><configuration><backend>html5</backend><outputDirectory>src/docs/asciidoc/html</outputDirectory></configuration></execution><execution><id>output-pdf</id><phase>generate-resources</phase><goals><goal>process-asciidoc</goal></goals><configuration><backend>pdf</backend><outputDirectory>src/docs/asciidoc/pdf</outputDirectory></configuration></execution></executions></plugin><plugin><groupId>org.asciidoctor</groupId><artifactId>asciidoctor-maven-plugin</artifactId><version>1.5.6</version></plugin>

3,新建测试类,并运行生成相关文件

@RunWith(SpringRunner.class)
@SpringBootTest
public class PdfTest {@Testpublic void generateAsciiDocs() throws Exception {// 输出Ascii格式Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withMarkupLanguage(MarkupLanguage.ASCIIDOC).withOutputLanguage(Language.ZH).withPathsGroupedBy(GroupBy.TAGS).withGeneratedExamples().withoutInlineSchema().build();Swagger2MarkupConverter.from(new URL("http://localhost:8080/v2/api-docs?group=xmliu")).withConfig(config).build().toFolder(Paths.get("src/docs/asciidoc/generated"));}}

4,中文乱码或丢失问题

核心思路就是替换字体,原因就是asciidoctorj-pdf对中文支持不友好

(1)首先找到这个jar

(2)用压缩软件打开这个jar,到如下目录,

(3)先加入不同类型的字体文件,比如粗体、斜体等,一共四种

字体文件如果没有合适的可从这里下载,https://download.csdn.net/download/diyangxia/19266310

(4)再修改themes中的配置文件default-themes.yml中字体指向即可

font:catalog:# Noto Serif supports Latin, Latin-1 Supplement, Latin Extended-A, Greek, Cyrillic, Vietnamese & an assortment of symbolsNoto Serif:normal: KaiGenGothicCN-Regular.ttfbold: KaiGenGothicCN-Bold.ttfitalic: KaiGenGothicCN-Regular-Italic.ttfbold_italic: KaiGenGothicCN-Bold-Italic.ttf

5,执行命令

mvn asciidoctor:process-asciidoc
mvn generate-resources

六,参考文档

Swagger2导出Html和pdf文件

swagger2导出html文档和pdf文档(解决pdf中文乱码与显示不全问题)

springboot项目集成 swagger2, 并生成离线html和pdf文档(已解决pdf中文乱码问题)

SWAGGER+ASCIIDOCTOR 导出PDF中文缺失乱码问题解决

七,Github

https://github.com/xmliu/swaggerDemo

knife4j 增强型swagger

https://gitee.com/xiaoym/knife4j

在线预览

Swagger2生成在线接口文档并导出pdf文件相关推荐

  1. SpringBoot集成swagger生成在线接口文档

    SpringBoot集成swagger生成在线接口文档 集成maven依赖 <dependency><groupId>io.springfox</groupId>& ...

  2. 基于 apidoc 生成在线接口文档 (实时更新)(linux系统)

    基于 apidoc 生成在线接口文档 (实时更新)(linux系统) 动态加载,热部署 背景: 规范开发人员的接口文档 文档统一管理,防止本地文档版本不统一 远程部署,保证文档的统一性 主要还是解决, ...

  3. vvv在线文档导出工具_使用ApiPost工具快速生成在线接口文档

    ApiPost是一个支持团队协作,并可直接生成文档的API调试.管理工具.它支持模拟POST.GET.PUT等常见请求,是后台接口开发者或前端.接口测试人员不可多得的工具 .使用者不仅可以利用apio ...

  4. SpringBoot 使用Swagger2打造在线接口文档(附源代码)

    点击上方"好好学java",选择"置顶公众号" 优秀学习资源.干货第一时间送达! 精彩内容 java实战练习项目教程 2018微服务资源springboot.s ...

  5. SpringBoot集成Swagger2生成API接口文档

    SpringBoot2.3.0集成Swagger2 引入Swagger2相应的依赖 入门示例 SpringBoot2集成Swagger2后启动报错 结语 背景:最近在工作中发现,已经多次发现后台开发人 ...

  6. 项目配置Swagger2生成API接口文档

    一.Swagger2介绍 前后端分离开发模式中,api文档是最好的沟通方式. Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务. 及时性 (接 ...

  7. 用apidoc 生成在线接口文档

    在开发接口的过程中,需要向外发布相应的接口文档.开始的时候使用word来写文档,时间长了发现有几个问题.1) 编写不方便.每次新增借口的时候都要复制上一个接口,然后再进行修改,一些相同的部分无法复用, ...

  8. 014-Axios Ajax:前后端分离概述,发送json类型的参数,前后端分离开发:在线接口文档,前端工程化、Element、nginx

    第一节 Ajax概述 1.概述 概念: Asynchronous JavaScript And XML,异步的JavaScript和XML. 作用: 数据交换:通过Ajax可以给服务器发送请求,并获取 ...

  9. Swagger+Spring mvc生成Restful接口文档

    2019独角兽企业重金招聘Python工程师标准>>> Swagger 是一个规范和完整的框架,用于生成.描述.调用和可视化 RESTful 风格的 Web 服务.总体目标是使客户端 ...

最新文章

  1. 通关制单机器人_2020关务节|“数字供应链与智能通关”论坛——如何打造云上跨境贸易生态圈...
  2. ClewareControl 2.4 发布,传感器控制程序,增加对 python 的支持
  3. python读文件每一行、并把这行替换-Python按行读文件
  4. Mysql双向同步复制
  5. 【Python基础入门系列】第05天:Python函数
  6. Windows服务器管理(3)——IIS服务器误删了Default Web Site 网站 解决方法
  7. 计算机终止程序按钮,怎样在VisualBasic中终止计算机系统呢?
  8. QTableWidget动态添加QComboBox并获取表格单元的Widget类型
  9. 图像处理四:霍夫变换
  10. elsevier中elsarticle模板如何使用apa引用格式
  11. B端产品经理知识框架
  12. 转换到coff期间_fatal error LNK1123: 转换到 COFF 期间失败: 文件无效或损坏 | Lellansin's 冰森...
  13. HDU 3533 Escape(BFS)
  14. gitter 卸载_最佳Gitter渠道:材料设计
  15. HTML 鼠标放上显示悬浮窗口
  16. python path包的使用详解
  17. 了解线性分组码的编码原理并编程实现C语言,线性分组码的编译码(DOC).doc
  18. 学习yum info命令
  19. 使用Typescript实现依赖注入(DI)
  20. 8086微型计算机原理答案,8086微型计算机原理与应用(吴宁)习题答案(第二章)

热门文章

  1. sip 协议注册流程
  2. 关于SpringMVC运行项目时出现404错误
  3. 前端技术学习:语义化
  4. linux软件保护,国产Linux违反《计算机软件保护条例》的说明
  5. 【图像处理】自动白平衡(AWB)
  6. 时空大数据与智慧城市
  7. 网络舆情分析关键词怎么获取的系统平台方法
  8. 怎么释放C盘空间?清理C盘空间的4大方法分享!
  9. python的星空绘制教程_星空系列教程-《教你绘制梵高的星空》
  10. 安卓手机并没有“校准电池”的方式