Spring RequestMapping检测路径匹配核心类AntPathMatcher

本文基于Spring 5.0+

项目某些页面是通过后台映射的,匹配映射路径时,有那种路径参数匹配。其中一个定义好的路径匹配是:

/{corporationName}_{vendorName}/{shopName}_with_{retailer_name}?g={goodsId}

当时没有仔细看,其实{goodsId}也应该作为路径参数,可能是前端想要拿到这个id,放在url参数的位置比较容易拿到,所以就放在这个位置。

想验证下这样自由的url是否能匹配成功,看了下spring-webmvc和spring-core的源码,找到url匹配核心类PathMatcher,目前还是只有古老的AntPathMatcher这一种实现。

我们来试下,是否能匹配成功:

new AntPathMatcher().match("/{corporationName}_{vendorName}/{shopName}_with_{retailer_name}?g={goodsId}","/corporation 1 _ vendor 2/shop 1_with_retailer 2?g=good1")

这个返回是true

看来可以匹配,实装后,发现访问路径返回404.查看源码,发现HttpRequest的url里面是不带url参数的,诶呀,把这个给忘了,修改成 @RequestMapping("/{corporationName}_{vendorName}/{shopName}_with_{retailer_name}")之后,成功

但是,还是在设计的时候,把goodId设置在路径上面,比较好。虽然前端可能会麻烦一点儿

评论

暂无评论