[英]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.