You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WebFlux嵌套路由中根路径路由返回404问题求助

问题排查与解决办法

嘿,我仔细看了你的代码,发现问题出在嵌套路由的定义顺序上!这是Spring WebFlux RouterFunction里很容易踩的一个坑。

为啥会返回404?

你看/category下的路由顺序:

.andRoute(GET("/{id}"), handler::handleGetProductCategoryById)
.andRoute(GET("/"), handler::handleGetAllProductCategories)

这里你先定义了GET("/{id}"),再定义GET("/")。而Spring WebFlux的路由匹配是按定义顺序来的,当你请求/category/的时候,框架会先尝试匹配/{id}——它会把路径末尾的空值(因为/category/最后一个/会被忽略)当成id的参数,所以直接命中了handleGetProductCategoryById方法。但你的这个Handler大概率没处理空字符串的id,所以就返回404了,根本轮不到handleGetAllProductCategories执行。

那为啥根路径和/brand下的同类路由没问题?

  • 根路径的GET("/")和GET("/{id}")其实是不同层级的路径(一个是apiPath+BASE_PATH,一个是apiPath+BASE_PATH/{id}),所以不会冲突;
  • 再看/brand的路由:你是先定义GET("/")再定义GET("/{id}"),所以请求/brand/的时候会优先匹配到handleGetAllProductBrands,自然正常工作。

怎么解决?

把/category下的GET("/")路由移到GET("/{id}")前面就行,调整后的代码:

.andNest(path("/category"), 
 route(POST("/").and(contentType(MediaType.APPLICATION_JSON)), handler::handleCreateProductCategory)
 .andRoute(GET("/"), handler::handleGetAllProductCategories) // 把这条移到/{id}前面
 .andRoute(GET("/{id}"), handler::handleGetProductCategoryById)
 .andRoute(GET("/search/{name}"), handler::handleGetProductCategoriesByName)
 ))

这样请求/category/的时候,会先匹配到GET("/")的路由,就能正确调用handleGetAllProductCategories了。

额外验证

你可以临时在handleGetProductCategoryById里加个日志,打印一下id参数,会发现请求/category/时,id是空字符串,这就验证了我们的结论。


内容的提问来源于stack exchange,提问作者J.Pip

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:24:24