簡體   English   中英

Spring MVC在控制器之前獲取POST主體

[英]Spring MVC Get POST body before controllers

我需要讀取POST請求正文而不消耗它。

我在我的自定義HandlerInterceptor中以多種方式嘗試過它並且沒有任何效果。 在某些時候,所有我試圖包裝和緩存請求主體都沒有用,可能是因為我無法控制Spring的功能。

所以我想到了另一件事:在某些時候,Spring會嘗試將請求主體映射到一個對象並將其傳遞給正確的Controller。 我可以攔截這個動作並在調用Controller之前獲取該對象?

在到達控制器之前從請求中讀取請求主體后,您無法在任何地方使用。 所以你可以做的是從Filter實現中的HttpServletRequest讀取body並在ThreadLocal變量中設置它。 然后你可以從那個ThreadLocal讀取。 下面是示例代碼。

Inside Filter實現類

try {
    YourModel yourModel = // Read the request body

    RequestContextHolder.setContext(yourModel);
}finally {
    RequestContextHolder.clearContext();
}

在當前請求中的任何時間點,您都可以執行以下操作。

RequestContextHolder.getContext();

這是RequestContextHolder

public class RequestContextHolder {

    private static final ThreadLocal<YourModel> THREAD_LOCAL = new ThreadLocal<>();

    public static void setContext(YourModel yourModel) {
        THREAD_LOCAL.set(yourModel);
    }

    public static YourModel getContext() {
       return THREAD_LOCAL.get();
    }

    public static void clearContext() {
       THREAD_LOCAL.remove();
    }
}

我找到了一個解決方案:使用CommonsRequestLoggingFilter Spring可以記錄請求的有效負載。 我發現的唯一麻煩是我只能在afterRequest方法中讀取有效負載,因為在beforeRequest中沒有。

有關CommonsRequestLoggingFilter的更多信息,請點擊此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM