RequestMappingHandlerMapping.java 15.1 KB
Newer Older
1
/*
2
 * Copyright 2002-2018 the original author or authors.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.web.servlet.mvc.method.annotation;

19
import java.lang.reflect.AnnotatedElement;
20
import java.lang.reflect.Method;
21 22
import java.util.Collections;
import java.util.LinkedHashMap;
23
import java.util.List;
24
import java.util.Map;
25
import java.util.Set;
26
import java.util.function.Predicate;
27
import javax.servlet.http.HttpServletRequest;
28

29
import org.springframework.context.EmbeddedValueResolverAware;
30
import org.springframework.core.annotation.AnnotatedElementUtils;
31
import org.springframework.lang.Nullable;
32
import org.springframework.stereotype.Controller;
33
import org.springframework.util.Assert;
S
Sebastien Deleuze 已提交
34
import org.springframework.util.CollectionUtils;
35
import org.springframework.util.StringUtils;
36
import org.springframework.util.StringValueResolver;
37
import org.springframework.web.accept.ContentNegotiationManager;
S
Sebastien Deleuze 已提交
38
import org.springframework.web.bind.annotation.CrossOrigin;
39
import org.springframework.web.bind.annotation.RequestMapping;
S
Sebastien Deleuze 已提交
40 41 42
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.method.HandlerMethod;
43 44
import org.springframework.web.servlet.handler.MatchableHandlerMapping;
import org.springframework.web.servlet.handler.RequestMatchResult;
45 46
import org.springframework.web.servlet.mvc.condition.AbstractRequestCondition;
import org.springframework.web.servlet.mvc.condition.CompositeRequestCondition;
47
import org.springframework.web.servlet.mvc.condition.RequestCondition;
48 49
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
50 51

/**
S
Stevo Slavic 已提交
52 53
 * Creates {@link RequestMappingInfo} instances from type and method-level
 * {@link RequestMapping @RequestMapping} annotations in
54
 * {@link Controller @Controller} classes.
55
 *
56 57
 * @author Arjen Poutsma
 * @author Rossen Stoyanchev
58
 * @author Sam Brannen
59
 * @since 3.1
60
 */
61
public class RequestMappingHandlerMapping extends RequestMappingInfoHandlerMapping
62
		implements MatchableHandlerMapping, EmbeddedValueResolverAware {
63

64 65
	private boolean useSuffixPatternMatch = true;

66 67
	private boolean useRegisteredSuffixPatternMatch = false;

68
	private boolean useTrailingSlashMatch = true;
69

70
	private final Map<String, Predicate<Class<?>>> pathPrefixes = new LinkedHashMap<>();
71

72 73
	private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();

74
	@Nullable
75 76
	private StringValueResolver embeddedValueResolver;

77 78
	private RequestMappingInfo.BuilderConfiguration config = new RequestMappingInfo.BuilderConfiguration();

79

80
	/**
81
	 * Whether to use suffix pattern match (".*") when matching patterns to
82
	 * requests. If enabled a method mapped to "/users" also matches to "/users.*".
S
Stevo Slavic 已提交
83
	 * <p>The default value is {@code true}.
84
	 * <p>Also see {@link #setUseRegisteredSuffixPatternMatch(boolean)} for
S
Sam Brannen 已提交
85
	 * more fine-grained control over specific suffixes to allow.
86 87 88 89
	 */
	public void setUseSuffixPatternMatch(boolean useSuffixPatternMatch) {
		this.useSuffixPatternMatch = useSuffixPatternMatch;
	}
90

91
	/**
R
Polish  
Rossen Stoyanchev 已提交
92 93 94 95 96
	 * Whether suffix pattern matching should work only against path extensions
	 * explicitly registered with the {@link ContentNegotiationManager}. This
	 * is generally recommended to reduce ambiguity and to avoid issues such as
	 * when a "." appears in the path for other reasons.
	 * <p>By default this is set to "false".
97
	 */
98 99
	public void setUseRegisteredSuffixPatternMatch(boolean useRegisteredSuffixPatternMatch) {
		this.useRegisteredSuffixPatternMatch = useRegisteredSuffixPatternMatch;
J
Juergen Hoeller 已提交
100
		this.useSuffixPatternMatch = (useRegisteredSuffixPatternMatch || this.useSuffixPatternMatch);
101 102
	}

103 104 105 106 107 108 109 110
	/**
	 * Whether to match to URLs irrespective of the presence of a trailing slash.
	 * If enabled a method mapped to "/users" also matches to "/users/".
	 * <p>The default value is {@code true}.
	 */
	public void setUseTrailingSlashMatch(boolean useTrailingSlashMatch) {
		this.useTrailingSlashMatch = useTrailingSlashMatch;
	}
111

112 113 114 115
	/**
	 * Configure path prefixes to apply to controller methods.
	 * <p>Prefixes are used to enrich the mappings of every {@code @RequestMapping}
	 * method whose controller type is matched by the corresponding
116 117 118
	 * {@code Predicate}. The prefix for the first matching predicate is used.
	 * <p>Consider using {@link org.springframework.web.method.HandlerTypePredicate
	 * HandlerTypePredicate} to group controllers.
119 120 121
	 * @param prefixes a map with path prefixes as key
	 * @since 5.1
	 */
122
	public void setPathPrefixes(Map<String, Predicate<Class<?>>> prefixes) {
123 124 125 126 127 128
		this.pathPrefixes.clear();
		prefixes.entrySet().stream()
				.filter(entry -> StringUtils.hasText(entry.getKey()))
				.forEach(entry -> this.pathPrefixes.put(entry.getKey(), entry.getValue()));
	}

129 130 131 132 133
	/**
	 * Set the {@link ContentNegotiationManager} to use to determine requested media types.
	 * If not set, the default constructor is used.
	 */
	public void setContentNegotiationManager(ContentNegotiationManager contentNegotiationManager) {
J
Juergen Hoeller 已提交
134
		Assert.notNull(contentNegotiationManager, "ContentNegotiationManager must not be null");
135 136 137
		this.contentNegotiationManager = contentNegotiationManager;
	}

J
Juergen Hoeller 已提交
138 139
	@Override
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
140
		this.embeddedValueResolver = resolver;
J
Juergen Hoeller 已提交
141 142 143 144
	}

	@Override
	public void afterPropertiesSet() {
145
		this.config = new RequestMappingInfo.BuilderConfiguration();
146
		this.config.setUrlPathHelper(getUrlPathHelper());
147 148 149 150 151
		this.config.setPathMatcher(getPathMatcher());
		this.config.setSuffixPatternMatch(this.useSuffixPatternMatch);
		this.config.setTrailingSlashMatch(this.useTrailingSlashMatch);
		this.config.setRegisteredSuffixPatternMatch(this.useRegisteredSuffixPatternMatch);
		this.config.setContentNegotiationManager(getContentNegotiationManager());
J
Juergen Hoeller 已提交
152

153 154
		super.afterPropertiesSet();
	}
J
Juergen Hoeller 已提交
155

J
Juergen Hoeller 已提交
156

157
	/**
158
	 * Whether to use suffix pattern matching.
159
	 */
160 161
	public boolean useSuffixPatternMatch() {
		return this.useSuffixPatternMatch;
162
	}
163 164 165 166 167

	/**
	 * Whether to use registered suffixes for pattern matching.
	 */
	public boolean useRegisteredSuffixPatternMatch() {
J
Juergen Hoeller 已提交
168
		return this.useRegisteredSuffixPatternMatch;
169 170
	}

171
	/**
J
Juergen Hoeller 已提交
172
	 * Whether to match to URLs irrespective of the presence of a trailing slash.
173 174 175 176
	 */
	public boolean useTrailingSlashMatch() {
		return this.useTrailingSlashMatch;
	}
177

178 179 180 181
	/**
	 * The configured path prefixes as a read-only, possibly empty map.
	 * @since 5.1
	 */
182
	public Map<String, Predicate<Class<?>>> getPathPrefixes() {
183 184 185
		return Collections.unmodifiableMap(this.pathPrefixes);
	}

186 187 188 189
	/**
	 * Return the configured {@link ContentNegotiationManager}.
	 */
	public ContentNegotiationManager getContentNegotiationManager() {
190 191 192 193
		return this.contentNegotiationManager;
	}

	/**
194
	 * Return the file extensions to use for suffix pattern matching.
195
	 */
196
	@Nullable
197
	public List<String> getFileExtensions() {
198
		return this.config.getFileExtensions();
199 200
	}

201

202
	/**
S
Stevo Slavic 已提交
203
	 * {@inheritDoc}
204 205
	 * <p>Expects a handler to have either a type-level @{@link Controller}
	 * annotation or a type-level @{@link RequestMapping} annotation.
206 207
	 */
	@Override
208
	protected boolean isHandler(Class<?> beanType) {
209 210
		return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
				AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
211 212 213
	}

	/**
214 215 216 217 218 219
	 * Uses method and type-level @{@link RequestMapping} annotations to create
	 * the RequestMappingInfo.
	 * @return the created RequestMappingInfo, or {@code null} if the method
	 * does not have a {@code @RequestMapping} annotation.
	 * @see #getCustomMethodCondition(Method)
	 * @see #getCustomTypeCondition(Class)
220 221
	 */
	@Override
222
	@Nullable
223
	protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
224 225 226 227 228
		RequestMappingInfo info = createRequestMappingInfo(method);
		if (info != null) {
			RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
			if (typeInfo != null) {
				info = typeInfo.combine(info);
229
			}
230
			for (Map.Entry<String, Predicate<Class<?>>> entry : this.pathPrefixes.entrySet()) {
231 232 233 234 235 236 237 238 239
				if (entry.getValue().test(handlerType)) {
					String prefix = entry.getKey();
					if (this.embeddedValueResolver != null) {
						prefix = this.embeddedValueResolver.resolveStringValue(prefix);
					}
					info = RequestMappingInfo.paths(prefix).build().combine(info);
					break;
				}
			}
240
		}
241 242 243
		return info;
	}

R
Polish  
Rossen Stoyanchev 已提交
244 245 246 247 248 249 250
	/**
	 * Delegates to {@link #createRequestMappingInfo(RequestMapping, RequestCondition)},
	 * supplying the appropriate custom {@link RequestCondition} depending on whether
	 * the supplied {@code annotatedElement} is a class or method.
	 * @see #getCustomTypeCondition(Class)
	 * @see #getCustomMethodCondition(Method)
	 */
251
	@Nullable
R
Polish  
Rossen Stoyanchev 已提交
252
	private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
253
		RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
254
		RequestCondition<?> condition = (element instanceof Class ?
J
Juergen Hoeller 已提交
255
				getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));
R
Polish  
Rossen Stoyanchev 已提交
256 257 258
		return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
	}

259
	/**
260
	 * Provide a custom type-level request condition.
S
Stevo Slavic 已提交
261
	 * The custom {@link RequestCondition} can be of any type so long as the
262
	 * same condition type is returned from all calls to this method in order
S
Stevo Slavic 已提交
263
	 * to ensure custom request conditions can be combined and compared.
264 265 266 267
	 * <p>Consider extending {@link AbstractRequestCondition} for custom
	 * condition types and using {@link CompositeRequestCondition} to provide
	 * multiple custom conditions.
	 * @param handlerType the handler type for which to create the condition
268 269
	 * @return the condition, or {@code null}
	 */
270
	@Nullable
271
	protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
272 273
		return null;
	}
274

275
	/**
276
	 * Provide a custom method-level request condition.
S
Stevo Slavic 已提交
277
	 * The custom {@link RequestCondition} can be of any type so long as the
278
	 * same condition type is returned from all calls to this method in order
S
Stevo Slavic 已提交
279
	 * to ensure custom request conditions can be combined and compared.
280 281 282 283
	 * <p>Consider extending {@link AbstractRequestCondition} for custom
	 * condition types and using {@link CompositeRequestCondition} to provide
	 * multiple custom conditions.
	 * @param method the handler method for which to create the condition
284 285
	 * @return the condition, or {@code null}
	 */
286
	@Nullable
287
	protected RequestCondition<?> getCustomMethodCondition(Method method) {
288
		return null;
289 290
	}

291
	/**
292 293 294 295
	 * Create a {@link RequestMappingInfo} from the supplied
	 * {@link RequestMapping @RequestMapping} annotation, which is either
	 * a directly declared annotation, a meta-annotation, or the synthesized
	 * result of merging annotation attributes within an annotation hierarchy.
296
	 */
J
Juergen Hoeller 已提交
297
	protected RequestMappingInfo createRequestMappingInfo(
298
			RequestMapping requestMapping, @Nullable RequestCondition<?> customCondition) {
299

300
		RequestMappingInfo.Builder builder = RequestMappingInfo
R
Polish  
Rossen Stoyanchev 已提交
301
				.paths(resolveEmbeddedValuesInPatterns(requestMapping.path()))
302 303 304 305 306
				.methods(requestMapping.method())
				.params(requestMapping.params())
				.headers(requestMapping.headers())
				.consumes(requestMapping.consumes())
				.produces(requestMapping.produces())
307 308 309 310 311
				.mappingName(requestMapping.name());
		if (customCondition != null) {
			builder.customCondition(customCondition);
		}
		return builder.options(this.config).build();
R
Rossen Stoyanchev 已提交
312
	}
313

314 315 316 317 318 319 320 321 322 323
	/**
	 * Resolve placeholder values in the given array of patterns.
	 * @return a new array with updated patterns
	 */
	protected String[] resolveEmbeddedValuesInPatterns(String[] patterns) {
		if (this.embeddedValueResolver == null) {
			return patterns;
		}
		else {
			String[] resolvedPatterns = new String[patterns.length];
J
Juergen Hoeller 已提交
324
			for (int i = 0; i < patterns.length; i++) {
325 326 327 328 329 330
				resolvedPatterns[i] = this.embeddedValueResolver.resolveStringValue(patterns[i]);
			}
			return resolvedPatterns;
		}
	}

331 332 333 334 335 336 337 338 339 340 341 342
	@Override
	public RequestMatchResult match(HttpServletRequest request, String pattern) {
		RequestMappingInfo info = RequestMappingInfo.paths(pattern).options(this.config).build();
		RequestMappingInfo matchingInfo = info.getMatchingCondition(request);
		if (matchingInfo == null) {
			return null;
		}
		Set<String> patterns = matchingInfo.getPatternsCondition().getPatterns();
		String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
		return new RequestMatchResult(patterns.iterator().next(), lookupPath, getPathMatcher());
	}

S
Sebastien Deleuze 已提交
343 344 345
	@Override
	protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
		HandlerMethod handlerMethod = createHandlerMethod(handler, method);
R
Rossen Stoyanchev 已提交
346 347
		Class<?> beanType = handlerMethod.getBeanType();
		CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class);
348
		CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);
S
Sebastien Deleuze 已提交
349

350 351 352
		if (typeAnnotation == null && methodAnnotation == null) {
			return null;
		}
S
Sebastien Deleuze 已提交
353

354
		CorsConfiguration config = new CorsConfiguration();
355 356
		updateCorsConfig(config, typeAnnotation);
		updateCorsConfig(config, methodAnnotation);
S
Sebastien Deleuze 已提交
357 358 359 360 361 362

		if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
			for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
				config.addAllowedMethod(allowedMethod.name());
			}
		}
R
Polish  
Rossen Stoyanchev 已提交
363
		return config.applyPermitDefaultValues();
S
Sebastien Deleuze 已提交
364 365
	}

366
	private void updateCorsConfig(CorsConfiguration config, @Nullable CrossOrigin annotation) {
S
Sebastien Deleuze 已提交
367 368 369
		if (annotation == null) {
			return;
		}
S
Sam Brannen 已提交
370
		for (String origin : annotation.origins()) {
371
			config.addAllowedOrigin(resolveCorsAnnotationValue(origin));
S
Sebastien Deleuze 已提交
372
		}
S
Sam Brannen 已提交
373
		for (RequestMethod method : annotation.methods()) {
S
Sebastien Deleuze 已提交
374 375 376
			config.addAllowedMethod(method.name());
		}
		for (String header : annotation.allowedHeaders()) {
377
			config.addAllowedHeader(resolveCorsAnnotationValue(header));
S
Sebastien Deleuze 已提交
378 379
		}
		for (String header : annotation.exposedHeaders()) {
380
			config.addExposedHeader(resolveCorsAnnotationValue(header));
S
Sebastien Deleuze 已提交
381
		}
382

383
		String allowCredentials = resolveCorsAnnotationValue(annotation.allowCredentials());
384
		if ("true".equalsIgnoreCase(allowCredentials)) {
S
Sebastien Deleuze 已提交
385 386
			config.setAllowCredentials(true);
		}
387
		else if ("false".equalsIgnoreCase(allowCredentials)) {
S
Sebastien Deleuze 已提交
388 389
			config.setAllowCredentials(false);
		}
390
		else if (!allowCredentials.isEmpty()) {
391 392
			throw new IllegalStateException("@CrossOrigin's allowCredentials value must be \"true\", \"false\", " +
					"or an empty string (\"\"): current value is [" + allowCredentials + "]");
S
Sebastien Deleuze 已提交
393
		}
394

J
Juergen Hoeller 已提交
395
		if (annotation.maxAge() >= 0 && config.getMaxAge() == null) {
S
Sebastien Deleuze 已提交
396 397 398 399
			config.setMaxAge(annotation.maxAge());
		}
	}

400
	private String resolveCorsAnnotationValue(String value) {
401 402 403 404 405 406 407
		if (this.embeddedValueResolver != null) {
			String resolved = this.embeddedValueResolver.resolveStringValue(value);
			return (resolved != null ? resolved : "");
		}
		else {
			return value;
		}
408 409
	}

410
}