Spring Boot核心技術之Restful映射以及源碼的分析


Spring Boot核心技術之Rest映射以及源碼的分析

該博客主要是Rest映射以及源碼的分析,主要是思路的學習。SpringBoot版本:2.4.9

環境的搭建

主要分兩部分:

image-20210801160602153

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>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="delete">
    <input value="REST-DELETE 提交" type="submit"/>
  </form>

  <form action="/user" method="put">
    <input value="REST-PUT提交"type="submit" />
  </form>

</body>
</html>

controller

package com.xbhong.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@RestController
public class myContro {
    @RequestMapping(value = "/user",method = RequestMethod.GET)
    public String getUser(){
        return "GET-張三";
    }

//    @PostMapping("/user")
    @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)
    public String deleteUser(){
        return "DELETE-張三";
    }
}

測試功能是否可用:

觀察效果:

Rest映射1

可以看到最后兩個請求都變成Get的請求了。由此我們可以引出來如下問題:

  1. 為什么不同的請求會出現相同的結果
  2. 怎么實現的才能完成我們的功能

后面的文章就是圍繞上述的問題進行展開的。

解決問題:

像之前的SpringMVC中的表單請求通過HiddenHttpMethodFilter實現的,這樣我們查一下在SpringBoot中是怎么樣的。

默認雙擊Shift鍵,輸入WebMvcAutoConfiguration這個類

找到默認配置的過濾器:

@Bean
@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false)
public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
    return new OrderedHiddenHttpMethodFilter();
}

通過OrderedHiddenHttpMethodFilter進入父類HiddenHttpMethodFilter:

在使用之前,我們需要將后兩個的請求方式改寫成post方式,並且需要在請求的時候傳入一個_method方法(設置隱藏域);

<form action="/user" method="post">
    <input name="_method" type="hidden" value="DELETE"/>
    <input value="REST-DELETE 提交" type="submit"/>
</form>

<form action="/user" method="post">
    <input name="_method" type="hidden" value="PUT" />
    <input value="REST-PUT提交"type="submit" />
</form>

為什么要這樣設置呢?我們到HiddenHttpMethodFilter中看下。

image-20210801165914667

流程:

  1. 第一步保存了傳入的請求
  2. 當該請求時post,並且請求沒有異常,才能進入下面方法,不是Post請求將直接通過過濾器鏈放行。
  3. 獲取請求中的參數(this.methodParam)
  4. DEFAULT_METHOD_PARAM = _method獲得(作為真正的請求方式)

然后再測試,發現還是沒有實現。

我再回到WebMvcConfiguration中:

@Bean
@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)
@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false)
public OrderedHiddenHttpMethodFilter hiddenHttpMethodFilter() {
    return new OrderedHiddenHttpMethodFilter();
}

首先該類存在於容器中。

@ConditionalOnMissingBean(HiddenHttpMethodFilter.class)

當容器中不存在HiddenHttpMethodFilter這個類的時候,下面內容開啟(條件裝配);

@ConditionalOnProperty(prefix = "spring.mvc.hiddenmethod.filter", name = "enabled", matchIfMissing = false)

表示:綁定的配置文件中:spring.mvc.hiddenmethod.filter名字為enable是默認不開啟的(后續版本可能開啟)。這樣我們就找到了問題的所在。

所以我們需要在配置文件中配置(兩種方法都可以)。

yaml:

spring:
  mvc:
    hiddenmethod:
      filter:
        enabled: true

properties:

spring.mvc.hiddenmethod.filter.enabled=true

重啟項目:成功解決。

Rest映射2

源碼分析:

主要是分析doFilterInternal:

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
    throws ServletException, IOException {

    HttpServletRequest requestToUse = request;

    if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
        String paramValue = request.getParameter(this.methodParam);
        if (StringUtils.hasLength(paramValue)) {
            String method = paramValue.toUpperCase(Locale.ENGLISH);
            if (ALLOWED_METHODS.contains(method)) {
                requestToUse = new HttpMethodRequestWrapper(request, method);
            }
        }
    }

    filterChain.doFilter(requestToUse, response);
}
  • 表單提交會帶上_method=PUT

  • 請求過來被HiddenHttpMethodFilter攔截

  • 請求是否正常,並且是POST

  • 獲取到_method的值。

  • 兼容以下請求;PUT.DELETE.PATCH

    當方法走到上述代碼11行時,進入ALLOWED_METHODS:

    private static final List<String> ALLOWED_METHODS =
    			Collections.unmodifiableList(Arrays.asList(HttpMethod.PUT.name(),
    					HttpMethod.DELETE.name(), HttpMethod.PATCH.name()));
    

    如果請求里的參數在ALLOWED_METHODS存在,則執行下面代碼。

  • 原生request(post),包裝模式requesWrapper重寫了getMethod方法,返回的是傳入的值。

    進入HttpMethodRequestWrapper對象中,向上找父類。本質還是HttpServletRequest

    由下面代碼:

    private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {
    
        private final String method;
    
        public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
            super(request);
            this.method = method;
        }
    
        @Override
        public String getMethod() {
            return this.method;
        }
    }
    

    可知,接收到前面的請求封裝為HttpMethodRequestWrapper返回。

  • 過濾器鏈放行的時候用wrapper。以后的方法調用getMethod是調用requesWrapper的。

部分補充:

由於源碼中規則:將獲得請求中的參數無條件的以英文格式轉完成大寫,所以前端的value="PUT"value的值大小寫無影響。

String paramValue = request.getParameter(this.methodParam);
if (StringUtils.hasLength(paramValue)) {
    String method = paramValue.toUpperCase(Locale.ENGLISH);

Rest使用客戶端工具,

  • 如PostMan直接發送Put、delete等方式請求,無需Filter。

參考文獻:

B站尚硅谷

結束:

如果你看到這里或者正好對你有所幫助,希望能點個關注或者推薦,感謝;

有錯誤的地方,歡迎在評論指出,作者看到會進行修改。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM