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

目录

  • [1. rest风格基础](#1. rest风格基础)
  • [2. 开启方法](#2. 开启方法)
  • [3. 实战练习](#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

  2. 编写Controller。在一个请求路径上,分别定义了GET、POST、PUT、DELETE四种method

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

Java 复制代码
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
Html 复制代码
<!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提交。如下所示:

    得到的结果如下:
相关推荐
TinpeaV3 天前
(JAVA)自建应用调用企业微信API接口,实现消息推送
java·redis·企业微信·springboot·springflux
tanxiaomi5 天前
学习分库分表的前置知识:高可用系统架构理论与实践
java·mysql·spring cloud·系统架构·springboot
麦兜*12 天前
国产大模型平替方案:Spring Boot通义千问API集成指南
java·spring boot·后端·python·spring cloud·系统架构·springboot
core51212 天前
fastdfs快速部署、集成、调优
docker·部署·springboot·fastdfs·调用
尚学教辅学习资料12 天前
SpringBoot3.x入门到精通系列: 2.3 Web开发基础
前端·springboot·web开发
97zz12 天前
项目配置文件正确但是启动失败,报配置文件内容错误或中间件地址与实际不符
java·中间件·springboot
闫小甲12 天前
jobrunr xxljob 怎么选?
springboot·xxljob·jobrunr
core51213 天前
elk快速部署、集成、调优
elk·springboot·kibana·索引·查询
还是鼠鼠13 天前
tlias智能学习辅助系统--SpringAOP-进阶-通知顺序
java·后端·mysql·spring·mybatis·springboot
蜗牛031414 天前
2、RabbitMQ的5种模式基本使用(Maven项目)
java·springboot·java-rabbitmq