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.StringValueResolver;
36
import org.springframework.web.accept.ContentNegotiationManager;
S
Sebastien Deleuze 已提交
37
import org.springframework.web.bind.annotation.CrossOrigin;
38
import org.springframework.web.bind.annotation.RequestMapping;
S
Sebastien Deleuze 已提交
39 40 41
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.method.HandlerMethod;
42 43
import org.springframework.web.servlet.handler.MatchableHandlerMapping;
import org.springframework.web.servlet.handler.RequestMatchResult;
44 45
import org.springframework.web.servlet.mvc.condition.AbstractRequestCondition;
import org.springframework.web.servlet.mvc.condition.CompositeRequestCondition;
46
import org.springframework.web.servlet.mvc.condition.RequestCondition;
47 48
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
49 50

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

63 64
	private boolean useSuffixPatternMatch = true;

65 66
	private boolean useRegisteredSuffixPatternMatch = false;

67
	private boolean useTrailingSlashMatch = true;
68

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

71 72
	private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();

73
	@Nullable
74 75
	private StringValueResolver embeddedValueResolver;

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

78

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

90
	/**
R
Polish  
Rossen Stoyanchev 已提交
91 92 93 94 95
	 * 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".
96
	 */
97 98
	public void setUseRegisteredSuffixPatternMatch(boolean useRegisteredSuffixPatternMatch) {
		this.useRegisteredSuffixPatternMatch = useRegisteredSuffixPatternMatch;
J
Juergen Hoeller 已提交
99
		this.useSuffixPatternMatch = (useRegisteredSuffixPatternMatch || this.useSuffixPatternMatch);
100 101
	}

102 103 104 105 106 107 108 109
	/**
	 * 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;
	}
110

111 112 113 114
	/**
	 * 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
115 116 117
	 * {@code Predicate}. The prefix for the first matching predicate is used.
	 * <p>Consider using {@link org.springframework.web.method.HandlerTypePredicate
	 * HandlerTypePredicate} to group controllers.
118 119 120
	 * @param prefixes a map with path prefixes as key
	 * @since 5.1
	 */
121
	public void setPathPrefixes(Map<String, Predicate<Class<?>>> prefixes) {
122
		this.pathPrefixes = Collections.unmodifiableMap(new LinkedHashMap<>(prefixes));
123 124
	}

125 126 127 128 129
	/**
	 * 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 已提交
130
		Assert.notNull(contentNegotiationManager, "ContentNegotiationManager must not be null");
131 132 133
		this.contentNegotiationManager = contentNegotiationManager;
	}

J
Juergen Hoeller 已提交
134 135
	@Override
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
136
		this.embeddedValueResolver = resolver;
J
Juergen Hoeller 已提交
137 138 139 140
	}

	@Override
	public void afterPropertiesSet() {
141
		this.config = new RequestMappingInfo.BuilderConfiguration();
142
		this.config.setUrlPathHelper(getUrlPathHelper());
143 144 145 146 147
		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 已提交
148

149 150
		super.afterPropertiesSet();
	}
J
Juergen Hoeller 已提交
151

J
Juergen Hoeller 已提交
152

153
	/**
154
	 * Whether to use suffix pattern matching.
155
	 */
156 157
	public boolean useSuffixPatternMatch() {
		return this.useSuffixPatternMatch;
158
	}
159 160 161 162 163

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

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

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

182 183 184 185
	/**
	 * Return the configured {@link ContentNegotiationManager}.
	 */
	public ContentNegotiationManager getContentNegotiationManager() {
186 187 188 189
		return this.contentNegotiationManager;
	}

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

197

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

	/**
210 211 212 213 214 215
	 * 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)
216 217
	 */
	@Override
218
	@Nullable
219
	protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
220 221 222 223 224
		RequestMappingInfo info = createRequestMappingInfo(method);
		if (info != null) {
			RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
			if (typeInfo != null) {
				info = typeInfo.combine(info);
225
			}
226 227 228
			String prefix = getPathPrefix(handlerType);
			if (prefix != null) {
				info = RequestMappingInfo.paths(prefix).build().combine(info);
229
			}
230
		}
231 232 233
		return info;
	}

234 235 236 237 238 239 240 241 242 243 244 245 246 247
	@Nullable
	String getPathPrefix(Class<?> handlerType) {
		for (Map.Entry<String, Predicate<Class<?>>> entry : this.pathPrefixes.entrySet()) {
			if (entry.getValue().test(handlerType)) {
				String prefix = entry.getKey();
				if (this.embeddedValueResolver != null) {
					prefix = this.embeddedValueResolver.resolveStringValue(prefix);
				}
				return prefix;
			}
		}
		return null;
	}

R
Polish  
Rossen Stoyanchev 已提交
248 249 250 251 252 253 254
	/**
	 * 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)
	 */
255
	@Nullable
R
Polish  
Rossen Stoyanchev 已提交
256
	private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
257
		RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
258
		RequestCondition<?> condition = (element instanceof Class ?
J
Juergen Hoeller 已提交
259
				getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));
R
Polish  
Rossen Stoyanchev 已提交
260 261 262
		return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
	}

263
	/**
264
	 * Provide a custom type-level request condition.
S
Stevo Slavic 已提交
265
	 * The custom {@link RequestCondition} can be of any type so long as the
266
	 * same condition type is returned from all calls to this method in order
S
Stevo Slavic 已提交
267
	 * to ensure custom request conditions can be combined and compared.
268 269 270 271
	 * <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
272 273
	 * @return the condition, or {@code null}
	 */
274
	@Nullable
275
	protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
276 277
		return null;
	}
278

279
	/**
280
	 * Provide a custom method-level request condition.
S
Stevo Slavic 已提交
281
	 * The custom {@link RequestCondition} can be of any type so long as the
282
	 * same condition type is returned from all calls to this method in order
S
Stevo Slavic 已提交
283
	 * to ensure custom request conditions can be combined and compared.
284 285 286 287
	 * <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
288 289
	 * @return the condition, or {@code null}
	 */
290
	@Nullable
291
	protected RequestCondition<?> getCustomMethodCondition(Method method) {
292
		return null;
293 294
	}

295
	/**
296 297 298 299
	 * 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.
300
	 */
J
Juergen Hoeller 已提交
301
	protected RequestMappingInfo createRequestMappingInfo(
302
			RequestMapping requestMapping, @Nullable RequestCondition<?> customCondition) {
303

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

318 319 320 321 322 323 324 325 326 327
	/**
	 * 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 已提交
328
			for (int i = 0; i < patterns.length; i++) {
329 330 331 332 333 334
				resolvedPatterns[i] = this.embeddedValueResolver.resolveStringValue(patterns[i]);
			}
			return resolvedPatterns;
		}
	}

335 336 337 338 339 340 341 342 343 344 345 346
	@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 已提交
347 348 349
	@Override
	protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
		HandlerMethod handlerMethod = createHandlerMethod(handler, method);
R
Rossen Stoyanchev 已提交
350 351
		Class<?> beanType = handlerMethod.getBeanType();
		CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class);
352
		CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);
S
Sebastien Deleuze 已提交
353

354 355 356
		if (typeAnnotation == null && methodAnnotation == null) {
			return null;
		}
S
Sebastien Deleuze 已提交
357

358
		CorsConfiguration config = new CorsConfiguration();
359 360
		updateCorsConfig(config, typeAnnotation);
		updateCorsConfig(config, methodAnnotation);
S
Sebastien Deleuze 已提交
361 362 363 364 365 366

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

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

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

J
Juergen Hoeller 已提交
399
		if (annotation.maxAge() >= 0 && config.getMaxAge() == null) {
S
Sebastien Deleuze 已提交
400 401 402 403
			config.setMaxAge(annotation.maxAge());
		}
	}

404
	private String resolveCorsAnnotationValue(String value) {
405 406 407 408 409 410 411
		if (this.embeddedValueResolver != null) {
			String resolved = this.embeddedValueResolver.resolveStringValue(value);
			return (resolved != null ? resolved : "");
		}
		else {
			return value;
		}
412 413
	}

414
}