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

SpringBoot对一个URL通过method(GET、POST、PUT、DELETE)实现增删改查操作

目录

  • 1. rest风格基础
  • 2. 开启方法
  • 3. 实战练习

1. rest风格基础

我们都知道GET、POST、PUT、DELETE分别对应查、增、改、删除

虽然Postman这些工具可以直接发送GET、POST、PUT、DELETE请求。但是@RequestMapping并不支持PUT和DELETE请求操作。需要我们手动开启

2. 开启方法

PUT和DELETE还是通过method=POST进行请求,但是需要添加对应的隐藏域_method=PUT/DELETE

然后配置文件进行参数的配置:spring.mvc.hiddenmethod.filter.enabled=true

3. 实战练习

  1. 添加如下参数到application.properties文件。表示开启隐藏方法使用
spring.mvc.hiddenmethod.filter.enabled=true
  1. 编写Controller。在一个请求路径上,分别定义了GET、POST、PUT、DELETE四种method

其中GetMapping、PostMapping、PutMapping、DeleteMapping等同于@RequestMapping对应的method。如下所示:

package com.hh.springboottest.myController;import org.springframework.web.bind.annotation.*;@RestController
public class HelloController {// @GetMapping("/user")@RequestMapping(value="/user", method = RequestMethod.GET)public String getUser() {return "get user";}// @PostMapping("/user")@RequestMapping(value="/user", method = RequestMethod.POST)public String saveUser() {return "save user";}// @PutMapping("/user")@RequestMapping(value="/user", method = RequestMethod.PUT)public String editUser() {return "edit user";}// @DeleteMapping("/user")@RequestMapping(value="/user", method = RequestMethod.DELETE)public String deleteUser() {return "delete user";}
}
  1. 编写resources/static/index.html页面。PUT和DELETE还是通过method=POST进行请求,但是需要添加对应的隐藏域_method=PUT/DELETE。还支持的一个隐藏域是_method=PATCH
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="UTF-8"><title>test title</title>
</head>
<body><form action="/user" method="get"><input value="rest get提交" type="submit" />
</form>
<form action="/user" method="post"><input value="rest post提交" type="submit" />
</form>
<form action="/user" method="post"><input name="_method" type="hidden" value="PUT" /><input value="rest put提交" type="submit" />
</form>
<form action="/user" method="post"><input name="_method" type="hidden" value="DELETE" /><input value="rest delete提交" type="submit" />
</form></body>
</html>
  1. 然后访问http://localhost:8080/,点击rest get提交。如下所示:
    rest get提交
    得到的结果如下:
    rest get提交结果
http://www.lryc.cn/news/122691.html

相关文章:

  • webpack 创建VUE项目
  • deepin 深度操作系统正式适配苹果 M1 芯片
  • Labview控制APx(Audio Precision)进行测试测量(七)
  • Mybatis 源码 ② :流程分析
  • Unity2D RPG开发笔记 P1 - Unity界面基础操作和知识
  • 聚类与回归
  • 了解IL汇编循环
  • 电脑突然黑屏的解决办法
  • socket练习
  • Gitlab CI/CD笔记-第二天-主机套接字进行构建并push镜像。
  • nginx服务器报错502 Bad Gateway的原因以及解决办法
  • 带你了解什么是内容协商---如何返回不同媒体类型的数据
  • 容器化相关面试题
  • BIO、NIO、AIO 有什么区别
  • 如何构建一个对象池并使用
  • 【沁恒蓝牙mesh】CH58x USB功能开发记录(三)
  • 2023国赛数学建模D题思路分析
  • linux 学习————LNMP之分布式部署
  • 第八课 双重所有格和不定代词
  • 使用xrdp协议远程桌面控制树莓派,无需公网IP!
  • 数据结构【图的类型定义和存储结构】
  • PHP Smarty如何进行调试和错误处理?
  • 手搓vue3组件_0,打包配置
  • WebAssembly
  • TM4C123库函数学习(2)--- LED闪烁,滴答定时器精准延时
  • Linux: network: tcp: back-off技术
  • 36 | 银行贷款数据分析
  • 计算机网络-物理层(二)- 传输方式
  • 超强台风“杜苏芮”来袭!如何实现安全可靠的通信?
  • 内网隧道—HTTP\DNS\ICMP