Spring WebFlux: 编写拦截器
译者:Han Bin
Spring WebFlux是Spring 5+的一部分, 提供了一种新的响应性Web框架。 在基于Spring MVC的传统应用程序 (Servlet Filter, HandlerInterceptor)中编写过滤器的方式与在基于Spring WebFlux的应用程序中编写过滤器的方式截然不同,本文将简单介绍使用WebFlux编写过滤器的方法。
方法 1: WebFilter
使用WebFilter编写的拦截器会广泛影响到所有端点,并覆盖了用函数样式编写的WebFlux端点, 以及使用注释样式编写的端点。. Kotlin中的WebFilter如下所示:
@Bean
fun sampleWebFilter(): WebFilter {
return WebFilter { e: ServerWebExchange, c: WebFilterChain ->
val l: MutableList<String> = e.getAttributeOrDefault(KEY, mutableListOf())
l.add("From WebFilter")
e.attributes.put(KEY, l)
c.filter(e)
}
}
WebFilter 只是添加了一个请求属性,该属性的值是一个集合。
方法 2: HandlerFilterFunction
这种方法更加的专注于使用函数样式编写的端点。。这里我们参考下面的代码来使用 RouterFunctions 来构建一个 filter。
按照下面的办法设置 Spring WebFlux 的端点:
@Bean
fun route(): RouterFunction<*> = router {
GET("/react/hello", { r ->
ok().body(fromObject(
Greeting("${r.attribute(KEY).orElse("[Fallback]: ")}: Hello")
))
POST("/another/endpoint", TODO())
PUT("/another/endpoint", TODO())
})
}
通过下面的代码看到,单独拦截这些 API 的 HanderFIlterFunction 可以被高度集中地添加:
fun route(): RouterFunction<*> = router {
GET("/react/hello", { r ->
ok().body(fromObject(
Greeting("${r.attribute(KEY).orElse("[Fallback]: ")}: Hello")
))
})
POST("/another/endpoint", TODO())
PUT("/another/endpoint", TODO())
}.filter({ r: ServerRequest, n: HandlerFunction<ServerResponse> ->
val greetings: MutableList<String> = r.attribute(KEY)
.map { v ->
v as MutableList<String>
}.orElse(mutableListOf())
greetings.add("From HandlerFilterFunction")
r.attributes().put(KEY, greetings)
n.handle(r)
})
请注意,不需要明确Kotlin中的类型----我添加它只是为了明确某些lambda表达式中的类型。
结束语
WebFilter和HandlerFilterFunction与使用Servlet规范编写过滤器或使用HandlerInterceptors的基于Spring-WebMVC的方法大不相同。 这篇文章总结了新的方法。 有关更多信息,我在我的my git repo中提供了示例,git 上面有详细信息。