【问题标题】:Spring SimpleUrlHandlerMapping: Pattern doesn't match URLSpring SimpleUrlHandlerMapping:模式与 URL 不匹配
【发布时间】:2014-04-01 10:19:06
【问题描述】:

我有以下映射:

<bean id="controllerMappingProperties" class="java.util.Properties">
    <constructor-arg>
        <props>
            <prop key="/service/q-*-fltr-brand-_-*-find-html.html">redirectController</prop>
            <prop key="/service/q">queryController</prop>
            <prop key="/service/q-*.html">queryController</prop>
        </props>
    </constructor-arg>
</bean>

所以网址

http://localhost:8080/service/q-foo-fltr-brand-_-bar-find-html.html

应该映射到redirectController,但它映射到queryController。

如果我将第一个映射更改为

<prop key="/service/q-*-fltr-brand-_-bar-find-html.html">redirectController</prop>`
or
<prop key="/service/q-foo-fltr-brand-_-*-find-html.html">redirectController</prop>

映射工作正常。

在模式中使用两个单星适用于其他映射,所以这不是问题。我做错了什么?

感谢您的帮助!

【问题讨论】:

    标签: spring url-mapping


    【解决方案1】:

    几天前我遇到了a similar question。问题在于AntPatternComparator 用于对匹配路径的集合进行排序。

    在您的情况下,将您的路径从 /service/q-*.html 更改为 /service/q-**.html。这不是最有意义的,但它应该可以工作。


    如果您查看RequestMappingInfo.getMatchingCondition,获取当前请求的匹配条件的方法,您会看到以下注释,其中指出最佳匹配模式将在列表中排在第一位。

    Spring 4 源码

    /**
     * Checks if all conditions in this request mapping info match the provided request and returns
     * a potentially new request mapping info with conditions tailored to the current request.
     * <p>For example the returned instance may contain the subset of URL patterns that match to
     * the current request, sorted with best matching patterns on top.
     * @return a new instance in case all conditions match; or {@code null} otherwise
     */
    @Override
    public RequestMappingInfo getMatchingCondition(HttpServletRequest request) {
            // ...
    }
    

    AntPatternComparator 基本上取决于模式中存在的*{ 的数量。如果它们的数字相同,则将比较模式长度。当使用AntPatternComparator 对模式集合进行排序时,您的/service/q-foo-fltr-brand-_-*-find-html.html 路径将基于长度大于/service/q-*.html。所以/service/q-*.html 将在顶部结束。

    添加额外的通配符使/service/q-**.html 最大,因为它的通配符数量更多。

    【讨论】:

    • 它有效。但我也想知道为什么。我希望有人能回答这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2020-10-02
    • 2019-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-30
    相关资源
    最近更新 更多