前言
Rest 方式可以发送 GET 、POST、PUT、DELETE 等方式的请求。但是表单只能GET提交或POST提交,通过 HiddenHttpMethodFilter 拦截器可以处理PUT、DELETE请求。本文主要介绍拦截器的使用。
其他的客户端工具,可以直接发送各种请求方式,因此无需filter做转换。因此,filter功能是选择性开启,不是一定要开启的。
一、Controller类
package com.example.demo.controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloCotroller {
@RequestMapping(value = "/user",method = RequestMethod.GET)
public String getUser(){
return "GET-张三";
}
@RequestMapping(value = "/user",method = RequestMethod.POST)
public String saveUser(){
return "POST-张三";
}
@RequestMapping(value = "/user",method = RequestMethod.PUT)
public String putUser(){
return "PUT-张三";
}
// @RequestMapping(value = "/user",method = RequestMethod.DELETE)
@DeleteMapping(value = "/user")
public String deleteUser(){
return "DELETE-张三";
}
}
- Delete请求两种写法——其他请求同理
@DeleteMapping(value = "/user")
@RequestMapping(value = "/user",method = RequestMethod.DELETE)
二、配置文件
spring:
mvc:
hiddenmethod:
filter:
enabled: true #开启表单的filter功能
三、请求写法
在post请求中加入
<input type="hidden" name="_method" value="delete">
完整代码:
<!--HiddenHttpMethodFilter拦截-->
<form action="/user" method="post">
<!--获取_method的值 value大小写都行,自动转为大写 容许的只有delete put patch-->
<input type="hidden" name="_method" value="delete">
<input type="submit" value="REST-DELETE 提交">
</form>
四、自定义 _method 名字
- 自定义Filter
创建一config包 —— 在config包下定义WebMvcConfigurer类
//自定义filter
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.filter.HiddenHttpMethodFilter;
@Configuration(proxyBeanMethods = false)
public class WebConfig implements WebMvcConfigurer {
@Bean
public HiddenHttpMethodFilter hiddenHttpMethodFilter(){
HiddenHttpMethodFilter methodFilter = new HiddenHttpMethodFilter();
methodFilter.setMethodParam("_myMethod");
return methodFilter;
}
}
Filter原理
● 表单提交会带上_method=PUT (大小写都可以)
● 请求被HiddenHttpMethodFilter拦截
1. 判断请求是否正常,并且是POST类请求
■ 获取到_method的值(value)
■ 兼容以下请求;PUT.DELETE.PATCH
■ 原生request(post),包装模式requesWrapper重写了getMethod方法,返回的是传入的值
■ 过滤器链放行的时候用wrapper。以后的方法调用getMethod是调用requesWrapper的。
请求映射原理
源码:
org.springframework.web.servlet.DispatcherServlet —— doDispatch()