简体   繁体   中英

Get the request body in play framework using filters and actions.(in java)

Not able to find request body for incoming request in play framework java. I need to log all the incoming request in play framework api. For that, I try to use filters and action compositions. But I am able to get the request body.

I try to use filters and action compositions.

public class LoggingFilter extends EssentialFilter {

    private final Executor executor;

    @Inject
    public LoggingFilter(Executor executor) {
        super();
        this.executor = executor;
    }

    @Override
    public EssentialAction apply(EssentialAction next) {
        return EssentialAction.of(request -> {
            long startTime = System.currentTimeMillis();

            Accumulator<ByteString, Result> accumulator = next.apply(request);

            System.out.println(request);
            return accumulator.map(result -> {
                long endTime = System.currentTimeMillis();
                long requestTime = endTime - startTime;


                Logger.info("{} {} took {}ms and returned {}",
                        request.method(), request.uri(), requestTime, result.status());

                return result.withHeader("Request-Time", "" + requestTime);
            }, executor);
        });
    }
}

From this request, I am just able to get boolean whether body is present or not. But not able to get the actual body.

You can get request body and log it as you want in action composition:

import play.Logger;
import play.mvc.Http;
import play.mvc.Result;

import java.util.concurrent.CompletionStage;

public class ClientLogger extends play.mvc.Action.Simple {

    public CompletionStage<Result> call(Http.Context context) {
        StringBuffer logMessage = new StringBuffer();
        logMessage.append(context.request().toString())
                .append("\n")
                .append("body json: " + context.request().body().asJson().toString());
        Logger.info(logMessage.toString());
        return delegate.call(context);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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