javascript
Spring Webflux –编写过滤器
Spring Webflux是Spring 5+的一部分提供的新的響應(yīng)式Web框架。 在傳統(tǒng)的基于Spring MVC的應(yīng)用程序( Servlet Filter , HandlerInterceptor )中編寫(xiě)過(guò)濾器的方式與在基于Spring Webflux的應(yīng)用程序中編寫(xiě)過(guò)濾器的方式非常不同,本文將簡(jiǎn)要介紹WebFlux的Filters方法。
方法1 – WebFilter
使用WebFilter的第一種方法會(huì)廣泛影響所有端點(diǎn),并涵蓋以功能樣式編寫(xiě)的 Webflux 端點(diǎn)以及使用注釋樣式編寫(xiě)的端點(diǎn) 。 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添加了一個(gè)request屬性,該屬性的值是一個(gè)集合,在該屬性中,過(guò)濾器僅將其攔截了請(qǐng)求的消息放入其中。
方法2 – HandlerFilterFunction
第二種方法更加集中,僅涵蓋使用功能樣式編寫(xiě)的端點(diǎn) 。 在這里,可以將特定的RouterFunction與過(guò)濾器連接起來(lái),方法如下:
考慮以以下方式定義的Spring Webflux端點(diǎn):
@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) })請(qǐng)注意,無(wú)需明確說(shuō)明Kotlin中的類型,我添加它只是為了清楚一些lambda表達(dá)式中的類型。
結(jié)論
WebFilter方法和HandlerFilterFunction與基于Spring WebMVC的使用Servlet Spec或HandlerInterceptor編寫(xiě)過(guò)濾器的方法有很大不同,本文總結(jié)了新方法- 我的git repo中提供了示例,詳細(xì)介紹了這些示例。
翻譯自: https://www.javacodegeeks.com/2017/12/spring-webflux-writing-filters.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的Spring Webflux –编写过滤器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 饥饿龙安卓版(饥饿龙 安卓)
- 下一篇: foxmail电脑同步设置(foxmai