下面列出了怎么用org.springframework.util.PathMatcher的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void customPathMatcher() {
ApplicationContext context = loadConfig(CustomConfig.class);
SimpleBrokerMessageHandler broker = context.getBean(SimpleBrokerMessageHandler.class);
DefaultSubscriptionRegistry registry = (DefaultSubscriptionRegistry) broker.getSubscriptionRegistry();
assertEquals("a.a", registry.getPathMatcher().combine("a", "a"));
PathMatcher pathMatcher =
context.getBean(SimpAnnotationMethodMessageHandler.class).getPathMatcher();
assertEquals("a.a", pathMatcher.combine("a", "a"));
DefaultUserDestinationResolver resolver = context.getBean(DefaultUserDestinationResolver.class);
assertNotNull(resolver);
assertEquals(false, resolver.isRemoveLeadingSlash());
}
/**
* Private constructor accepting a collection of patterns.
*/
private PatternsRequestCondition(Collection<String> patterns, @Nullable UrlPathHelper urlPathHelper,
@Nullable PathMatcher pathMatcher, boolean useSuffixPatternMatch,
boolean useTrailingSlashMatch, @Nullable List<String> fileExtensions) {
this.patterns = Collections.unmodifiableSet(prependLeadingSlash(patterns));
this.pathHelper = urlPathHelper != null ? urlPathHelper : new UrlPathHelper();
this.pathMatcher = pathMatcher != null ? pathMatcher : new AntPathMatcher();
this.useSuffixPatternMatch = useSuffixPatternMatch;
this.useTrailingSlashMatch = useTrailingSlashMatch;
if (fileExtensions != null) {
for (String fileExtension : fileExtensions) {
if (fileExtension.charAt(0) != '.') {
fileExtension = "." + fileExtension;
}
this.fileExtensions.add(fileExtension);
}
}
}
private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) {
PathMatcher pathMatcher = new AntPathMatcher();
List<HandlerInterceptor> result = new ArrayList<>();
for (Object interceptor : this.registry.getInterceptors()) {
if (interceptor instanceof MappedInterceptor) {
MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
if (mappedInterceptor.matches(lookupPath, pathMatcher)) {
result.add(mappedInterceptor.getInterceptor());
}
}
else if (interceptor instanceof HandlerInterceptor) {
result.add((HandlerInterceptor) interceptor);
}
else {
fail("Unexpected interceptor type: " + interceptor.getClass().getName());
}
}
return result;
}
@Override
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
if (configAttributeMap == null) this.loadDataSource();
List<ConfigAttribute> configAttributes = new ArrayList<>();
//获取当前访问的路径
String url = ((FilterInvocation) o).getRequestUrl();
String path = URLUtil.getPath(url);
PathMatcher pathMatcher = new AntPathMatcher();
Iterator<String> iterator = configAttributeMap.keySet().iterator();
//获取访问该路径所需资源
while (iterator.hasNext()) {
String pattern = iterator.next();
if (pathMatcher.match(pattern, path)) {
configAttributes.add(configAttributeMap.get(pattern));
}
}
// 未设置操作请求权限,返回空集合
return configAttributes;
}
/**
* Private constructor accepting a collection of patterns.
*/
private PatternsRequestCondition(Collection<String> patterns, UrlPathHelper urlPathHelper,
PathMatcher pathMatcher, boolean useSuffixPatternMatch, boolean useTrailingSlashMatch,
List<String> fileExtensions) {
this.patterns = Collections.unmodifiableSet(prependLeadingSlash(patterns));
this.pathHelper = (urlPathHelper != null ? urlPathHelper : new UrlPathHelper());
this.pathMatcher = (pathMatcher != null ? pathMatcher : new AntPathMatcher());
this.useSuffixPatternMatch = useSuffixPatternMatch;
this.useTrailingSlashMatch = useTrailingSlashMatch;
if (fileExtensions != null) {
for (String fileExtension : fileExtensions) {
if (fileExtension.charAt(0) != '.') {
fileExtension = "." + fileExtension;
}
this.fileExtensions.add(fileExtension);
}
}
}
@Bean
public SimpAnnotationMethodMessageHandler simpAnnotationMethodMessageHandler() {
SimpAnnotationMethodMessageHandler handler = createAnnotationMethodMessageHandler();
handler.setDestinationPrefixes(getBrokerRegistry().getApplicationDestinationPrefixes());
handler.setMessageConverter(brokerMessageConverter());
handler.setValidator(simpValidator());
List<HandlerMethodArgumentResolver> argumentResolvers = new ArrayList<>();
addArgumentResolvers(argumentResolvers);
handler.setCustomArgumentResolvers(argumentResolvers);
List<HandlerMethodReturnValueHandler> returnValueHandlers = new ArrayList<>();
addReturnValueHandlers(returnValueHandlers);
handler.setCustomReturnValueHandlers(returnValueHandlers);
PathMatcher pathMatcher = getBrokerRegistry().getPathMatcher();
if (pathMatcher != null) {
handler.setPathMatcher(pathMatcher);
}
return handler;
}
@Test
public void customPathMatcher() {
ApplicationContext context = loadConfig(CustomConfig.class);
SimpleBrokerMessageHandler broker = context.getBean(SimpleBrokerMessageHandler.class);
DefaultSubscriptionRegistry registry = (DefaultSubscriptionRegistry) broker.getSubscriptionRegistry();
assertEquals("a.a", registry.getPathMatcher().combine("a", "a"));
PathMatcher pathMatcher =
context.getBean(SimpAnnotationMethodMessageHandler.class).getPathMatcher();
assertEquals("a.a", pathMatcher.combine("a", "a"));
DefaultUserDestinationResolver resolver = context.getBean(DefaultUserDestinationResolver.class);
assertNotNull(resolver);
assertEquals(false, resolver.isRemoveLeadingSlash());
}
private List<HandlerInterceptor> getInterceptorsForPath(String lookupPath) {
PathMatcher pathMatcher = new AntPathMatcher();
List<HandlerInterceptor> result = new ArrayList<HandlerInterceptor>();
for (Object interceptor : this.registry.getInterceptors()) {
if (interceptor instanceof MappedInterceptor) {
MappedInterceptor mappedInterceptor = (MappedInterceptor) interceptor;
if (mappedInterceptor.matches(lookupPath, pathMatcher)) {
result.add(mappedInterceptor.getInterceptor());
}
}
else if (interceptor instanceof HandlerInterceptor) {
result.add((HandlerInterceptor) interceptor);
}
else {
fail("Unexpected interceptor type: " + interceptor.getClass().getName());
}
}
return result;
}
@Autowired
@Qualifier("simpleBrokerMessageHandler")
public void onSimpleBrockedMessageChannel(AbstractBrokerMessageHandler handler) {
// here we try to inherit matcher from subscription registry
if (!(handler instanceof SimpleBrokerMessageHandler)) {
return;
}
SubscriptionRegistry registry = ((SimpleBrokerMessageHandler) handler).getSubscriptionRegistry();
if (!(registry instanceof DefaultSubscriptionRegistry)) {
return;
}
PathMatcher pathMatcher = ((DefaultSubscriptionRegistry) registry).getPathMatcher();
if(pathMatcher != null) {
this.pathMatcher = pathMatcher;
}
}
/**
* Set the PathMatcher implementation to use for matching URL paths
* against registered URL patterns. Default is AntPathMatcher.
* @see org.springframework.util.AntPathMatcher
*/
public void setPathMatcher(PathMatcher pathMatcher) {
Assert.notNull(pathMatcher, "PathMatcher must not be null");
this.pathMatcher = pathMatcher;
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) {
((UrlBasedCorsConfigurationSource)this.corsConfigurationSource).setPathMatcher(pathMatcher);
}
}
private boolean isAllowed(String resourcePath) {
if (resourcePath.matches(PROTECTED_PATH)) {
return false;
}
PathMatcher pathMatcher = new AntPathMatcher();
for (String pattern : allowedResourcePaths) {
if (pathMatcher.match(pattern, resourcePath)) {
return true;
}
}
return false;
}
@Bean
public ResourceUrlProvider mvcResourceUrlProvider() {
ResourceUrlProvider urlProvider = new ResourceUrlProvider();
UrlPathHelper pathHelper = getPathMatchConfigurer().getUrlPathHelper();
if (pathHelper != null) {
urlProvider.setUrlPathHelper(pathHelper);
}
PathMatcher pathMatcher = getPathMatchConfigurer().getPathMatcher();
if (pathMatcher != null) {
urlProvider.setPathMatcher(pathMatcher);
}
return urlProvider;
}
public static Set<Resource> findMatchingResources(
URL rootDirURL, String locationPattern, PathMatcher pathMatcher) throws IOException {
Object root = VfsPatternUtils.findRoot(rootDirURL);
PatternVirtualFileVisitor visitor =
new PatternVirtualFileVisitor(VfsPatternUtils.getPath(root), locationPattern, pathMatcher);
VfsPatternUtils.visit(root, visitor);
return visitor.getResources();
}
/**
* Create an instance with a matching pattern.
* @param matchingPattern the matching pattern, possibly not the same as the
* input pattern, e.g. inputPattern="/foo" and matchingPattern="/foo/".
* @param lookupPath the lookup path extracted from the request
* @param pathMatcher the PathMatcher used
*/
public RequestMatchResult(String matchingPattern, String lookupPath, PathMatcher pathMatcher) {
Assert.hasText(matchingPattern, "'matchingPattern' is required");
Assert.hasText(lookupPath, "'lookupPath' is required");
Assert.notNull(pathMatcher, "'pathMatcher' is required");
this.matchingPattern = matchingPattern;
this.lookupPath = lookupPath;
this.pathMatcher = pathMatcher;
}
/**
* A {@link ResourceUrlProvider} bean for use with the MVC dispatcher.
* @since 4.1
*/
@Bean
public ResourceUrlProvider mvcResourceUrlProvider() {
ResourceUrlProvider urlProvider = new ResourceUrlProvider();
UrlPathHelper pathHelper = getPathMatchConfigurer().getUrlPathHelper();
if (pathHelper != null) {
urlProvider.setUrlPathHelper(pathHelper);
}
PathMatcher pathMatcher = getPathMatchConfigurer().getPathMatcher();
if (pathMatcher != null) {
urlProvider.setPathMatcher(pathMatcher);
}
return urlProvider;
}
/**
* Set the PathMatcher implementation to use for matching URL paths
* against registered URL patterns. Default is AntPathMatcher.
* @see org.springframework.util.AntPathMatcher
*/
public void setPathMatcher(PathMatcher pathMatcher) {
Assert.notNull(pathMatcher, "PathMatcher must not be null");
this.pathMatcher = pathMatcher;
if (this.corsConfigurationSource instanceof UrlBasedCorsConfigurationSource) {
((UrlBasedCorsConfigurationSource) this.corsConfigurationSource).setPathMatcher(pathMatcher);
}
}
@Test
public void addInterceptorsWithCustomPathMatcher() {
PathMatcher pathMatcher = Mockito.mock(PathMatcher.class);
this.registry.addInterceptor(interceptor1).addPathPatterns("/path1/**").pathMatcher(pathMatcher);
MappedInterceptor mappedInterceptor = (MappedInterceptor) this.registry.getInterceptors().get(0);
assertSame(pathMatcher, mappedInterceptor.getPathMatcher());
}
/**
* A {@link ResourceUrlProvider} bean for use with the MVC dispatcher.
* @since 4.1
*/
@Bean
public ResourceUrlProvider mvcResourceUrlProvider() {
ResourceUrlProvider urlProvider = new ResourceUrlProvider();
UrlPathHelper pathHelper = getPathMatchConfigurer().getUrlPathHelper();
if (pathHelper != null) {
urlProvider.setUrlPathHelper(pathHelper);
}
PathMatcher pathMatcher = getPathMatchConfigurer().getPathMatcher();
if (pathMatcher != null) {
urlProvider.setPathMatcher(pathMatcher);
}
return urlProvider;
}
@Test
public void configurePathMatch() throws Exception {
final PathMatcher pathMatcher = mock(PathMatcher.class);
final UrlPathHelper pathHelper = mock(UrlPathHelper.class);
List<WebMvcConfigurer> configurers = new ArrayList<>();
configurers.add(new WebMvcConfigurer() {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseRegisteredSuffixPatternMatch(true)
.setUseTrailingSlashMatch(false)
.setUrlPathHelper(pathHelper)
.setPathMatcher(pathMatcher);
}
});
delegatingConfig.setConfigurers(configurers);
RequestMappingHandlerMapping handlerMapping = delegatingConfig.requestMappingHandlerMapping();
assertNotNull(handlerMapping);
assertEquals("PathMatchConfigurer should configure RegisteredSuffixPatternMatch",
true, handlerMapping.useRegisteredSuffixPatternMatch());
assertEquals("PathMatchConfigurer should configure SuffixPatternMatch",
true, handlerMapping.useSuffixPatternMatch());
assertEquals("PathMatchConfigurer should configure TrailingSlashMatch",
false, handlerMapping.useTrailingSlashMatch());
assertEquals("PathMatchConfigurer should configure UrlPathHelper",
pathHelper, handlerMapping.getUrlPathHelper());
assertEquals("PathMatchConfigurer should configure PathMatcher",
pathMatcher, handlerMapping.getPathMatcher());
}
@Test
public void configurePathMatch() throws Exception {
final PathMatcher pathMatcher = mock(PathMatcher.class);
final UrlPathHelper pathHelper = mock(UrlPathHelper.class);
List<WebMvcConfigurer> configurers = new ArrayList<>();
configurers.add(new WebMvcConfigurer() {
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseRegisteredSuffixPatternMatch(true)
.setUseTrailingSlashMatch(false)
.setUrlPathHelper(pathHelper)
.setPathMatcher(pathMatcher);
}
});
delegatingConfig.setConfigurers(configurers);
RequestMappingHandlerMapping handlerMapping = delegatingConfig.requestMappingHandlerMapping(
delegatingConfig.mvcContentNegotiationManager(), delegatingConfig.mvcConversionService(),
delegatingConfig.mvcResourceUrlProvider());
assertNotNull(handlerMapping);
assertEquals("PathMatchConfigurer should configure RegisteredSuffixPatternMatch",
true, handlerMapping.useRegisteredSuffixPatternMatch());
assertEquals("PathMatchConfigurer should configure SuffixPatternMatch",
true, handlerMapping.useSuffixPatternMatch());
assertEquals("PathMatchConfigurer should configure TrailingSlashMatch",
false, handlerMapping.useTrailingSlashMatch());
assertEquals("PathMatchConfigurer should configure UrlPathHelper",
pathHelper, handlerMapping.getUrlPathHelper());
assertEquals("PathMatchConfigurer should configure PathMatcher",
pathMatcher, handlerMapping.getPathMatcher());
}
@BusPathMatcher
// There is a @Bean of type PathMatcher coming from Spring MVC
@ConditionalOnMissingBean(name = BusAutoConfiguration.BUS_PATH_MATCHER_NAME)
@Bean(name = BusAutoConfiguration.BUS_PATH_MATCHER_NAME)
public PathMatcher busPathMatcher() {
return new DefaultBusPathMatcher(new AntPathMatcher(":"));
}
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
BlogLanguage blogLanguage = (BlogLanguage) request.getAttribute(BlogLanguageMethodArgumentResolver.BLOG_LANGUAGE_ATTRIBUTE);
if (blogLanguage == null) {
Blog blog = blogService.getBlogById(Blog.DEFAULT_ID);
blogLanguage = blog.getLanguage(blog.getDefaultLanguage());
}
String path = urlPathHelper.getLookupPathForRequest(request);
PathMatcher pathMatcher = new AntPathMatcher();
if (!pathMatcher.match(PATH_PATTERN, path)) {
throw new HttpNotFoundException();
}
Map<String, String> variables = pathMatcher.extractUriTemplateVariables(PATH_PATTERN, path);
request.setAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, variables);
Page page = pageService.getPageByCode(variables.get("code"), blogLanguage.getLanguage());
if (page == null) {
page = pageService.getPageByCode(variables.get("code"), blogLanguage.getBlog().getDefaultLanguage());
}
if (page == null) {
throw new HttpNotFoundException();
}
if (page.getStatus() != Post.Status.PUBLISHED) {
throw new HttpNotFoundException();
}
return createModelAndView(page);
}
public static Set<Resource> findMatchingResources(
URL rootDirURL, String locationPattern, PathMatcher pathMatcher) throws IOException {
Object root = VfsPatternUtils.findRoot(rootDirURL);
PatternVirtualFileVisitor visitor =
new PatternVirtualFileVisitor(VfsPatternUtils.getPath(root), locationPattern, pathMatcher);
VfsPatternUtils.visit(root, visitor);
return visitor.getResources();
}
private static Set<String> prependLeadingSlash(Collection<String> patterns, PathMatcher pathMatcher) {
boolean slashSeparator = pathMatcher.combine("a", "a").equals("a/a");
Set<String> result = new LinkedHashSet<>(patterns.size());
for (String pattern : patterns) {
if (slashSeparator && StringUtils.hasLength(pattern) && !pattern.startsWith("/")) {
pattern = "/" + pattern;
}
result.add(pattern);
}
return result;
}
/**
* Set the PathMatcher implementation to use for matching destinations
* against configured destination patterns.
* <p>By default, {@link AntPathMatcher} is used.
*/
public void setPathMatcher(PathMatcher pathMatcher) {
Assert.notNull(pathMatcher, "PathMatcher must not be null");
this.pathMatcher = pathMatcher;
this.slashPathSeparator = this.pathMatcher.combine("a", "a").equals("a/a");
}
/**
* Return the configured {@link PathMatcher}.
*/
public PathMatcher getPathMatcher() {
return this.pathMatcher;
}
/**
* Set the PathMatcher implementation to use for matching URL paths against registered URL patterns.
* <p>Default is {@link org.springframework.util.AntPathMatcher}.
*/
public void setPathMatcher(PathMatcher pathMatcher) {
Assert.notNull(pathMatcher, "PathMatcher must not be null");
this.pathMatcher = pathMatcher;
}
@Bean
public PathMatcher antPathMatcher() {
//...
return null;
}
/**
* Return the PathMatcher that this resource pattern resolver uses.
*/
public PathMatcher getPathMatcher() {
return this.pathMatcher;
}
private DestinationPatternsMessageCondition(Collection<String> patterns, @Nullable PathMatcher pathMatcher) {
this.pathMatcher = (pathMatcher != null ? pathMatcher : new AntPathMatcher());
this.patterns = Collections.unmodifiableSet(prependLeadingSlash(patterns, this.pathMatcher));
}