没有一个很好的Java API可用于创建Play Filters。但是,您可以将现有的 Scala API 改编成一个不错的 Java 模板。
例如:
import play.api.mvc.*;
import scala.Function1;
import scala.concurrent.Future;
import scala.runtime.AbstractFunction1;
public abstract class JavaFilter implements Filter {
@Override
public Future<Result> apply(Function1<RequestHeader, Future<Result>> nextFilter, RequestHeader requestHeader) {
return nextFilter
.apply(requestHeader)
.map(new AbstractFunction1<Result, Result>() {
@Override
public Result apply(Result currentResult) {
return Apply(currentResult, requestHeader);
}
},
play.api.libs.concurrent.Execution.defaultContext());
}
@Override
public EssentialAction apply(EssentialAction next) {
return Filter$class.apply(this, next);
}
public abstract Result Apply(Result currentResult, RequestHeader requestHeader);
}
示例实现:
import play.api.mvc.RequestHeader;
import play.api.mvc.Result;
public class HelloFilter extends JavaFilter {
@Override
public Result Apply(Result currentResult, RequestHeader requestHeader) {
if (requestHeader.headers().get("X-Filter").isDefined()) {
ResultAdapter resultAdapter = new ResultAdapter(currentResult);
return resultAdapter.WithHeader("X-Hello", "World!");
}
return currentResult;
}
}
有关其工作原理的进一步解释,请参阅我在此处的博客文章