mvc matcher and mvc mapping handler do not work the same

Viewed 25

Doesn't spring handler mapping use spring HandlerMappingIntrospector to match received urls? So why doesn't mvc macther, which itself uses this class, work like handler mapping? For example, in @RequestMapping, you can not put / before the address and the program will work correctly. But in mvc matcher, if we do not put / before the address, that page will not be secured. Why?

@RequestMapping("contact") // it works

but:

http.csrf().disable()
                .authorizeRequests()
                .mvcMatchers("contact").authenticated() //if we do not put / at the first of the home it does not recohnize the address
1 Answers

When building the RequestMappingInfo, "/" is automatically prepended to the path when parsing the path in the PathPatternsRequestCondition constructor if not specified "/" by the user. The source code is as follows:

public PathPatternsRequestCondition(PathPatternParser parser, String... patterns) {
    this(parse(parser, patterns));
}

private static SortedSet<PathPattern> parse(PathPatternParser parser, String... patterns) {
    if (patterns.length == 0 || (patterns.length == 1 && !StringUtils.hasText(patterns[0]))) {
        return EMPTY_PATH_PATTERN;
    }
    SortedSet<PathPattern> result = new TreeSet<>();
    for (String path : patterns) {
        if (StringUtils.hasText(path) && !path.startsWith("/")) {
            path = "/" + path;
        }
        result.add(parser.parse(path));
    }
    return result;
}

This will result in "/contact“ not matching "contact”

Related