RequestMappingHandlerMapping.java 13.2 KB
Newer Older
1
/*
2
 * Copyright 2002-2016 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.stereotype.Controller;
28
import org.springframework.util.Assert;
S
Sebastien Deleuze 已提交
29
import org.springframework.util.CollectionUtils;
30
import org.springframework.util.StringValueResolver;
31
import org.springframework.web.accept.ContentNegotiationManager;
S
Sebastien Deleuze 已提交
32
import org.springframework.web.bind.annotation.CrossOrigin;
33
import org.springframework.web.bind.annotation.RequestMapping;
S
Sebastien Deleuze 已提交
34 35 36
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.method.HandlerMethod;
37 38
import org.springframework.web.servlet.handler.MatchableHandlerMapping;
import org.springframework.web.servlet.handler.RequestMatchResult;
39 40
import org.springframework.web.servlet.mvc.condition.AbstractRequestCondition;
import org.springframework.web.servlet.mvc.condition.CompositeRequestCondition;
41
import org.springframework.web.servlet.mvc.condition.RequestCondition;
42 43
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
44 45

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

58 59
	private boolean useSuffixPatternMatch = true;

60 61
	private boolean useRegisteredSuffixPatternMatch = false;

62
	private boolean useTrailingSlashMatch = true;
63

64 65
	private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();

66 67
	private StringValueResolver embeddedValueResolver;

68 69
	private RequestMappingInfo.BuilderConfiguration config = new RequestMappingInfo.BuilderConfiguration();

70

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

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

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

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

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

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

127 128
		super.afterPropertiesSet();
	}
J
Juergen Hoeller 已提交
129

J
Juergen Hoeller 已提交
130

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

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

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

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

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

166

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

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

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

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

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

241
	/**
242 243 244 245
	 * 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.
246
	 */
J
Juergen Hoeller 已提交
247 248
	protected RequestMappingInfo createRequestMappingInfo(
			RequestMapping requestMapping, RequestCondition<?> customCondition) {
249

R
Polish  
Rossen Stoyanchev 已提交
250 251
		return RequestMappingInfo
				.paths(resolveEmbeddedValuesInPatterns(requestMapping.path()))
252 253 254 255 256 257
				.methods(requestMapping.method())
				.params(requestMapping.params())
				.headers(requestMapping.headers())
				.consumes(requestMapping.consumes())
				.produces(requestMapping.produces())
				.mappingName(requestMapping.name())
258 259 260
				.customCondition(customCondition)
				.options(this.config)
				.build();
R
Rossen Stoyanchev 已提交
261
	}
262

263 264 265 266 267 268 269 270 271 272
	/**
	 * 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 已提交
273
			for (int i = 0; i < patterns.length; i++) {
274 275 276 277 278 279
				resolvedPatterns[i] = this.embeddedValueResolver.resolveStringValue(patterns[i]);
			}
			return resolvedPatterns;
		}
	}

280 281 282 283 284 285 286 287 288 289 290 291
	@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 已提交
292 293 294
	@Override
	protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
		HandlerMethod handlerMethod = createHandlerMethod(handler, method);
R
Rossen Stoyanchev 已提交
295 296
		Class<?> beanType = handlerMethod.getBeanType();
		CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(beanType, CrossOrigin.class);
297
		CrossOrigin methodAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, CrossOrigin.class);
S
Sebastien Deleuze 已提交
298

299 300 301
		if (typeAnnotation == null && methodAnnotation == null) {
			return null;
		}
S
Sebastien Deleuze 已提交
302

303
		CorsConfiguration config = new CorsConfiguration();
304 305
		updateCorsConfig(config, typeAnnotation);
		updateCorsConfig(config, methodAnnotation);
S
Sebastien Deleuze 已提交
306 307 308 309 310 311

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

315
	private void updateCorsConfig(CorsConfiguration config, CrossOrigin annotation) {
S
Sebastien Deleuze 已提交
316 317 318
		if (annotation == null) {
			return;
		}
S
Sam Brannen 已提交
319
		for (String origin : annotation.origins()) {
320
			config.addAllowedOrigin(resolveCorsAnnotationValue(origin));
S
Sebastien Deleuze 已提交
321
		}
S
Sam Brannen 已提交
322
		for (RequestMethod method : annotation.methods()) {
S
Sebastien Deleuze 已提交
323 324 325
			config.addAllowedMethod(method.name());
		}
		for (String header : annotation.allowedHeaders()) {
326
			config.addAllowedHeader(resolveCorsAnnotationValue(header));
S
Sebastien Deleuze 已提交
327 328
		}
		for (String header : annotation.exposedHeaders()) {
329
			config.addExposedHeader(resolveCorsAnnotationValue(header));
S
Sebastien Deleuze 已提交
330
		}
331

332
		String allowCredentials = resolveCorsAnnotationValue(annotation.allowCredentials());
333
		if ("true".equalsIgnoreCase(allowCredentials)) {
S
Sebastien Deleuze 已提交
334 335
			config.setAllowCredentials(true);
		}
336
		else if ("false".equalsIgnoreCase(allowCredentials)) {
S
Sebastien Deleuze 已提交
337 338
			config.setAllowCredentials(false);
		}
339
		else if (!allowCredentials.isEmpty()) {
340 341
			throw new IllegalStateException("@CrossOrigin's allowCredentials value must be \"true\", \"false\", " +
					"or an empty string (\"\"): current value is [" + allowCredentials + "]");
S
Sebastien Deleuze 已提交
342
		}
343

J
Juergen Hoeller 已提交
344
		if (annotation.maxAge() >= 0 && config.getMaxAge() == null) {
S
Sebastien Deleuze 已提交
345 346 347 348
			config.setMaxAge(annotation.maxAge());
		}
	}

349 350 351 352
	private String resolveCorsAnnotationValue(String value) {
		return (this.embeddedValueResolver != null ? this.embeddedValueResolver.resolveStringValue(value) : value);
	}

353
}