RequestMappingHandlerMapping.java 13.5 KB
Newer Older
1
/*
2
 * Copyright 2002-2017 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
import java.util.List;
22 23
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
24

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

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

59 60
	private boolean useSuffixPatternMatch = true;

61 62
	private boolean useRegisteredSuffixPatternMatch = false;

63
	private boolean useTrailingSlashMatch = true;
64

65 66
	private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();

67
	@Nullable
68 69
	private StringValueResolver embeddedValueResolver;

70 71
	private RequestMappingInfo.BuilderConfiguration config = new RequestMappingInfo.BuilderConfiguration();

72

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

84
	/**
R
Polish  
Rossen Stoyanchev 已提交
85 86 87 88 89
	 * 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".
90
	 */
91 92
	public void setUseRegisteredSuffixPatternMatch(boolean useRegisteredSuffixPatternMatch) {
		this.useRegisteredSuffixPatternMatch = useRegisteredSuffixPatternMatch;
J
Juergen Hoeller 已提交
93
		this.useSuffixPatternMatch = (useRegisteredSuffixPatternMatch || this.useSuffixPatternMatch);
94 95
	}

96 97 98 99 100 101 102 103
	/**
	 * 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;
	}
104

105 106 107 108 109
	/**
	 * 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 已提交
110
		Assert.notNull(contentNegotiationManager, "ContentNegotiationManager must not be null");
111 112 113
		this.contentNegotiationManager = contentNegotiationManager;
	}

J
Juergen Hoeller 已提交
114 115
	@Override
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
116
		this.embeddedValueResolver = resolver;
J
Juergen Hoeller 已提交
117 118 119 120
	}

	@Override
	public void afterPropertiesSet() {
121
		this.config = new RequestMappingInfo.BuilderConfiguration();
122
		this.config.setUrlPathHelper(getUrlPathHelper());
123 124 125 126 127
		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 已提交
128

129 130
		super.afterPropertiesSet();
	}
J
Juergen Hoeller 已提交
131

J
Juergen Hoeller 已提交
132

133
	/**
134
	 * Whether to use suffix pattern matching.
135
	 */
136 137
	public boolean useSuffixPatternMatch() {
		return this.useSuffixPatternMatch;
138
	}
139 140 141 142 143

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

147
	/**
J
Juergen Hoeller 已提交
148
	 * Whether to match to URLs irrespective of the presence of a trailing slash.
149 150 151 152
	 */
	public boolean useTrailingSlashMatch() {
		return this.useTrailingSlashMatch;
	}
153

154 155 156 157
	/**
	 * Return the configured {@link ContentNegotiationManager}.
	 */
	public ContentNegotiationManager getContentNegotiationManager() {
158 159 160 161
		return this.contentNegotiationManager;
	}

	/**
162
	 * Return the file extensions to use for suffix pattern matching.
163
	 */
164
	@Nullable
165
	public List<String> getFileExtensions() {
166
		return this.config.getFileExtensions();
167 168
	}

169

170
	/**
S
Stevo Slavic 已提交
171
	 * {@inheritDoc}
172 173
	 * <p>Expects a handler to have either a type-level @{@link Controller}
	 * annotation or a type-level @{@link RequestMapping} annotation.
174 175
	 */
	@Override
176
	protected boolean isHandler(Class<?> beanType) {
177 178
		return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
				AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
179 180 181
	}

	/**
182 183 184 185 186 187
	 * 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)
188 189
	 */
	@Override
190
	@Nullable
191
	protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
192 193 194 195 196
		RequestMappingInfo info = createRequestMappingInfo(method);
		if (info != null) {
			RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
			if (typeInfo != null) {
				info = typeInfo.combine(info);
197
			}
198
		}
199 200 201
		return info;
	}

R
Polish  
Rossen Stoyanchev 已提交
202 203 204 205 206 207 208
	/**
	 * 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)
	 */
209
	@Nullable
R
Polish  
Rossen Stoyanchev 已提交
210
	private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
211
		RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
212
		RequestCondition<?> condition = (element instanceof Class ?
J
Juergen Hoeller 已提交
213
				getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));
R
Polish  
Rossen Stoyanchev 已提交
214 215 216
		return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
	}

217
	/**
218
	 * Provide a custom type-level request condition.
S
Stevo Slavic 已提交
219
	 * The custom {@link RequestCondition} can be of any type so long as the
220
	 * same condition type is returned from all calls to this method in order
S
Stevo Slavic 已提交
221
	 * to ensure custom request conditions can be combined and compared.
222 223 224 225
	 * <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
226 227
	 * @return the condition, or {@code null}
	 */
228
	@Nullable
229
	protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
230 231
		return null;
	}
232

233
	/**
234
	 * Provide a custom method-level request condition.
S
Stevo Slavic 已提交
235
	 * The custom {@link RequestCondition} can be of any type so long as the
236
	 * same condition type is returned from all calls to this method in order
S
Stevo Slavic 已提交
237
	 * to ensure custom request conditions can be combined and compared.
238 239 240 241
	 * <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
242 243
	 * @return the condition, or {@code null}
	 */
244
	@Nullable
245
	protected RequestCondition<?> getCustomMethodCondition(Method method) {
246
		return null;
247 248
	}

249
	/**
250 251 252 253
	 * 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.
254
	 */
J
Juergen Hoeller 已提交
255
	protected RequestMappingInfo createRequestMappingInfo(
256
			RequestMapping requestMapping, @Nullable RequestCondition<?> customCondition) {
257

258
		RequestMappingInfo.Builder builder = RequestMappingInfo
R
Polish  
Rossen Stoyanchev 已提交
259
				.paths(resolveEmbeddedValuesInPatterns(requestMapping.path()))
260 261 262 263 264
				.methods(requestMapping.method())
				.params(requestMapping.params())
				.headers(requestMapping.headers())
				.consumes(requestMapping.consumes())
				.produces(requestMapping.produces())
265 266 267 268 269
				.mappingName(requestMapping.name());
		if (customCondition != null) {
			builder.customCondition(customCondition);
		}
		return builder.options(this.config).build();
R
Rossen Stoyanchev 已提交
270
	}
271

272 273 274 275 276 277 278 279 280 281
	/**
	 * 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 已提交
282
			for (int i = 0; i < patterns.length; i++) {
283 284 285 286 287 288
				resolvedPatterns[i] = this.embeddedValueResolver.resolveStringValue(patterns[i]);
			}
			return resolvedPatterns;
		}
	}

289 290 291 292 293 294 295 296 297 298 299 300
	@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 已提交
301 302 303
	@Override
	protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
		HandlerMethod handlerMethod = createHandlerMethod(handler, method);
R
Rossen Stoyanchev 已提交
304 305
		Class<?> beanType = handlerMethod.getBeanType();
		CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class);
306
		CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);
S
Sebastien Deleuze 已提交
307

308 309 310
		if (typeAnnotation == null && methodAnnotation == null) {
			return null;
		}
S
Sebastien Deleuze 已提交
311

312
		CorsConfiguration config = new CorsConfiguration();
313 314
		updateCorsConfig(config, typeAnnotation);
		updateCorsConfig(config, methodAnnotation);
S
Sebastien Deleuze 已提交
315 316 317 318 319 320

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

324
	private void updateCorsConfig(CorsConfiguration config, @Nullable CrossOrigin annotation) {
S
Sebastien Deleuze 已提交
325 326 327
		if (annotation == null) {
			return;
		}
S
Sam Brannen 已提交
328
		for (String origin : annotation.origins()) {
329
			config.addAllowedOrigin(resolveCorsAnnotationValue(origin));
S
Sebastien Deleuze 已提交
330
		}
S
Sam Brannen 已提交
331
		for (RequestMethod method : annotation.methods()) {
S
Sebastien Deleuze 已提交
332 333 334
			config.addAllowedMethod(method.name());
		}
		for (String header : annotation.allowedHeaders()) {
335
			config.addAllowedHeader(resolveCorsAnnotationValue(header));
S
Sebastien Deleuze 已提交
336 337
		}
		for (String header : annotation.exposedHeaders()) {
338
			config.addExposedHeader(resolveCorsAnnotationValue(header));
S
Sebastien Deleuze 已提交
339
		}
340

341
		String allowCredentials = resolveCorsAnnotationValue(annotation.allowCredentials());
342
		if ("true".equalsIgnoreCase(allowCredentials)) {
S
Sebastien Deleuze 已提交
343 344
			config.setAllowCredentials(true);
		}
345
		else if ("false".equalsIgnoreCase(allowCredentials)) {
S
Sebastien Deleuze 已提交
346 347
			config.setAllowCredentials(false);
		}
348
		else if (!allowCredentials.isEmpty()) {
349 350
			throw new IllegalStateException("@CrossOrigin's allowCredentials value must be \"true\", \"false\", " +
					"or an empty string (\"\"): current value is [" + allowCredentials + "]");
S
Sebastien Deleuze 已提交
351
		}
352

J
Juergen Hoeller 已提交
353
		if (annotation.maxAge() >= 0 && config.getMaxAge() == null) {
S
Sebastien Deleuze 已提交
354 355 356 357
			config.setMaxAge(annotation.maxAge());
		}
	}

358
	private String resolveCorsAnnotationValue(String value) {
359 360 361 362 363 364 365
		if (this.embeddedValueResolver != null) {
			String resolved = this.embeddedValueResolver.resolveStringValue(value);
			return (resolved != null ? resolved : "");
		}
		else {
			return value;
		}
366 367
	}

368
}