简体   繁体   English

Spring MVC在控制器之前获取POST主体

[英]Spring MVC Get POST body before controllers

I need to read POST requests body without consuming it. 我需要读取POST请求正文而不消耗它。

I've tried it in a several ways in my custom HandlerInterceptor and nothing works. 我在我的自定义HandlerInterceptor中以多种方式尝试过它并且没有任何效果。 All I've tried to do to wrap and cache request bodies, at a some point, didn't work, probably even because I cannot control what Spring does. 在某些时候,所有我试图包装和缓存请求主体都没有用,可能是因为我无法控制Spring的功能。

So I thinked another thing: at some point Spring will try to map request body to an object and pass it to the right Controller. 所以我想到了另一件事:在某些时候,Spring会尝试将请求主体映射到一个对象并将其传递给正确的Controller。 I can intercept this action and get that object before the Controller is called? 我可以拦截这个动作并在调用Controller之前获取该对象?

Once the request body is read from the request before reaching controller you can not use anywhere. 在到达控制器之前从请求中读取请求主体后,您无法在任何地方使用。 So what you can do is to read the body from HttpServletRequest in the Filter implementation and set it in ThreadLocal variable. 所以你可以做的是从Filter实现中的HttpServletRequest读取body并在ThreadLocal变量中设置它。 Then you can read from that ThreadLocal . 然后你可以从那个ThreadLocal读取。 Below is the sample code. 下面是示例代码。

Inside Filter implementation class Inside Filter实现类

try {
    YourModel yourModel = // Read the request body

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

and at any point of time in the current request you can do like below. 在当前请求中的任何时间点,您都可以执行以下操作。

RequestContextHolder.getContext();

Here is the RequestContextHolder class 这是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();
    }
}

I've found a solution: using a CommonsRequestLoggingFilter Spring can log even the payload of the requests. 我找到了一个解决方案:使用CommonsRequestLoggingFilter Spring可以记录请求的有效负载。 The only bother I'm finding is that I can read the payload only in afterRequest method because in the beforeRequest is absent. 我发现的唯一麻烦是我只能在afterRequest方法中读取有效负载,因为在beforeRequest中没有。

More info on CommonsRequestLoggingFilter here . 有关CommonsRequestLoggingFilter的更多信息,请点击此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM