Swagger2离线文档:PDF和Html5格式

 

Swagger2在线文档

(内容为原网站转发,最后执行的效果.生成了pdf 和html.但是点击pdf/html没有看到文档而是去了csdn首页还望好心人看到这篇文章以后配置成功加以教导)

原网站链接:https://blog.csdn.net/fly910905/article/details/79131755

0.程序结构

1.Maven配置

 
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <project xmlns="http://maven.apache.org/POM/4.0.0"

  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  5. <modelVersion>4.0.0</modelVersion>

  6.  
  7. <groupId>com.swagger.offline</groupId>

  8. <artifactId>SwaggerOfflineDoc</artifactId>

  9. <version>1.0-SNAPSHOT</version>

  10.  
  11. <parent>

  12. <groupId>org.springframework.boot</groupId>

  13. <artifactId>spring-boot-starter-parent</artifactId>

  14. <version>1.5.2.RELEASE</version>

  15. </parent>

  16.  
  17. <properties>

  18. <snippetsDirectory>${project.build.directory}/generated-snippets</snippetsDirectory>

  19.  
  20. <asciidoctor.input.directory>${project.basedir}/docs/asciidoc</asciidoctor.input.directory>

  21. <generated.asciidoc.directory>${project.build.directory}/asciidoc</generated.asciidoc.directory>

  22. <asciidoctor.html.output.directory>${project.build.directory}/asciidoc/html</asciidoctor.html.output.directory>

  23. <asciidoctor.pdf.output.directory>${project.build.directory}/asciidoc/pdf</asciidoctor.pdf.output.directory>

  24.  
  25. </properties>

  26.  
  27. <dependencies>

  28.  
  29. <dependency>

  30. <groupId>com.alibaba</groupId>

  31. <artifactId>fastjson</artifactId>

  32. <version>1.2.8</version>

  33. </dependency>

  34.  
  35. <!--WEB层-->

  36. <dependency>

  37. <groupId>org.springframework.boot</groupId>

  38. <artifactId>spring-boot-starter-web</artifactId>

  39. </dependency>

  40. <!--测试-->

  41. <dependency>

  42. <groupId>org.springframework.boot</groupId>

  43. <artifactId>spring-boot-starter-test</artifactId>

  44. </dependency>

  45. <!--Swagger2-->

  46. <!--在线文档-->

  47. <!--swagger本身不支持spring mvc的,springfox把swagger包装了一下,让他可以支持springmvc-->

  48. <dependency>

  49. <groupId>io.springfox</groupId>

  50. <artifactId>springfox-swagger2</artifactId>

  51. <version>2.6.1</version>

  52. </dependency>

  53. <dependency>

  54. <groupId>io.springfox</groupId>

  55. <artifactId>springfox-swagger-ui</artifactId>

  56. <version>2.6.1</version>

  57. </dependency>

  58. <!--离线文档-->

  59. <dependency>

  60. <groupId>org.springframework.restdocs</groupId>

  61. <artifactId>spring-restdocs-mockmvc</artifactId>

  62. <version>1.1.2.RELEASE</version>

  63. <scope>test</scope>

  64. </dependency>

  65. <!--springfox-staticdocs 生成静态文档-->

  66. <dependency>

  67. <groupId>io.springfox</groupId>

  68. <artifactId>springfox-staticdocs</artifactId>

  69. <version>2.6.1</version>

  70. </dependency>

  71. </dependencies>

  72.  
  73. <build>

  74. <finalName>SwaggerOfflineDoc</finalName>

  75. <plugins>

  76. <!--<plugin>

  77. <groupId>org.springframework.boot</groupId>

  78. <artifactId>spring-boot-maven-plugin</artifactId>

  79. </plugin>-->

  80. <!--Maven通过Maven Surefire Plugin插件执行单元测试-->

  81. <plugin>

  82. <groupId>org.apache.maven.plugins</groupId>

  83. <artifactId>maven-surefire-plugin</artifactId>

  84. </plugin>

  85. <!-- Run the generated asciidoc through Asciidoctor to generate

  86. other documentation types, such as PDFs or HTML5 -->

  87. <!--通过Asciidoctor使得asciidoc生成其他的文档格式,例如:PDF 或者HTML5-->

  88. <plugin>

  89. <groupId>org.asciidoctor</groupId>

  90. <artifactId>asciidoctor-maven-plugin</artifactId>

  91. <version>1.5.3</version>

  92. <!-- Include Asciidoctor PDF for pdf generation -->

  93. <!--生成PDF-->

  94. <dependencies>

  95. <dependency>

  96. <groupId>org.asciidoctor</groupId>

  97. <artifactId>asciidoctorj-pdf</artifactId>

  98. <version>1.5.0-alpha.14</version>

  99. </dependency>

  100. <!-- Comment this section to use the default jruby artifact provided by the plugin -->

  101. <dependency>

  102. <groupId>org.jruby</groupId>

  103. <artifactId>jruby-complete</artifactId>

  104. <version>1.7.21</version>

  105. </dependency>

  106. </dependencies>

  107.  
  108. <!-- Configure generic document generation settings -->

  109. <!--文档生成配置-->

  110. <configuration>

  111. <sourceDirectory>${asciidoctor.input.directory}</sourceDirectory>

  112. <sourceDocumentName>index.adoc</sourceDocumentName>

  113. <attributes>

  114. <doctype>book</doctype>

  115. <toc>left</toc>

  116. <toclevels>3</toclevels>

  117. <numbered></numbered>

  118. <hardbreaks></hardbreaks>

  119. <sectlinks></sectlinks>

  120. <sectanchors></sectanchors>

  121. <generated>${generated.asciidoc.directory}</generated>

  122. </attributes>

  123. </configuration>

  124. <!-- Since each execution can only handle one backend, run

  125. separate executions for each desired output type -->

  126. <!--因为每次执行只能处理一个后端,所以对于每个想要的输出类型,都是独立分开执行-->

  127. <executions>

  128. <!--html5-->

  129. <execution>

  130. <id>output-html</id>

  131. <phase>test</phase>

  132. <goals>

  133. <goal>process-asciidoc</goal>

  134. </goals>

  135. <configuration>

  136. <backend>html5</backend>

  137. <outputDirectory>${asciidoctor.html.output.directory}</outputDirectory>

  138. </configuration>

  139. </execution>

  140. <!--pdf-->

  141. <execution>

  142. <id>output-pdf</id>

  143. <phase>test</phase>

  144. <goals>

  145. <goal>process-asciidoc</goal>

  146. </goals>

  147. <configuration>

  148. <backend>pdf</backend>

  149. <outputDirectory>${asciidoctor.pdf.output.directory}</outputDirectory>

  150. </configuration>

  151. </execution>

  152. </executions>

  153. </plugin>

  154. </plugins>

  155. </build>

  156.  
  157.  
  158. </project>

2.index.adoc

  • 路径:项目名/docs/asciidoc/index.adoc
 
  1. include::{generated}/overview.adoc[]

  2. include::{generated}/definitions.adoc[]

  3. include::{generated}/paths.adoc[]

3.Swagger2配置

 
  1. package com.swagger.offline.config;

  2.  
  3. import org.springframework.context.annotation.Bean;

  4. import org.springframework.context.annotation.Configuration;

  5. import springfox.documentation.builders.ApiInfoBuilder;

  6. import springfox.documentation.builders.PathSelectors;

  7. import springfox.documentation.builders.RequestHandlerSelectors;

  8. import springfox.documentation.service.ApiInfo;

  9. import springfox.documentation.spi.DocumentationType;

  10. import springfox.documentation.spring.web.plugins.Docket;

  11. import springfox.documentation.swagger2.annotations.EnableSwagger2;

  12.  
  13.  
  14. /**

  15. * @version V1.0

  16. * @Title: Swagger配置类

  17. * @ClassName: com.newcapec.config.swagger.Swagger2Configuration.java

  18. * @Description:

  19. * @Copyright 2016-2017 - Powered By 研发中心

  20. * @author: 王延飞

  21. * @date:2017-12-11 8:20

  22. */

  23.  
  24. @Configuration

  25. @EnableSwagger2

  26. public class SwaggerConfiguration {

  27. @Bean

  28. public Docket buildDocket() {

  29. return new Docket(DocumentationType.SWAGGER_2)

  30. .apiInfo(buildApiInfo())

  31. .select()

  32. //要扫描的API(Controller)基础包

  33. .apis(RequestHandlerSelectors.basePackage("com.swagger.offline.controller"))

  34. .paths(PathSelectors.any())

  35. .build();

  36. }

  37.  
  38. /**

  39. * @param

  40. * @return springfox.documentation.service.ApiInfo

  41. * @Title: 构建API基本信息

  42. * @methodName: buildApiInfo

  43. * @Description:

  44. * @author: 王延飞

  45. * @date: 2017-12-11 8:44

  46. */

  47. private ApiInfo buildApiInfo() {

  48.  
  49. return new ApiInfoBuilder()

  50. .title("用户信息API文档")

  51. .description("这里除了查看接口功能外,还提供了调试测试功能")

  52. .contact("王延飞")

  53. .version("1.0")

  54. .build();

  55.  
  56. }

  57. }

4.实体类

 
  1. import io.swagger.annotations.ApiModel;

  2. import io.swagger.annotations.ApiModelProperty;

  3.  
  4. @ApiModel(value = "User", description = "用户信息描述")

  5. public class User {

  6. /**

  7. * 学号

  8. */

  9. @ApiModelProperty("证件号")

  10. private int id;

  11. /**

  12. * 姓名

  13. */

  14. @ApiModelProperty("姓名")

  15. private String name;

  16. /**

  17. * 年龄

  18. */

  19. @ApiModelProperty("年龄")

  20. private int age;

  21. /**

  22. * 性别

  23. */

  24. @ApiModelProperty("性别")

  25. private String sex;

  26. /**

  27. * 住址

  28. */

  29. @ApiModelProperty("家庭住址")

  30. private String address;

  31. public int getId() {

  32. return id;

  33. }

  34. public void setId(int id) {

  35. this.id = id;

  36. }

  37. public String getName() {

  38. return name;

  39. }

  40. public void setName(String name) {

  41. this.name = name;

  42. }

  43. public int getAge() {

  44. return age;

  45. }

  46. public void setAge(int age) {

  47. this.age = age;

  48. }

  49. public String getSex() {

  50. return sex;

  51. }

  52. public void setSex(String sex) {

  53. this.sex = sex;

  54. }

  55. public String getAddress() {

  56. return address;

  57. }

  58. public void setAddress(String address) {

  59. this.address = address;

  60. }

  61. @Override

  62. public String toString() {

  63. return "User{" +

  64. "id=" + id +

  65. ", name='" + name + '\'' +

  66. ", age=" + age +

  67. ", sex='" + sex + '\'' +

  68. ", address='" + address + '\'' +

  69. '}';

  70. }

  71. }

5.Controller

 

 
  1. import io.swagger.annotations.Api;

  2. import io.swagger.annotations.ApiOperation;

  3. import org.springframework.http.MediaType;

  4. import org.springframework.stereotype.Controller;

  5. import org.springframework.web.bind.annotation.*;

  6. /**

  7. * @Title:

  8. * @ClassName: UserController.java

  9. * @Description:

  10. *

  11. * @Copyright 2016-2018 - Powered By 研发中心

  12. * @author: 王延飞

  13. * @date: 2018-01-22 16:08

  14. * @version V1.0

  15. */

  16. @Controller

  17. @RequestMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE)

  18. @Api(value = "用户信息查询", description = "用户基本信息操作API", tags = "UserApi", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)

  19. public class UserController {

  20. @ApiOperation(value = "/getUser", notes = "根据姓名查询用户信息")

  21. @RequestMapping(value = "getUser", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)

  22. @ResponseBody

  23. public User getUser(@RequestParam("name") String name){

  24. User user = new User();

  25. user.setId(123456);

  26. user.setName(name);

  27. user.setAge(25);

  28. user.setAddress("河南郑州");

  29. user.setSex("男");

  30. return user;

  31. }

  32. @ApiOperation(value = "/addUser", notes = "添加一个用户")

  33. @RequestMapping(value = "addUser", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)

  34. @ResponseBody

  35. public User addUser(@RequestBody User user){

  36. return user;

  37. }

  38. }

6.测试类

 
  1. import com.alibaba.fastjson.JSON;

  2. import io.github.robwin.markup.builder.MarkupLanguage;

  3. import io.github.robwin.swagger2markup.GroupBy;

  4. import io.github.robwin.swagger2markup.Swagger2MarkupConverter;

  5. import org.junit.After;

  6. import org.junit.Test;

  7. import org.junit.runner.RunWith;

  8. import org.springframework.beans.factory.annotation.Autowired;

  9. import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs;

  10. import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;

  11. import org.springframework.boot.test.context.SpringBootTest;

  12. import org.springframework.http.MediaType;

  13. import org.springframework.restdocs.mockmvc.MockMvcRestDocumentation;

  14. import org.springframework.test.context.junit4.SpringRunner;

  15. import org.springframework.test.web.servlet.MockMvc;

  16. import springfox.documentation.staticdocs.SwaggerResultHandler;

  17. import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.get;

  18. import static org.springframework.restdocs.mockmvc.RestDocumentationRequestBuilders.post;

  19. import static org.springframework.restdocs.operation.preprocess.Preprocessors.preprocessResponse;

  20. import static org.springframework.restdocs.operation.preprocess.Preprocessors.prettyPrint;

  21. import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

  22. /**

  23. * @Title:

  24. * @ClassName: SwaggerStaticDocTest.java

  25. * @Description:

  26. *

  27. * @Copyright 2016-2018 - Powered By 研发中心

  28. * @author: 王延飞

  29. * @date: 2018-01-22 16:06

  30. * @version V1.0

  31. */

  32. @AutoConfigureMockMvc

  33. @AutoConfigureRestDocs(outputDir = "target/generated-snippets")

  34. @RunWith(SpringRunner.class)

  35. @SpringBootTest

  36. public class SwaggerStaticDocTest {

  37. private String snippetDir = "target/generated-snippets";

  38. private String outputDir = "target/asciidoc";

  39. @Autowired

  40. private MockMvc mockMvc;

  41. @After

  42. public void Test() throws Exception {

  43. // 得到swagger.json,写入outputDir目录中

  44. mockMvc.perform(get("/v2/api-docs").accept(MediaType.APPLICATION_JSON))

  45. .andDo(SwaggerResultHandler.outputDirectory(outputDir).build())

  46. .andExpect(status().isOk())

  47. .andReturn();

  48. // 读取上一步生成的swagger.json转成asciiDoc,写入到outputDir

  49. // 这个outputDir必须和插件里面<generated></generated>标签配置一致

  50. Swagger2MarkupConverter.from(outputDir + "/swagger.json")

  51. .withPathsGroupedBy(GroupBy.TAGS)// 按tag排序

  52. .withMarkupLanguage(MarkupLanguage.ASCIIDOC)// 格式

  53. .withExamples(snippetDir)

  54. .build()

  55. .intoFolder(outputDir);// 输出

  56. }

  57. @Test

  58. public void TestApi() throws Exception {

  59. mockMvc.perform(get("/user/getUser").param("name", "FLY")

  60. .accept(MediaType.APPLICATION_JSON))

  61. .andExpect(status().isOk())

  62. .andDo(MockMvcRestDocumentation.document("getUser", preprocessResponse(prettyPrint())));

  63. User user = new User();

  64. user.setId(123456);

  65. user.setName("FLY");

  66. user.setAge(25);

  67. user.setAddress("河南郑州");

  68. user.setSex("男");

  69. mockMvc.perform(post("/user/addUser").contentType(MediaType.APPLICATION_JSON)

  70. .content(JSON.toJSONString(user))

  71. .accept(MediaType.APPLICATION_JSON))

  72. .andExpect(status().is2xxSuccessful())

  73. .andDo(MockMvcRestDocumentation.document("addUser", preprocessResponse(prettyPrint())));

  74. }

  75. }

 

7.测试

mvn clean test
生成的PDF和HTML文件:target/asciidoc/html and target/asciidoc/pdf

html格式

pdf格式

猜你喜欢

转载自blog.csdn.net/qq_35568099/article/details/83786787