RequestMappingHandlerMapping.java 13.6 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.Arrays;
22
import java.util.List;
23 24
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
25

26
import org.springframework.context.EmbeddedValueResolverAware;
27
import org.springframework.core.annotation.AnnotatedElementUtils;
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 68
	private StringValueResolver embeddedValueResolver;

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

71

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

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

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

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

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

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

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

J
Juergen Hoeller 已提交
131

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

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

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

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

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

167

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

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

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

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

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

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

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

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

281 282 283 284 285 286 287 288 289 290 291 292
	@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 已提交
293 294 295
	@Override
	protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
		HandlerMethod handlerMethod = createHandlerMethod(handler, method);
296 297
		CrossOrigin typeAnnotation = AnnotatedElementUtils.findMergedAnnotation(handlerMethod.getBeanType(), CrossOrigin.class);
		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
		if (CollectionUtils.isEmpty(config.getAllowedOrigins())) {
S
Sebastien Deleuze 已提交
308
			config.setAllowedOrigins(Arrays.asList(CrossOrigin.DEFAULT_ORIGINS));
309
		}
S
Sebastien Deleuze 已提交
310 311 312 313 314 315
		if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
			for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
				config.addAllowedMethod(allowedMethod.name());
			}
		}
		if (CollectionUtils.isEmpty(config.getAllowedHeaders())) {
316 317 318 319 320 321 322
			config.setAllowedHeaders(Arrays.asList(CrossOrigin.DEFAULT_ALLOWED_HEADERS));
		}
		if (config.getAllowCredentials() == null) {
			config.setAllowCredentials(CrossOrigin.DEFAULT_ALLOW_CREDENTIALS);
		}
		if (config.getMaxAge() == null) {
			config.setMaxAge(CrossOrigin.DEFAULT_MAX_AGE);
S
Sebastien Deleuze 已提交
323 324 325 326
		}
		return config;
	}

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

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

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

361 362 363 364
	private String resolveCorsAnnotationValue(String value) {
		return (this.embeddedValueResolver != null ? this.embeddedValueResolver.resolveStringValue(value) : value);
	}

365
}