
正文
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风格,即使用请求方式来判断用户的具体业务操作,避免了原生的请求名称过长,或不易记、以后也不需要为想名字而烦恼了






