001/* 002 * Copyright 2002-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * https://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.web.servlet.mvc.method.annotation; 018 019import java.util.Collections; 020import java.util.LinkedHashMap; 021import java.util.Map; 022 023import org.springframework.core.MethodParameter; 024import org.springframework.lang.Nullable; 025import org.springframework.util.CollectionUtils; 026import org.springframework.util.StringUtils; 027import org.springframework.web.bind.annotation.PathVariable; 028import org.springframework.web.bind.support.WebDataBinderFactory; 029import org.springframework.web.context.request.NativeWebRequest; 030import org.springframework.web.context.request.RequestAttributes; 031import org.springframework.web.method.support.HandlerMethodArgumentResolver; 032import org.springframework.web.method.support.ModelAndViewContainer; 033import org.springframework.web.servlet.HandlerMapping; 034 035/** 036 * Resolves {@link Map} method arguments annotated with an @{@link PathVariable} 037 * where the annotation does not specify a path variable name. The created 038 * {@link Map} contains all URI template name/value pairs. 039 * 040 * @author Rossen Stoyanchev 041 * @since 3.2 042 * @see PathVariableMethodArgumentResolver 043 */ 044public class PathVariableMapMethodArgumentResolver implements HandlerMethodArgumentResolver { 045 046 @Override 047 public boolean supportsParameter(MethodParameter parameter) { 048 PathVariable ann = parameter.getParameterAnnotation(PathVariable.class); 049 return (ann != null && Map.class.isAssignableFrom(parameter.getParameterType()) && 050 !StringUtils.hasText(ann.value())); 051 } 052 053 /** 054 * Return a Map with all URI template variables or an empty map. 055 */ 056 @Override 057 public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer, 058 NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception { 059 060 @SuppressWarnings("unchecked") 061 Map<String, String> uriTemplateVars = 062 (Map<String, String>) webRequest.getAttribute( 063 HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); 064 065 if (!CollectionUtils.isEmpty(uriTemplateVars)) { 066 return new LinkedHashMap<>(uriTemplateVars); 067 } 068 else { 069 return Collections.emptyMap(); 070 } 071 } 072 073}