Springboot中Rest风格请求映射如何开启并使用

阅读目录

 


回到顶部

问题引入

因为前端页面只能请求两种方式:GET请求和POST请求,所以就需要后台对其进行处理

解决办法:通过springmvc中提供的HiddenHttpMethodFilter过滤器来实现

而由于我们springboot中通过OrderedHiddenHttpMethodFilter类去继承了springmvc中的HiddenHttpMethodFilter类,所以该类就拥有了HiddenHttpMethodFilter的所有功能,而只要我们在springboot启动时将该组件加入到容器中,那么该功能就会生效

生效的条件:

回到顶部

查看HiddenHttpMethodFilter过滤器源码

找到其中的 doFilterInternal()方法

回到顶部

编写代码

后台控制器UserController

 1 package com.lzp.controller;
 2 
 3 import org.springframework.web.bind.annotation.*;
 4 
 5 /**
 6  * @Author LZP
 7  * @Date 2021/7/19 11:18
 8  * @Version 1.0
 9  */
10 @RestController
11 public class UserController {
12 
13     @PostMapping("/user")
14     public String post() {
15         return "POST-USER";
16     }
17 
18     @DeleteMapping("/user")
19     public String delete() {
20         return "DELETE_USER";
21     }
22 
23     @PutMapping("/user")
24     public String put() {
25         return "PUT_USER";
26     }
27 
28     @GetMapping("/user")
29     public String get() {
30         return "GET-USER";
31     }
32 
33 
34 
35 }

HTML页面代码

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8     <form action="/user" method="get">
 9         <input type="submit" value="GET方法">
10     </form>
11     <form action="/user" method="post">
12         <input type="submit" value="POST方法">
13     </form>
14     <form action="/user" method="post">
15         <input type="hidden" name="_method" value="DELETE">
16         <input type="submit" value="DELETE方法">
17     </form>
18     <form action="/user" method="post">
19         <input type="hidden" name="_method" value="PUT">
20         <input type="submit" value="PUT方法">
21     </form>
22 </body>
23 </html>

回到顶部

开启过滤器

在springboot全局配置文件application.properties中进行配置

回到顶部

前端页面效果展示

get请求

post请求

delete请求

put请求

这样一来,我们就可以使用Rest风格,即使用请求方式来判断用户的具体业务操作,避免了原生的请求名称过长,或不易记、以后也不需要为想名字而烦恼了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值