当前位置: 首页 > news >正文

sping boot 基于 RESTful 风格,模拟增删改查操作

RESTful -> 
增:post  
删:delete 
改:  put
查:  get
RESTful 资源路径,一般以 s 复数结尾  

以下是代码示例:

package com.example.springboot.controller;import org.springframework.web.bind.annotation.*;@RestController
public class Hello {@RequestMapping("/hellos")//设置浏览器访问路径public String hello(){System.out.println("完成查询操作");return "模拟返回查询结果";}@RequestMapping(value = "/hellos",method = RequestMethod.POST)public void post(){System.out.println("完成新增操作");}@RequestMapping(value = "/hellos/{id}",method = RequestMethod.PUT)public void updateByID(@PathVariable Integer id){System.out.println("根据id修改记录,当前id为:"+id);}@RequestMapping(value = "/hellos/{id}",method = RequestMethod.DELETE)public void deleteByID(@PathVariable Integer id){System.out.println("根据id删除记录,当前id为:"+id);}}

使用 postman 发送对应请求

四个请求分别是:

get: localhost:8080/hellos

post: localhost:8080/hellos

put: localhost:8080/hellos/1

delete: localhost:8080/hellos/1

四个请求都发送后,运行结果:

2024-09-07T22:22:14.577+08:00  INFO 7396 --- [springboot] [nio-8080-exec-2] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-09-07T22:22:14.578+08:00  INFO 7396 --- [springboot] [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2024-09-07T22:22:14.581+08:00  INFO 7396 --- [springboot] [nio-8080-exec-2] o.s.web.servlet.DispatcherServlet        : Completed initialization in 2 ms
完成查询操作
完成新增操作
根据id修改记录,当前id为:1
根据id删除记录,当前id为:1

对应大量重复的注解,我们可以对其进行改造,使其可读性更好

package com.example.springboot.controller;import org.springframework.web.bind.annotation.*;@RestController
@RequestMapping("/hellos")//改造1
public class Hello {@GetMapping//改造1public String hello(){System.out.println("完成查询操作");return "模拟返回查询结果";}@PostMapping//改造2public void post(){System.out.println("完成新增操作");}@PutMapping("/{id}")//改造3public void updateByID(@PathVariable Integer id){System.out.println("根据id修改记录,当前id为:"+id);}@DeleteMapping("/{id}")//改造4public void deleteByID(@PathVariable Integer id){System.out.println("根据id删除记录,当前id为:"+id);}}


http://www.mrgr.cn/news/21817.html

相关文章:

  • ue5 伤害插件
  • springboot websocket 服务端
  • HarmonyOS】ArkTS学习之基于TextTimer的简易计时器的elapsedTime最小时间单位问题
  • Java项目: 基于SpringBoot+mybatis+maven网上租贸系统(含源码+数据库+毕业论文)
  • Computer Exercise
  • idea插件开发的第二天-写一个时间查看器
  • VMware时提示系统尚未修改安装失败
  • android系统源码12 修改默认桌面壁纸--SRO方式
  • 【AcWing】852. spfa判断负环
  • Cortex-A7:ARM官方推荐的嵌套中断实现机制
  • GitHub每日最火火火项目(9.7)
  • 二、Maven工程的创建--JavaSEJavaEE
  • Kafka 分布式消息系统详细介绍
  • Android之外部存储可以访问哪些文件夹
  • SpringBoot开发——整合JDBC
  • 自定义view中常用到哪些方法作用分别是什么
  • web登录校验
  • YOLOv8改进 | Conv篇 | YOLOv8引入DWR
  • 改写二进制文件
  • The One You Love 你爱的那个人