Filter

基本使用

@Bean
public Filter addHeaderFilter() {
    return new Filter() {
        @Override
        public CompletableFuture<Void> doFilter(AsyncRequest request, AsyncResponse response, FilterChain chain) {
            request.setHeader("foo", "bar");
            return chain.doFilter(request, response);
        }
    };
}

上面的例子将会给所有到来的请求都加上一个固定的Header。

异步Filter

@Bean
public Filter filter() {
    return new Filter() {
        @Override
        public CompletableFuture<Void> doFilter(AsyncRequest request, AsyncResponse response, FilterChain chain) {
            return CompletableFuture.runAsync(() -> {
                // do something...
            }).thenCompose(r -> {
                // invoke next filter
                return chain.doFilter(request, response);
            });
        }
    };
}

上面的例子演示了在doFilter(xxx)中进行异步操作,并在该操作完成后回调FilterChain继续执行后续操作。

终止Filter的执行

当不期望执行后续的Filter时可返回一个CompletableFuture.completedFuture(null)实例。

@Override
public CompletableFuture<Void> doFilter(AsyncRequest request, AsyncResponse response, FilterChain chain) {
    return CompletableFuture.completedFuture(null);
}