实现GlobalFilter, Ordered
接口即可,详见注释
记得加@Component
注解
模板如下
@Component
@Slf4j
public class GatewayFilter implements GlobalFilter, Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
{
System.out.println("time:"+new Date()+"\t 自定义的全局过滤器:"+"GatewayFilter");
// 提取出参数key为username的值
String uname = exchange.getRequest().getQueryParams().getFirst("username");
// 拦截
if (username == null) {
System.out.println("****用户名为null,无法登录");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE); // set一个不接受的代码
return exchange.getResponse().setComplete();
}
// 放行
return chain.filter(exchange);
}
@Override
public int getOrder() {
return 0;
}
}
如果请求不加username参数,就会被拦截