环境:Springboot2。4。12 本篇主要内容:RouterFunction中使用过滤器URL处理组件 请先阅读:《SpringWebFlux使用函数式编程之HandlerFunction(1)》《SpringWebFlux使用函数式编程之RouterFunction(2)》概述 你可以通过在路由函数构建器上使用before、after或filter方法来筛选处理程序函数。通过使用注释,你可以通过使用ControllerAdvice、ServletFilter或两者都可以实现类似的功能。过滤器将应用于构建器构建的所有路由。这意味着在嵌套路由中定义的过滤器不适用于顶级路由。例如,考虑下面的例子:RouterFunctionServerResponserouteroute()。path(person,b1b1。nest(accept(APPLICATIONJSON),b2b2。GET({id},handler::getPerson)。GET(,handler::listPeople)。before(requestServerRequest。from(request)1。header(XRequestHeader,Value)。build()))。POST(person,handler::createPerson))。after((request,response)logResponse(response))2。build();添加自定义请求头的before过滤器只应用于两个GET路由。记录响应的after过滤器应用于所有路由,包括嵌套路由。 路由器构建器上的filter方法接受HandlerFilterFunction:一个接受ServerRequest和HandlerFunction并返回ServerResponse的函数。处理程序函数参数表示链中的下一个元素。这通常是路由到的处理程序,但如果应用了多个过滤器,它也可以是另一个过滤器。完整示例 处理程序句柄ComponentpublicclassPersonHandler{publicServerResponsequeryPerson(ServerRequestrequest)throwsException{System。out。println(request。headers()。header(xpack));returnok()。body(newPerson(Integer。valueOf(request。pathVariable(id)),中国));}privateErrorsvalidate(Personperson){ErrorserrorsnewBeanPropertyBindingResult(person,person);validator。validate(person,errors);if(errors。hasErrors()){}}} 路由配置ConfigurationpublicclassPersonHandlerConfiguration{ResourceprivatePersonHBeanpublicRouterFunctionServerResponsenestPerson2(){returnroute()。path(persons2,b1b1。nest(accept(MediaType。APPLICATIONJSON),b2b2。GET({id},accept(MediaType。APPLICATIONJSON),ph::queryPerson)。before(requestServerRequest。from(request)。header(xpack,123123)。build()))。POST(save,ph::save))。after((request,response){System。out。println(afterexecution。。。response。statusCode());})。filter((request,next){if(request。pathVariable(id)。equals(100)){returnServerResponse。ok()。body(参数错误);}else{returnnext。handle(request);}})。build();}} POJOpublicclassPerson{privateINotEmpty(message姓名必须填写)privateS}URL处理组件 URL组件可以在SpringMVCandSpringWebFlux中都可以使用。 UriComponentsBuilder帮助从带有变量的URI模板构建URI,如下例所示:UriComponentsuriComponentsUriComponentsBuilder。fromUriString(https:pack。comlovers{lover})1。queryParam(q,{q})2。encode()3。build();4URIuriuriComponents。expand(lover,hcw)。toUri();5使用URI模板的静态工厂方法添加或替换URI组件请求对URI模板和URI变量进行编码建立一个UriComponents展开变量并获得URI 以上代码运行结果:https:pack。comloverslover?qhcw 上面的例子可以合并为一个链,并使用buildAndExpand进行缩短,如下面的例子所示:URIuriUriComponentsBuilder。fromUriString(https:pack。comlovers{lover})。queryParam(q,{q})。encode()。buildAndExpand(lover,hcw)。toUri(); 你可以通过直接进入URI(这意味着编码)来进一步缩短它,如下面的例子所示:URIuriUriComponentsBuilder。fromUriString(https:pack。comlovers{lover})。queryParam(q,{q})。build(lover,hcw); 你可以使用完整的URI模板进一步缩短它,如下例所示:URIuriUriComponentsBuilder。fromUriString(https:pack。comlovers{lover})。build(lover,hcw); 完毕!!! Spring容器这些扩展点你都清楚了吗? Spring事务实现原理源码分析 Spring中的Configuration注解你真的了解吗? SpringBoot对SpringMVC都做了哪些事?(一) SpringBoot对SpringMVC都做了哪些事?(二) SpringBoot对SpringMVC都做了哪些事?(三) SpringBoot对SpringMVC都做了哪些事?(四)