Spring Webflux是Spring 5+的一部分提供的新的响应式Web框架。 在传统的基于Spring MVC的应用程序( Servlet Filter , HandlerInterceptor )中编写过滤器的方式与在基于Spring Webflux的应用程序中编写过滤器的方式非常不同,本文将简要介绍WebFlux的Filters方法。
方法1 – WebFilter
使用WebFilter的第一种方法会广泛影响所有端点,并涵盖以功能样式编写的 Webflux 端点以及使用注释样式编写的端点 。 Kotlin中的WebFilter如下所示:
@Beanfun 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添加了一个request属性,该属性的值是一个集合,在该属性中,过滤器仅将其拦截了请求的消息放入其中。
方法2 – HandlerFilterFunction
第二种方法更加集中,仅涵盖使用功能样式编写的端点 。 在这里,可以将特定的RouterFunction与过滤器连接起来,方法如下:
考虑以以下方式定义的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的HandlerFilterFunction:
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与基于Spring WebMVC的使用Servlet Spec或HandlerInterceptor编写过滤器的方法有很大不同,本文总结了新方法- 我的git repo中提供了示例,详细介绍了这些示例。
翻译自: https://www.javacodegeeks.com/2017/12/spring-webflux-writing-filters.html