Spring Boot 判断 URL 地址是否匹配 Controller 路径

Spring Boot About 2,160 words

PathMatcher

match方法第一个参数是Controller的地址,第二个参数是需要匹配的URL地址,可以是指定的字符串或者请求的地址。

@Controller
public class TestController {

    @Resource
    private PathMatcher pathMatcher;

    @GetMapping("/")
    public boolean match(HttpServletRequest request) {
        boolean result = pathMatcher.match("/p/{id}.html", request.getRequestURI());
        return result;
    }

}

PathPatternParser

parse方法接收Controller的地址,matches方法接收PathContainer对象,PathContainer对象的parsePath方法接收需要匹配的URL地址。

public class TestController {

    @Resource
    private PathPatternParser pathPatternParser;

    @GetMapping("/")
    public boolean match(HttpServletRequest request) {
        boolean result = pathPatternParser.parse(Endpoint.Portal.POST).matches(PathContainer.parsePath(request.getRequestURI()));
        return result;
    }

}

源码

public class WebMvcConfigurationSupport implements ApplicationContextAware, ServletContextAware {

    /**
     * Return a global {@link PathMatcher} instance which is used for URL path
     * matching with String patterns. The returned instance can be configured
     * using {@link #configurePathMatch(PathMatchConfigurer)}.
     * <p><b>Note:</b> This is only used when parsed patterns are not
     * {@link PathMatchConfigurer#setPatternParser enabled}.
     * @since 4.1
     */
    @Bean
    public PathMatcher mvcPathMatcher() {
        return getPathMatchConfigurer().getPathMatcherOrDefault();
    }

    /**
     * Return a global {@link PathPatternParser} instance to use for parsing
     * patterns to match to the {@link org.springframework.http.server.RequestPath}.
     * The returned instance can be configured using
     * {@link #configurePathMatch(PathMatchConfigurer)}.
     * @since 5.3.4
     */
    @Bean
    public PathPatternParser mvcPatternParser() {
        return getPathMatchConfigurer().getPatternParserOrDefault();
    }

}

public interface PathMatcher {

    boolean match(String pattern, String path);

}

public class PathPatternParser {

    public PathPattern parse(String pathPattern) throws PatternParseException {
        return new InternalPathPatternParser(this).parse(pathPattern);
    }

}
Views: 591 · Posted: 2024-03-29

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh