Solon v3.0.3

八、过滤器的三种应用

</> markdown

1、用于全局请求的管控(默认)

  • 组件自动注册形式
@Component(index = 0) //index 为顺序位(不加,则默认为0)
public class AppFilter implements Filter {
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        //bef ...
        chain.doFilter(ctx);
        //aft ...
    }
}  
  • 手动注册形式
public class App {
    public static void main(String[] args) {
        Solon.start(App.class, args, app-> {
            app.filter((ctx, chain)-> {
                //bef ...
                chain.doFilter(ctx);
                //aft ...
            });
        });
    }
}

2、用于本地网关

具体参考后面的 《Solon Gateway 开发》

@Mapping("/api/**")
@Component
public class ApiGateway extends Gateway {
    @Override
    protected void register() {
        filter((ctx, chain)-> {
            //bef ...
            chain.doFilter(ctx);
            //aft ...
        });

        //添加Bean
        addBeans(bw -> "api".equals(bw.tag()));
    }

    //重写渲染处理异常
    @Override
    public void render(Object obj, Context c) throws Throwable {
        if (obj instanceof Throwable) {
            c.render(Result.failure("unknown error"));
        } else {
            c.render(obj);
        }
    }
}

3、用于局部控制(附加到控制器)

v2.9.3 后支持

@Controller
public class DemoController{
    //删除比较危险,加个白名单检查
    @Addition(WhitelistFilter.class)
    @Mapping("user/del")
    public void delUser(..){
    }
}

//将 @Addition 附加在 Whitelist 注解上;@Whitelist 就代表了 @Addition(WhitelistFilter.class)
@Addition(WhitelistFilter.class)
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Whitelist {
}

public class WhitelistFilter implements Filter{
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        //bef do...
        chain.doFilter(ctx);
    }
}