RequestMappingHandlerMapping.java 13.3 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
import java.util.Set;
23

24
import javax.servlet.http.HttpServletRequest;
25

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

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

60 61
	private boolean useSuffixPatternMatch = true;

62 63
	private boolean useRegisteredSuffixPatternMatch = false;

64
	private boolean useTrailingSlashMatch = true;
65

66 67
	private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();

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
	public List<String> getFileExtensions() {
165
		return this.config.getFileExtensions();
166 167
	}

168

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

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

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

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

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

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

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

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

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

303 304 305
		if (typeAnnotation == null && methodAnnotation == null) {
			return null;
		}
S
Sebastien Deleuze 已提交
306

307
		CorsConfiguration config = new CorsConfiguration();
308 309
		updateCorsConfig(config, typeAnnotation);
		updateCorsConfig(config, methodAnnotation);
S
Sebastien Deleuze 已提交
310 311 312 313 314 315

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

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

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

J
Juergen Hoeller 已提交
348
		if (annotation.maxAge() >= 0 && config.getMaxAge() == null) {
S
Sebastien Deleuze 已提交
349 350 351 352
			config.setMaxAge(annotation.maxAge());
		}
	}

353 354 355 356
	private String resolveCorsAnnotationValue(String value) {
		return (this.embeddedValueResolver != null ? this.embeddedValueResolver.resolveStringValue(value) : value);
	}

357
}