我有一个WebFilter,我想排除几个URL。
我使用了PathPattern,该路径可用于排除1个网址,但不能超过此数量。
私有最终PathPattern pathPattern;
public MyFilter() {
pathPattern = new PathPatternParser().parse("/url");
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
if (pathPattern.matches(exchange.getRequest().getPath().pathWithinApplication())) {
return chain.filter(exchange);
}
答案 0 :(得分:0)
有多种方法,下面是其中一种方法
@Slf4j
@Component
public class LogFilter implements WebFilter {
List<PathPattern> pathPatternList;
public LogFilter() {
PathPattern pathPattern1 = new PathPatternParser()
.parse("/admin");
PathPattern pathPattern2 = new PathPatternParser().parse("/emp");
pathPatternList = new ArrayList<>();
pathPatternList.add(pathPattern1);
pathPatternList.add(pathPattern2);
}
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
RequestPath path = exchange.getRequest().getPath();
if (pathPatternList.stream().anyMatch(pathPattern -> pathPattern.matches(path.pathWithinApplication()))) {
log.info(path.toString() + " path excluded");
return chain.filter(exchange);
}
log.info("executing logic for " + path.toString() + " path");
return chain.filter(exchange);
}
}
对于网址/admin
和/emp
,它将排除其他网址的逻辑,它将在日志下面执行逻辑检查
2019-05-10 00:20:55.660 INFO 15837 --- [ctor-http-nio-3] o.l.reactiveapp.filter.LogFilter : /admin path excluded
2019-05-10 00:20:55.661 INFO 15837 --- [ctor-http-nio-3] o.l.r.controller.AdminController : get admin
2019-05-10 00:20:58.361 INFO 15837 --- [ctor-http-nio-3] o.l.reactiveapp.filter.LogFilter : /emp path excluded
2019-05-10 00:20:58.362 INFO 15837 --- [ctor-http-nio-3] o.l.r.controller.EmployeeController : get employee
2019-05-10 00:21:03.649 INFO 15837 --- [ctor-http-nio-3] o.l.reactiveapp.filter.LogFilter : executing logic for /messages/10 path
2019-05-10 00:21:03.651 INFO 15837 --- [ctor-http-nio-3] o.l.r.controller.StoresController : getting message details for id 10 enter code here
我希望这能回答您的问题
谢谢
答案 1 :(得分:0)
您可以使用装饰器包装您的 WebFilter,该装饰器通过提供的 ServerWebExchangeMatcher 限制内部 WebFilter 调用。
@RequiredArgsConstructor
public class RestrictedWebFilterDecorator implements WebFilter {
private final WebFilter inner;
private final ServerWebExchangeMatcher restrictionMatcher;
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
return restrictionMatcher.matches(exchange)
.flatMap(result -> result.isMatch()
? inner.filter(exchange, chain)
: chain.filter(exchange)
);
}
}
用法示例:
@Order(Ordered.HIGHEST_PRECEDENCE)
@Bean
public WebFilter yourWebFilter() {
return new RestrictedWebFilterDecorator(
new YourWebFilter,
new NegatedServerWebExchangeMatcher(YOUR_EXCHANGE_MATCHER)
);
}