Spring启动中/*和/**模式有什么区别?

ami*_*ion 7 pattern-matching spring-boot

当我注意到/*/**模式之间存在差异时,我试图为过滤器注册某些URL .

    @Bean
    public FilterRegistrationBean tokenAuthenticationFilterBean() {
        FilterRegistrationBean registration = new FilterRegistrationBean(tokenAuthenticationFilter);
        registration.addUrlPatterns("/api/**","/ping","/api/*");
        return registration;
    }
Run Code Online (Sandbox Code Playgroud)

这些模式有什么区别?

Lu5*_*u55 10

在这种情况下,恕我直言代码价值 100 字:

import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.springframework.util.AntPathMatcher

class AntPathMatcherTests {
    @Test
    fun twoAsterisks() {
        val pattern = "/api/balance/**"

        val matcher = AntPathMatcher()
        val matching = { path: String -> matcher.match(pattern, path) }

        assertTrue(matching("/api/balance"))
        assertTrue(matching("/api/balance/"))
        assertTrue(matching("/api/balance/abc"))
        assertTrue(matching("/api/balance/abc/"))
        assertTrue(matching("/api/balance/abc/update"))

        assertFalse(matching("/api/bala"))
    }

    @Test
    fun oneAsterisk() {
        val pattern = "/api/balance/*"

        val matcher = AntPathMatcher()
        val matching = { path: String -> matcher.match(pattern, path) }

        assertTrue(matching("/api/balance/"))
        assertTrue(matching("/api/balance/abc"))

        assertFalse(matching("/api/bala"))
        assertFalse(matching("/api/balance"))
        assertFalse(matching("/api/balance/abc/"))
        assertFalse(matching("/api/balance/abc/update"))
    }
}
Run Code Online (Sandbox Code Playgroud)


rhi*_*nds 9

Spring通常对URL使用ant风格的路径匹配模式 - 如果你查看AntPathMatcher的java文档,你会看到解释

The mapping matches URLs using the following rules: ? matches one character
* matches zero or more characters
** matches zero or more directories in a path 
{spring:[a-z]+} matches the regexp [a-z]+ as a path variable named "spring"
Run Code Online (Sandbox Code Playgroud)

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/util/AntPathMatcher.html