001/* 002 * Copyright 2002-2014 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.util.CollectionUtils; 025import org.springframework.util.StringUtils; 026import org.springframework.web.bind.annotation.PathVariable; 027import org.springframework.web.bind.support.WebDataBinderFactory; 028import org.springframework.web.context.request.NativeWebRequest; 029import org.springframework.web.context.request.RequestAttributes; 030import org.springframework.web.method.support.HandlerMethodArgumentResolver; 031import org.springframework.web.method.support.ModelAndViewContainer; 032import org.springframework.web.servlet.HandlerMapping; 033 034/** 035 * Resolves {@link Map} method arguments annotated with an @{@link PathVariable} 036 * where the annotation does not specify a path variable name. The created 037 * {@link Map} contains all URI template name/value pairs. 038 * 039 * @author Rossen Stoyanchev 040 * @since 3.2 041 * @see PathVariableMethodArgumentResolver 042 */ 043public class PathVariableMapMethodArgumentResolver implements HandlerMethodArgumentResolver { 044 045 @Override 046 public boolean supportsParameter(MethodParameter parameter) { 047 PathVariable ann = parameter.getParameterAnnotation(PathVariable.class); 048 return (ann != null && (Map.class.isAssignableFrom(parameter.getParameterType())) 049 && !StringUtils.hasText(ann.value())); 050 } 051 052 /** 053 * Return a Map with all URI template variables or an empty map. 054 */ 055 @Override 056 public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, 057 NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { 058 059 @SuppressWarnings("unchecked") 060 Map<String, String> uriTemplateVars = 061 (Map<String, String>) webRequest.getAttribute( 062 HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST); 063 064 if (!CollectionUtils.isEmpty(uriTemplateVars)) { 065 return new LinkedHashMap<String, String>(uriTemplateVars); 066 } 067 else { 068 return Collections.emptyMap(); 069 } 070 } 071 072}