RequestMappingHandlerMapping.java 13.3 KB
Newer Older
1
/*
S
Sebastien Deleuze 已提交
2
 * Copyright 2002-2015 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 org.springframework.context.EmbeddedValueResolverAware;
25
import org.springframework.core.annotation.AnnotatedElementUtils;
26 27
import org.springframework.core.annotation.AnnotationUtils;
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.mvc.condition.AbstractRequestCondition;
import org.springframework.web.servlet.mvc.condition.CompositeRequestCondition;
S
Sebastien Deleuze 已提交
39
import org.springframework.web.servlet.mvc.condition.NameValueExpression;
40
import org.springframework.web.servlet.mvc.condition.RequestCondition;
41 42
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
43 44

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

57 58
	private boolean useSuffixPatternMatch = true;

59 60
	private boolean useRegisteredSuffixPatternMatch = false;

61
	private boolean useTrailingSlashMatch = true;
62

63 64
	private ContentNegotiationManager contentNegotiationManager = new ContentNegotiationManager();

65 66
	private StringValueResolver embeddedValueResolver;

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

69

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

81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
	/**
	 * Whether to use suffix pattern match for registered file extensions only
	 * when matching patterns to requests.
	 * <p>If enabled, a controller method mapped to "/users" also matches to
	 * "/users.json" assuming ".json" is a file extension registered with the
	 * provided {@link #setContentNegotiationManager(ContentNegotiationManager)
	 * contentNegotiationManager}. This can be useful for allowing only specific
	 * URL extensions to be used as well as in cases where a "." in the URL path
	 * can lead to ambiguous interpretation of path variable content, (e.g. given
	 * "/users/{user}" and incoming URLs such as "/users/john.j.joe" and
	 * "/users/john.j.joe.json").
	 * <p>If enabled, this flag also enables
	 * {@link #setUseSuffixPatternMatch(boolean) useSuffixPatternMatch}. The
	 * default value is {@code false}.
	 */
96 97
	public void setUseRegisteredSuffixPatternMatch(boolean useRegisteredSuffixPatternMatch) {
		this.useRegisteredSuffixPatternMatch = useRegisteredSuffixPatternMatch;
J
Juergen Hoeller 已提交
98
		this.useSuffixPatternMatch = (useRegisteredSuffixPatternMatch || this.useSuffixPatternMatch);
99 100
	}

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

110 111 112 113 114
	/**
	 * 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 已提交
115
		Assert.notNull(contentNegotiationManager, "ContentNegotiationManager must not be null");
116 117 118
		this.contentNegotiationManager = contentNegotiationManager;
	}

J
Juergen Hoeller 已提交
119 120 121 122 123 124 125 126
	@Override
	public void setEmbeddedValueResolver(StringValueResolver resolver) {
		this.embeddedValueResolver  = resolver;
	}

	@Override
	public void afterPropertiesSet() {

127 128 129 130 131 132 133
		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 已提交
134

135 136
		super.afterPropertiesSet();
	}
J
Juergen Hoeller 已提交
137

138
	/**
139
	 * Whether to use suffix pattern matching.
140
	 */
141 142
	public boolean useSuffixPatternMatch() {
		return this.useSuffixPatternMatch;
143
	}
144 145 146 147 148

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

152
	/**
J
Juergen Hoeller 已提交
153
	 * Whether to match to URLs irrespective of the presence of a trailing slash.
154 155 156 157
	 */
	public boolean useTrailingSlashMatch() {
		return this.useTrailingSlashMatch;
	}
158

159 160 161 162
	/**
	 * Return the configured {@link ContentNegotiationManager}.
	 */
	public ContentNegotiationManager getContentNegotiationManager() {
163 164 165 166
		return this.contentNegotiationManager;
	}

	/**
167
	 * Return the file extensions to use for suffix pattern matching.
168
	 */
169
	public List<String> getFileExtensions() {
170
		return this.config.getFileExtensions();
171 172
	}

173

174
	/**
S
Stevo Slavic 已提交
175
	 * {@inheritDoc}
176
	 * Expects a handler to have a type-level @{@link Controller} annotation.
177 178
	 */
	@Override
179
	protected boolean isHandler(Class<?> beanType) {
180 181
		return ((AnnotationUtils.findAnnotation(beanType, Controller.class) != null) ||
				(AnnotationUtils.findAnnotation(beanType, RequestMapping.class) != null));
182 183 184
	}

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

R
Polish  
Rossen Stoyanchev 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	/**
	 * 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) {
		RequestMapping requestMapping = AnnotatedElementUtils.findAnnotation(element, RequestMapping.class);
		RequestCondition<?> condition = (element instanceof Class<?> ?
				getCustomTypeCondition((Class<?>) element) :
				getCustomMethodCondition((Method) element));
		return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
	}

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

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

252
	/**
253 254 255 256
	 * 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.
257
	 */
258
	protected RequestMappingInfo createRequestMappingInfo(RequestMapping requestMapping,
259 260
			RequestCondition<?> customCondition) {

R
Polish  
Rossen Stoyanchev 已提交
261 262
		return RequestMappingInfo
				.paths(resolveEmbeddedValuesInPatterns(requestMapping.path()))
263 264 265 266 267 268
				.methods(requestMapping.method())
				.params(requestMapping.params())
				.headers(requestMapping.headers())
				.consumes(requestMapping.consumes())
				.produces(requestMapping.produces())
				.mappingName(requestMapping.name())
269 270 271
				.customCondition(customCondition)
				.options(this.config)
				.build();
R
Rossen Stoyanchev 已提交
272
	}
273

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

S
Sebastien Deleuze 已提交
291 292 293
	@Override
	protected CorsConfiguration initCorsConfiguration(Object handler, Method method, RequestMappingInfo mappingInfo) {
		HandlerMethod handlerMethod = createHandlerMethod(handler, method);
294 295
		CrossOrigin typeAnnotation = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), CrossOrigin.class);
		CrossOrigin methodAnnotation = AnnotationUtils.findAnnotation(method, CrossOrigin.class);
S
Sebastien Deleuze 已提交
296

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

301
		CorsConfiguration config = new CorsConfiguration();
302 303
		updateCorsConfig(config, typeAnnotation);
		updateCorsConfig(config, methodAnnotation);
S
Sebastien Deleuze 已提交
304

305 306 307
		if (CollectionUtils.isEmpty(config.getAllowedOrigins())) {
			config.setAllowedOrigins(Arrays.asList(CrossOrigin.DEFAULT_ORIGIN));
		}
S
Sebastien Deleuze 已提交
308 309 310 311 312 313
		if (CollectionUtils.isEmpty(config.getAllowedMethods())) {
			for (RequestMethod allowedMethod : mappingInfo.getMethodsCondition().getMethods()) {
				config.addAllowedMethod(allowedMethod.name());
			}
		}
		if (CollectionUtils.isEmpty(config.getAllowedHeaders())) {
314 315 316 317 318 319 320
			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 已提交
321 322 323 324
		}
		return config;
	}

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

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

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

359
}