Solon v3.0.3

七、Route 的过滤器与定制

</> markdown

RouteFilterFactory 是专为路由过滤拦截处理设计的接口。对应路由配置 filters

1、内置的路由过滤器

过滤器工厂本置前缀说明与示例
AddRequestHeaderFilterFactoryAddRequestHeader=添加请求头
(AddRequestHeader=Demo-Ver,1.0)
AddResponseHeaderFilterFactoryAddResponseHeader=添加响应头
(AddResponseHeader=Demo-Ver,1.0)
PrefixPathFilterFactoryPrefixPath=附加路径前缀
(PrefixPath=/app)
RedirectToFilterFactoryRedirectTo=跳转到
(RedirectTo=302,http://demo.org/a,true)
RemoveRequestHeaderFilterFactoryRemoveRequestHeader=移除请求头
(RemoveRequestHeader=Demo-Ver,1.0)
RemoveResponseHeaderFilterFactoryRemoveResponseHeader=移除响应头
(RemoveResponseHeader=Demo-Ver,1.0)
StripPrefixFilterFactoryStripPrefix=移除路径前缀段数
(StripPrefix=1)

2、定制示例

  • StripPrefix 过滤器定制示例(配置例:StripPrefix=1
@Component
public class StripPrefixFilterFactory implements RouteFilterFactory {

    @Override
    public String prefix() {
        return "StripPrefix";
    }

    @Override
    public ExFilter create(String config) {
        return new StripPrefixFilter(config);
    }

    public static class StripPrefixFilter implements ExFilter {
        private int parts;

        public StripPrefixFilter(String config) {
            if (Utils.isBlank(config)) {
                throw new IllegalArgumentException("StripPrefixFilter config cannot be blank");
            }

            this.parts = Integer.parseInt(config);
        }

        @Override
        public Completable doFilter(ExContext ctx, ExFilterChain chain) {
            //目标路径重组
            List<String> pathFragments = Arrays.asList(ctx.newRequest().getPath().split("/", -1));
            String newPath = "/" + String.join("/", pathFragments.subList(parts + 1, pathFragments.size()));
            ctx.newRequest().path(newPath);

            return chain.doFilter(ctx);
        }
    }
}