简体   繁体   中英

How to drop HTTP requests in a Java Play! filter?

I have a filter (coded in Java) that processes every HTTP request made to my app. I want this filter to look at the value of a specific header, and based on that value, drop (ie eventually return a 404 error) this current HTTP request.

Is it possible to do this in Play?

Thanks,

This is fairly straight-forward. First of all, read and understand the section on filters in the documentation .

The implementation of your filter then looks like this:

import akka.stream.Materializer;
import play.mvc.Filter;
import play.mvc.Http;

public class HeaderFilter extends Filter {
    @Inject
    public HeaderFilter(final Materializer mat) {
        super(mat);
    }

    @Override
    public CompletionStage<Result> apply(final Function<Http.RequestHeader, CompletionStage<Result>> next,
                                         final Http.RequestHeader requestHeader) {
        final String header = requestHeader.getHeader("header name");
        if (some test) {
            // allow the request to continue
            return next.apply(requestHeader);
        } else {
            // block the request
            return CompletableFuture.completedFuture(Results.notFound());
        }
    }
}

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