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

news2024/9/20 14:47:03

环境介绍

技术栈

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)

用例

@RestController

public class RestControllerDemo {

    @Resource
    private StaffService service;
    /**
     * @PathVariable:获取url中的数据
     *  value :路径变量名
     *  位置: 放在控制器方法的形参前面
     *  {id}定义路径变量
     */
    @GetMapping("/Info/{id}")
    public String getInfo(@PathVariable("id") int id){
        //根据id查询信息
        Staff staff = service.selectById(id);
        return staff.getId()+staff.getName();
    }
    @PostMapping("/create/Staff/{id}/{name}")
    public String createStaff(@PathVariable("id") int id,@PathVariable String name){
        //执行sql----
        return "获得到数据:"+id+" : "+name;
    }
    @PutMapping("/modifyStaff/{id}/{name}")
    public String modifyStaff(@PathVariable("id") int id,@PathVariable String name){
        //执行sql语句 UPDATE staff SET name=#{name}  WHERE  id=#{id}
    return "更新了:"+id+" : "+name;
    }
    @DeleteMapping("/Delete/{id}")
    public String DelStaff(@PathVariable("id") int id){
        //执行sql语句 UPDATE staff SET name=#{name}  WHERE  id=#{id}
        return "id为"+id+"的用户被删除了";
    }

}

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

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

Springboot框架启用HiddenHttpMethodFilter

application.properties配置

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

Html页面

Put

<form action="/boot/modifyStaff/003/张三" method="post">
    <input type="hidden" name="_method" value="put">
    <input type="submit" value="提交">
</form>
Delete
<form action="/boot/Delete/001" method="post">
    <input type="hidden" name="_method" value="delete">
    <input type="submit" value="提交">
</form>

Controller

RUL:地址必须唯一

@PutMapping("/modifyStaff/{id}/{name}")

public String modifyStaff(@PathVariable("id") int id,@PathVariable String name){

    //执行sql语句 UPDATE staff SET name=#{name}  WHERE  id=#{id}

return "更新了:"+id+" : "+name;

}
@DeleteMapping("/Delete/{id}")

public String DelStaff(@PathVariable("id") int id){
    //执行sql语句 DELETE

    return "id为"+id+"的用户被删除了";

}

@RestController注解

@Controller与@ResponseBody的组合

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

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

Springboot2.7集成Swagger2.9.2

pom.xml

<dependencies>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger2</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-swagger-ui</artifactId>
        <version>2.9.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.5.4.1</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>com.mysql</groupId>
        <artifactId>mysql-connector-j</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.oracle.database.jdbc</groupId>
        <artifactId>ojdbc8</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.1.14</version>
    </dependency>
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>dynamic-datasource-spring-boot-starter</artifactId>
        <version>3.5.0</version>
    </dependency>
    <dependency>
        <groupId>p6spy</groupId>
        <artifactId>p6spy</artifactId>
        <version>3.9.1</version>
    </dependency>
</dependencies>

application.yml

hxiot:
  swagger2:
    # 是否开启swagger2 开启为true,关闭为false
    enable: true

management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    prometheus:
      enabled: true
    health:
      show-details: always
  metrics:
    export:
      prometheus:
        enabled: true
server:
  port: 8007

spring:
  mvc:
    path match:
      matching-strategy: ant_path_matcher
  profiles:
    active: dev

  application:
    name: ProvideAPIServices
  datasource:
    dynamic:
      primary: sys2 #设置默认的数据源或者数据源组,默认值即为master
      strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源
      datasource:
        oracle:
          username: system
          password: pwd
          url: jdbc:oracle:thin:@0.0.0.0:1521:orcl
          driver-class-name: oracle.jdbc.driver.OracleDriver
#          driver-class-name: com.mysql.jdbc.Driver
        wms:
          url: jdbc:p6spy:mysql://0.0.0.0:3306/Wms?useUnicode=true&characterEncoding=UTF-8
          username: root
          password: pwd
          driver-class-name: com.p6spy.engine.spy.P6SpyDriver
#          driver-class-name: com.mysql.jdbc.Driver
        sys2:
          username: root
          password: pwd
          url: jdbc:p6spy:mysql://127.0.0.1:3306/sys?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8
          driver-class-name: com.p6spy.engine.spy.P6SpyDriver
mybatis-plus:
  configuration:
    #输出日志
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    #配置映射规则
    map-underscore-to-camel-case: true #表示支持下划线到驼蜂的映射
    #隐藏mybatis图标
  global-config:
    banner: false
    db-config:
      logic-delete-field: status
      logic-not-delete-value: 1
      logic-delete-value: 0
#
#mybatis:
#  mapper-locations=classpath: com/example/dao/*.xml

demoController

 Controller需符合REST风格

@Api(value = "ApiTest")
@RestController("/demo")
public class demoController {
    @Autowired
    private TAddressServiceImpl tAddressService;

    @ApiOperation(value = "测试")
    @GetMapping("/test")
    public List<TAddress> setTAddressService() {
        return tAddressService.list();
    }

    @ApiOperation(value = "上传文件")
    @PutMapping("/upload")
    //FileUploadDemo
    public void fileUp(@ApiParam("文件") MultipartFile file, HttpServletRequest request) throws IOException {
        //获取文件名称
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
        //获取web服务器运行目录
        String currentPath = request.getServletContext().getRealPath("/upload/");
        System.out.println(currentPath);
        saveFile(file,currentPath);
        System.out.println("ok");
    }

    public void saveFile(MultipartFile file,String path) throws IOException {

        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File newFile = new File(path+file.getOriginalFilename());
        file.transferTo(newFile);
    }

}

Configuration

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * Docket
     */
    @Bean
    public Docket createRestAPi() {
        // 构造函数传入初始化规范,这是swagger2规范
        return new Docket(DocumentationType.SWAGGER_2)
                //.pathMapping("/")
                // apiInfo:添加api的详情信息,参数为ApiInfo类型的参数,这个参数包含了基本描述信息:比如标题、描述、版本之类的,开发中一般都是自定义这些信息
                .apiInfo(apiInfo())
                // select、apis、paths、build 这四个是一组的,组合使用才能返回一个Docket实例对象,其中apis和paths是可选的。
                .select()
                // apis:添加过滤条件。RequestHandlerSelectors中有很多过滤方式;RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class):加了ApiOperation注解的类,生成接口文档
                //扫描com.qgs.controller包下的API交给Swagger2管理
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                // paths:控制那些路径的api会被显示出来。
                //.paths(PathSelecto1rs.any())
                .build()
                // 是否开启swagger 如果是false,浏览器将无法访问,默认是true
                .enable(true);
    }

    /**
     * ApiInfo
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                // 标题内容
                .title("ProvideAPIServicesAPI文档")
                // 描述内容
                .description("接口文档详情信息")
                // 版本
                .version("1.0")
                 联系人信息
                //.contact(new Contact("", "", ""))
                // 许可
                //.license("")
                // 许可链接
                //.licenseUrl("")
                .build();
    }

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降低降低

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【informer】 时间序列的预测学习 2021 AAAI best paper

文章目录 前言1.引入2.数据集训练 前言 数据集 https://github.com/zhouhaoyi/ETDataset/blob/main/README_CN.md 代码&#xff1a;https://github.com/zhouhaoyi/Informer2020#reproducibility 21年的paper:https://arxiv.org/pdf/2012.07436.pdf 论文在代码上有连接&#xf…

Promise 重写 (第一部分)

学习关键语句&#xff1a; promise 重写 写在前面 重新学习了怎么重写 promise &#xff0c; 我觉得最重要的就是要有思路&#xff0c;不然有些 A 规范是完全想不到的 开始 重写函数的过程中, 最重要的是有思路 我们从哪里获取重写思路? 从正常的代码中 我们先看正常的代码…

C语言判断水仙花数(ZZULIOJ1027:判断水仙花数)

题目描述 春天是鲜花的季节&#xff0c;水仙花就是其中最迷人的代表&#xff0c;数学上有个水仙花数&#xff0c;他是这样定义的&#xff1a;“水仙花数”是指一个三位数&#xff0c;它的各位数字的立方和等于其本身&#xff0c;比如153135333。 现在要求输入一个三位数&#…

delete 与 truncate 命令的区别

直接去看原文 原文链接:【SQL】delete 与 truncate 命令的区别_truncate和delete的区别-CSDN博客 -------------------------------------------------------------------------------------------------------------------------------- 1. 相同点 二者都能删除表中的数据…

不敢信,30+岁的项目经理会是这样

大家好&#xff0c;我是老原。 你们知道&#xff0c;每个阶段的项目经理都是什么样的吗&#xff1f; 20多岁时&#xff0c;刚踏入项目管理的你可能是个什么都不懂的职场小白&#xff0c;或者只能在旁边打打下手&#xff1b; 到了30岁&#xff0c;经历了项目的人情冷暖&#…

QT中的鼠标事件

鼠标追踪打开后进去一动就显示

我把微信群聊机器人项目开源

▍PART 序 开源项目地址》InsCode - 让你的灵感立刻落地 目前支持的回复 ["抽签", "天气", "讲笑话", "讲情话", "梦到", "解第", "动漫图", "去水印-", "历史今天", "星座-…

Linux控制---进程程序替换

前言&#xff1a;前面我们学洗了Linux进程退出的相关知识&#xff0c;了解了什么是进程退出&#xff0c;已经进程等待的相关话题&#xff0c;今天&#xff0c;我们来学习Linux中的进程程序替换&#xff0c;进程程序替换在Linux中可以用于实现新程序的启动、程序升级、多进程程序…

k8s-集群升级 2

在每个集群节点都安装部署cir-docker 配置cri-docker 升级master节点 导入镜像到本地并将其上传到仓库 修改节点套接字 升级kubelet 注&#xff1a;先腾空后进行升级&#xff0c;顺序不能搞反&#xff0c;否则会导致严重问题 配置kubelet使用cri-docker 解除节点保护 升级wor…

传统企业如何利用软文营销突破重围

数字经济的发展让企业有了更多发展的可能&#xff0c;通过线下线上齐发展能够助力企业推广品牌&#xff0c;获得不错的销量。传统的线下门店销售在数字化时代下还是有一定的局限性&#xff0c;转型只是时间问题&#xff0c;然而有些企业在面对网络营销的时候却束手无策&#xf…

11.15 知识总结(模板层、模型层)

一、 模板层 1.1 过滤器 1.什么是过滤器&#xff1f; 过滤器类似于python的内置函数&#xff0c;用来把变量值加以修饰后再显示。 2. 语法 1、 {{ 变量名|过滤器名 }} 2、链式调用&#xff1a;上一个过滤器的结果继续被下一个过滤器处理 {{ 变量名|过滤器1|过滤器2 }} 3、有的过…

windows 安装 Oracle Database 19c

目录 什么是 Oracle 数据库 下载 Oracle 数据库 解压文件 运行安装程序 测试连接 什么是 Oracle 数据库 Oracle数据库是由美国Oracle Corporation&#xff08;甲骨文公司&#xff09;开发和提供的一种关系型数据库管理系统&#xff0c;它是一种强大的关系型数据库管理系统…

kubernetes资源管理

资源管理 资源管理介绍 在kubernetes中&#xff0c;所有的内容都抽象为资源&#xff0c;用户需要通过操作资源来管理kubernetes。 kubernetes的本质上就是一个集群系统&#xff0c;用户可以在集群中部署各种服务&#xff0c;所谓的部署服务&#xff0c;其实就是在kubernetes集…

基于Java Web的云端学习系统的设计与实现

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

Prometheus入门与实战

1.Prometheus介绍 1.什么是监控&#xff1f; 从技术角度来看&#xff0c;监控是度量和管理技术系统的工具和过程&#xff0c;但监控也提供从系统和应用程序生成的指标到业务价值的转换。这些指标转换为用户体验的度量&#xff0c;为业务提供反馈&#xff0c;同样还向技术提供反…

记feign调用第三方接口时header是multipart/form-data

1.请求第三方接口&#xff0c;用feign请求 请求第三方接口&#xff0c;用feign请求&#xff0c;header不通&#xff0c;feign的写法不同 调用时报错Could not write request: no suitable HttpMessageConverter found for request type [com.ccreate.cnpc.mall.dto.zm.ZMPage…

现场直击!触想智能亮相德国2023 SPS展会

当地时间11月14日上午9时 2023 年(德国)纽伦堡国际工业自动化及元器件展览会 SPS 展(以下简称&#xff1a;SPS展会)正式拉开帷幕&#xff0c;触想智能与来自全球各地的领先科技公司及前沿业者齐聚盛会&#xff0c;共赴一场科技与创新交汇的“饕餮盛宴”。 △ 2023 SPS展会开幕(…

sCrypt Playground 发布

sCrypt Playground 发布了。 与桌面IDE 完全相同的功能&#xff0c;但是无需安装。体验地址: https://playground.scrypt.io。 请不要在 sCrypt Playground 上存储重要数据。我们会不定时清除用户保存在其上的数据。

海外邮件接收延迟、接收不到怎么办?U-Mail邮件网关来了

随着经济全球化的发展&#xff0c;很多国内企业开始踏足海外市场&#xff0c;电子邮件就成为了国内企业与海外客户沟通交流的主要渠道。然而海外邮件接收延迟、接收不到等问题成为了困扰企业与海外客户沟通的一大阻碍&#xff0c;导致客户邮件回复不及时&#xff0c;询盘邮件接…

Javaweb之Vue的概述

2.1 Vue概述 通过我们学习的htmlcssjs已经能够开发美观的页面了&#xff0c;但是开发的效率还有待提高&#xff0c;那么如何提高呢&#xff1f;我们先来分析下页面的组成。一个完整的html页面包括了视图和数据&#xff0c;数据是通过请求 从后台获取的&#xff0c;那么意味着我…