• 手摸手入门Springboot2.7集成Swagger2.9.2


    环境介绍

    技术栈

    springboot+mybatis-plus+mysql+oracle+Swagger

    软件

    版本

    mysql

    8

    IDEA

    IntelliJ IDEA 2022.2.1

    JDK

    1.8

    Spring Boot

    2.7.13

    mybatis-plus

    3.5.3.2

    REST软件架构风格

    REST即表述性状态传递(英文:Representational State Transfer,简称REST,中文:表示层状态转移)是Roy Fielding博士在2000年他的博士论文中提出来的一种软件架构风格。它是一种针对网络应用的设计和开发方式,可以降低开发的复杂性,提高系统的可伸缩性。

    在三种主流的Web服务实现方案中,因为REST模式的Web服务与复杂的SOAP和XML-RPC对比来讲明显的更加简洁,越来越多的web服务开始采用REST风格设计和实现。例如,Amazon.com提供接近REST风格的Web服务进行图书查找;雅虎提供的Web服务也是REST风格的。

    REST中的要素:用REST表示资源和对资源的操作。在互联网中,表示一个资源或者一个操作。

    资源用URL表示。

    资源:查询资源、创建资源、更新资源、删除资源

    表示层(视图层)状态转移:显示资源,通过视图页面,jsp等。

    状态:资源变化。 转移:资源变化。

    RESTful的注解

    @PathVariable注解:获取url中的数据

    @GetMapping注解

    接收和处理get请求。等同于RequestMapping(method=RequestMethod.GET)

    @PostMapping注解

    接收和处理Post请求。等同于RequestMapping(method=RequestMethod.POST)

    @PutMapping注解, Request method 'POST' and 'GET' not supported

    支持put请求方式。等同于RequestMapping(method=RequestMethod.PUT)

    @DeleteMapping注解 Request method 'POST' and 'GET' not supported

    接收delete方式的请求,等同于RequestMapping(method=RequestMethod.DELETE)

    用例

    1. @RestController
    2. public class RestControllerDemo {
    3. @Resource
    4. private StaffService service;
    5. /**
    6. * @PathVariable:获取url中的数据
    7. * value :路径变量名
    8. * 位置: 放在控制器方法的形参前面
    9. * {id}定义路径变量
    10. */
    11. @GetMapping("/Info/{id}")
    12. public String getInfo(@PathVariable("id") int id){
    13. //根据id查询信息
    14. Staff staff = service.selectById(id);
    15. return staff.getId()+staff.getName();
    16. }
    17. @PostMapping("/create/Staff/{id}/{name}")
    18. public String createStaff(@PathVariable("id") int id,@PathVariable String name){
    19. //执行sql----
    20. return "获得到数据:"+id+" : "+name;
    21. }
    22. @PutMapping("/modifyStaff/{id}/{name}")
    23. public String modifyStaff(@PathVariable("id") int id,@PathVariable String name){
    24. //执行sql语句 UPDATE staff SET name=#{name} WHERE id=#{id}
    25. return "更新了:"+id+" : "+name;
    26. }
    27. @DeleteMapping("/Delete/{id}")
    28. public String DelStaff(@PathVariable("id") int id){
    29. //执行sql语句 UPDATE staff SET name=#{name} WHERE id=#{id}
    30. return "id为"+id+"的用户被删除了";
    31. }
    32. }

    建议使用Postman测试get,post,put,delete

    配置html支持put和delect请求方式。
    HiddenHttpMethodFilter支持将post请求转为put、delete请求

    Springboot框架启用HiddenHttpMethodFilter

    application.properties配置

    1. #启用HiddenHttpMethodFilter过滤器
    2. spring.mvc.hiddenmethod.filter.enabled=true

    Html页面

    1. Put
    2. <form action="/boot/modifyStaff/003/张三" method="post">
    3. <input type="hidden" name="_method" value="put">
    4. <input type="submit" value="提交">
    5. </form>
    6. Delete
    7. <form action="/boot/Delete/001" method="post">
    8. <input type="hidden" name="_method" value="delete">
    9. <input type="submit" value="提交">
    10. </form>

    Controller

    RUL:地址必须唯一

    1. @PutMapping("/modifyStaff/{id}/{name}")
    2. public String modifyStaff(@PathVariable("id") int id,@PathVariable String name){
    3. //执行sql语句 UPDATE staff SET name=#{name} WHERE id=#{id}
    4. return "更新了:"+id+" : "+name;
    5. }
    6. @DeleteMapping("/Delete/{id}")
    7. public String DelStaff(@PathVariable("id") int id){
    8. //执行sql语句 DELETE
    9. return "id为"+id+"的用户被删除了";
    10. }

    @RestController注解

    @Controller与@ResponseBody的组合

    Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTFUL风格的Web服务,是非常流行的API表达工具。

    Swagger能够自动生成完善的 RESTFUL AP文档,,同时并根据后台代码的修改同步更新,同时提供完整的测试页面来调试API。

    Springboot2.7集成Swagger2.9.2

    pom.xml

    1. <dependencies>
    2. <dependency>
    3. <groupId>io.springfox</groupId>
    4. <artifactId>springfox-swagger2</artifactId>
    5. <version>2.9.2</version>
    6. </dependency>
    7. <dependency>
    8. <groupId>io.springfox</groupId>
    9. <artifactId>springfox-swagger-ui</artifactId>
    10. <version>2.9.2</version>
    11. </dependency>
    12. <dependency>
    13. <groupId>org.springframework.boot</groupId>
    14. <artifactId>spring-boot-starter-web</artifactId>
    15. </dependency>
    16. <dependency>
    17. <groupId>com.baomidou</groupId>
    18. <artifactId>mybatis-plus-boot-starter</artifactId>
    19. <version>3.5.4.1</version>
    20. </dependency>
    21. <dependency>
    22. <groupId>org.springframework.boot</groupId>
    23. <artifactId>spring-boot-devtools</artifactId>
    24. <scope>runtime</scope>
    25. <optional>true</optional>
    26. </dependency>
    27. <dependency>
    28. <groupId>com.mysql</groupId>
    29. <artifactId>mysql-connector-j</artifactId>
    30. <scope>runtime</scope>
    31. </dependency>
    32. <dependency>
    33. <groupId>com.oracle.database.jdbc</groupId>
    34. <artifactId>ojdbc8</artifactId>
    35. <scope>runtime</scope>
    36. </dependency>
    37. <dependency>
    38. <groupId>org.springframework.boot</groupId>
    39. <artifactId>spring-boot-configuration-processor</artifactId>
    40. <optional>true</optional>
    41. </dependency>
    42. <dependency>
    43. <groupId>org.projectlombok</groupId>
    44. <artifactId>lombok</artifactId>
    45. <optional>true</optional>
    46. </dependency>
    47. <dependency>
    48. <groupId>org.springframework.boot</groupId>
    49. <artifactId>spring-boot-starter-test</artifactId>
    50. <scope>test</scope>
    51. </dependency>
    52. <dependency>
    53. <groupId>com.alibaba</groupId>
    54. <artifactId>druid-spring-boot-starter</artifactId>
    55. <version>1.1.14</version>
    56. </dependency>
    57. <dependency>
    58. <groupId>com.baomidou</groupId>
    59. <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
    60. <version>3.5.0</version>
    61. </dependency>
    62. <dependency>
    63. <groupId>p6spy</groupId>
    64. <artifactId>p6spy</artifactId>
    65. <version>3.9.1</version>
    66. </dependency>
    67. </dependencies>

    application.yml

    1. hxiot:
    2. swagger2:
    3. # 是否开启swagger2 开启为true,关闭为false
    4. enable: true
    5. management:
    6. endpoints:
    7. web:
    8. exposure:
    9. include: "*"
    10. endpoint:
    11. prometheus:
    12. enabled: true
    13. health:
    14. show-details: always
    15. metrics:
    16. export:
    17. prometheus:
    18. enabled: true
    19. server:
    20. port: 8007
    21. spring:
    22. mvc:
    23. path match:
    24. matching-strategy: ant_path_matcher
    25. profiles:
    26. active: dev
    27. application:
    28. name: ProvideAPIServices
    29. datasource:
    30. dynamic:
    31. primary: sys2 #设置默认的数据源或者数据源组,默认值即为master
    32. strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
    33. datasource:
    34. oracle:
    35. username: system
    36. password: pwd
    37. url: jdbc:oracle:thin:@0.0.0.0:1521:orcl
    38. driver-class-name: oracle.jdbc.driver.OracleDriver
    39. # driver-class-name: com.mysql.jdbc.Driver
    40. wms:
    41. url: jdbc:p6spy:mysql://0.0.0.0:3306/Wms?useUnicode=true&characterEncoding=UTF-8
    42. username: root
    43. password: pwd
    44. driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    45. # driver-class-name: com.mysql.jdbc.Driver
    46. sys2:
    47. username: root
    48. password: pwd
    49. url: jdbc:p6spy:mysql://127.0.0.1:3306/sys?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
    50. driver-class-name: com.p6spy.engine.spy.P6SpyDriver
    51. mybatis-plus:
    52. configuration:
    53. #输出日志
    54. log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    55. #配置映射规则
    56. map-underscore-to-camel-case: true #表示支持下划线到驼蜂的映射
    57. #隐藏mybatis图标
    58. global-config:
    59. banner: false
    60. db-config:
    61. logic-delete-field: status
    62. logic-not-delete-value: 1
    63. logic-delete-value: 0
    64. #
    65. #mybatis:
    66. # mapper-locations=classpath: com/example/dao/*.xml

    demoController

     Controller需符合REST风格

    1. @Api(value = "ApiTest")
    2. @RestController("/demo")
    3. public class demoController {
    4. @Autowired
    5. private TAddressServiceImpl tAddressService;
    6. @ApiOperation(value = "测试")
    7. @GetMapping("/test")
    8. public List setTAddressService() {
    9. return tAddressService.list();
    10. }
    11. @ApiOperation(value = "上传文件")
    12. @PutMapping("/upload")
    13. //FileUploadDemo
    14. public void fileUp(@ApiParam("文件") MultipartFile file, HttpServletRequest request) throws IOException {
    15. //获取文件名称
    16. String originalFilename = file.getOriginalFilename();
    17. System.out.println(originalFilename);
    18. //获取web服务器运行目录
    19. String currentPath = request.getServletContext().getRealPath("/upload/");
    20. System.out.println(currentPath);
    21. saveFile(file,currentPath);
    22. System.out.println("ok");
    23. }
    24. public void saveFile(MultipartFile file,String path) throws IOException {
    25. File dir = new File(path);
    26. if (!dir.exists()) {
    27. dir.mkdirs();
    28. }
    29. File newFile = new File(path+file.getOriginalFilename());
    30. file.transferTo(newFile);
    31. }
    32. }

    Configuration

    1. @Configuration
    2. @EnableSwagger2
    3. public class SwaggerConfig {
    4. /**
    5. * Docket
    6. */
    7. @Bean
    8. public Docket createRestAPi() {
    9. // 构造函数传入初始化规范,这是swagger2规范
    10. return new Docket(DocumentationType.SWAGGER_2)
    11. //.pathMapping("/")
    12. // apiInfo:添加api的详情信息,参数为ApiInfo类型的参数,这个参数包含了基本描述信息:比如标题、描述、版本之类的,开发中一般都是自定义这些信息
    13. .apiInfo(apiInfo())
    14. // select、apis、paths、build 这四个是一组的,组合使用才能返回一个Docket实例对象,其中apis和paths是可选的。
    15. .select()
    16. // apis:添加过滤条件。RequestHandlerSelectors中有很多过滤方式;RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class):加了ApiOperation注解的类,生成接口文档
    17. //扫描com.qgs.controller包下的API交给Swagger2管理
    18. .apis(RequestHandlerSelectors.any())
    19. .paths(PathSelectors.any())
    20. // paths:控制那些路径的api会被显示出来。
    21. //.paths(PathSelecto1rs.any())
    22. .build()
    23. // 是否开启swagger 如果是false,浏览器将无法访问,默认是true
    24. .enable(true);
    25. }
    26. /**
    27. * ApiInfo
    28. */
    29. private ApiInfo apiInfo() {
    30. return new ApiInfoBuilder()
    31. // 标题内容
    32. .title("ProvideAPIServicesAPI文档")
    33. // 描述内容
    34. .description("接口文档详情信息")
    35. // 版本
    36. .version("1.0")
    37. 联系人信息
    38. //.contact(new Contact("", "", ""))
    39. // 许可
    40. //.license("")
    41. // 许可链接
    42. //.licenseUrl("")
    43. .build();
    44. }

    http://192.168.1.8:8007/swagger-ui.html

    可能遇到的问题

    org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

    Springboot2.7与Swagger3.0冲突,将Swagger降低降低

    Springboot2.7与Swagger3.0冲突,将Swagger降低降低

  • 相关阅读:
    深入了解代理服务器:Socks5、IP代理与网络安全
    通过模糊测试寻找车载蓝牙的安全漏洞
    【PostgreSQL启动,停止命令(重启)】
    程序员造轮子:一个基于posix线程库的互斥类(源码)
    Python for循环
    Graalvm-21 Windows初体验
    PYTHON 自动化办公:更改图片后缀
    Mysql 45讲学习笔记(十一)字符串字段怎么加索引
    全面解析缓存应用经典问题
    一款强大的子域名收集工具(OneForAll)
  • 原文地址:https://blog.csdn.net/weixin_47268883/article/details/134430651