27、請求處理-【源碼分析】-怎么改變默認的_method
要改變 Spring Boot 中默認的 `_method` 參數,可以通過以下步驟實現:
#### 原理分析
Spring Boot 中默認的 `HiddenHttpMethodFilter` 用于將表單中的 `_method` 參數值映射為實際的 HTTP 方法(如 PUT、DELETE 等),以便支持 RESTful 風格的請求。
#### 修改默認 `_method` 參數
1. **自定義 `HiddenHttpMethodFilter`**
? ?
? ?- 創建一個配置類,自定義 `HiddenHttpMethodFilter` Bean。
? ?
? ?```java
? ?@Configuration
? ?public class WebConfig {
? ?
? ? ? ?@Bean
? ? ? ?public HiddenHttpMethodFilter hiddenHttpMethodFilter() {
? ? ? ? ? ?HiddenHttpMethodFilter filter = new HiddenHttpMethodFilter();
? ? ? ? ? ?filter.setMethodParam("_m"); // 將默認的 _method 修改為 _m
? ? ? ? ? ?return filter;
? ? ? ?}
? ?}
? ?```
? ?
2. **修改表單**
? ?
? ?- 在表單中,將原先的 `_method` 隱藏域名稱修改為 `_m`。
? ?
? ?```html
? ?<form action="/user" method="post">
? ? ? ?<input name="_m" type="hidden" value="DELETE" />
? ? ? ?<input type="submit" value="REST-DELETE 提交" />
? ?</form>
? ?```
#### 原理說明
- **`@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)`**
??
? - `WebMvcAutoConfiguration` 類中,默認的 `HiddenHttpMethodFilter` Bean 是在沒有用戶自定義該 Bean 時才會被創建。
??
- **自定義 Bean 生效**
??
? - 通過自定義 `HiddenHttpMethodFilter` Bean 并設置 `setMethodParam` 方法,覆蓋了默認的配置,從而改變了 `_method` 參數的默認值。
---
通過以上步驟,成功將 Spring Boot 中默認的 `_method` 參數修改為 `_m`,實現了自定義請求方法參數的功能。