[英]How to log RequestBody in async spring controller?
我向現有的spring-mvc
應用程序添加了一個異步端點:
@RestController
public class MyController {
@PostMapping("/")
public Mono<String> post(Object body) {
return Mono.just("test");
//webClient.retrieve().bodyToMono(String.class);
}
}
我想創建一個全局攔截器/過濾器來記錄請求正文有效負載。 但是我怎樣才能訪問它呢?
我嘗試添加一個HandlerInterceptorAdapter
,但有效負載始終為空:
static class LoggingInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
ContentCachingRequestWrapper wrapper = new ContentCachingRequestWrapper(request);
byte[] buf = wrapper.getContentAsByteArray();
System.out.println(buf);
System.out.println(buf.length);
return true;
}
}
可能有效負載尚未出現在請求中,或者已經被讀取。 那么如何在這種異步情況下訪問正文呢?
不幸的是,在Webflux 中您不能使用HandlerInterceptorAdapter,因為它來自web mvc模塊並且僅適用於 servlet。 我找到了一篇帶有解決方案的好文章。
PS 如果要使用反應式端點,您必須刪除 spring-mvc 依賴項。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.