建设中专网站首页,招网络推广招聘,外汇直播室都是网站做,丽江网架公司Spring Webflux是Spring 5的一部分提供的新的响应式Web框架。 在传统的基于Spring MVC的应用程序#xff08; Servlet Filter #xff0c; HandlerInterceptor #xff09;中编写过滤器的方式与在基于Spring Webflux的应用程序中编写过滤器的方式非常不同#xff0c;本文将… 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: MutableListString 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: HandlerFunctionServerResponse -val greetings: MutableListString r.attribute(KEY).map { v -v as MutableListString}.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