ModelAttributeMethodProcessor.java 19.4 KB
Newer Older
1
/*
2
 * Copyright 2002-2021 the original author or authors.
3 4 5 6 7
 *
 * 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
 *
S
Spring Operator 已提交
8
 *      https://www.apache.org/licenses/LICENSE-2.0
9 10 11 12 13 14 15 16
 *
 * 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.
 */

17
package org.springframework.web.method.annotation;
18 19

import java.lang.annotation.Annotation;
20
import java.lang.reflect.Constructor;
21 22 23 24 25
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
26
import java.util.Map;
27
import java.util.Optional;
28
import java.util.Set;
29

30 31 32
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

33 34
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
35

36
import org.springframework.beans.BeanInstantiationException;
37
import org.springframework.beans.BeanUtils;
38
import org.springframework.beans.TypeMismatchException;
39
import org.springframework.core.MethodParameter;
40
import org.springframework.lang.Nullable;
41
import org.springframework.util.Assert;
42
import org.springframework.util.StringUtils;
43
import org.springframework.validation.BindException;
44
import org.springframework.validation.BindingResult;
45
import org.springframework.validation.Errors;
46 47
import org.springframework.validation.SmartValidator;
import org.springframework.validation.Validator;
48
import org.springframework.validation.annotation.ValidationAnnotationUtils;
49 50 51 52 53 54 55 56
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.bind.support.WebRequestDataBinder;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
57 58 59
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.multipart.support.StandardServletPartUtils;
60 61

/**
R
Polish  
Rossen Stoyanchev 已提交
62 63
 * Resolve {@code @ModelAttribute} annotated method arguments and handle
 * return values from {@code @ModelAttribute} annotated methods.
64
 *
R
Polish  
Rossen Stoyanchev 已提交
65 66 67 68
 * <p>Model attributes are obtained from the model or created with a default
 * constructor (and then added to the model). Once created the attribute is
 * populated via data binding to Servlet request parameters. Validation may be
 * applied if the argument is annotated with {@code @javax.validation.Valid}.
69
 * or Spring's own {@code @org.springframework.validation.annotation.Validated}.
70
 *
R
Polish  
Rossen Stoyanchev 已提交
71
 * <p>When this handler is created with {@code annotationNotRequired=true}
72
 * any non-simple type argument and return value is regarded as a model
73
 * attribute with or without the presence of an {@code @ModelAttribute}.
74
 *
75
 * @author Rossen Stoyanchev
76
 * @author Juergen Hoeller
77
 * @author Sebastien Deleuze
78 79
 * @since 3.1
 */
J
Juergen Hoeller 已提交
80
public class ModelAttributeMethodProcessor implements HandlerMethodArgumentResolver, HandlerMethodReturnValueHandler {
81

82
	protected final Log logger = LogFactory.getLog(getClass());
83

84
	private final boolean annotationNotRequired;
85

86

87
	/**
R
Polish  
Rossen Stoyanchev 已提交
88
	 * Class constructor.
89
	 * @param annotationNotRequired if "true", non-simple method arguments and
90
	 * return values are considered model attributes with or without a
91
	 * {@code @ModelAttribute} annotation
92
	 */
93 94
	public ModelAttributeMethodProcessor(boolean annotationNotRequired) {
		this.annotationNotRequired = annotationNotRequired;
95 96
	}

97

98
	/**
R
Polish  
Rossen Stoyanchev 已提交
99 100 101
	 * Returns {@code true} if the parameter is annotated with
	 * {@link ModelAttribute} or, if in default resolution mode, for any
	 * method parameter that is not a simple type.
102
	 */
103
	@Override
104
	public boolean supportsParameter(MethodParameter parameter) {
R
Polish  
Rossen Stoyanchev 已提交
105 106
		return (parameter.hasParameterAnnotation(ModelAttribute.class) ||
				(this.annotationNotRequired && !BeanUtils.isSimpleProperty(parameter.getParameterType())));
107 108 109
	}

	/**
110 111
	 * Resolve the argument from the model or if not found instantiate it with
	 * its default if it is available. The model attribute is then populated
112 113 114
	 * with request values via data binding and optionally validated
	 * if {@code @java.validation.Valid} is present on the argument.
	 * @throws BindException if data binding and validation result in an error
115 116
	 * and the next method parameter is not of type {@link Errors}
	 * @throws Exception if WebDataBinder initialization fails
117
	 */
118
	@Override
119
	@Nullable
120 121 122 123 124
	public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

		Assert.state(mavContainer != null, "ModelAttributeMethodProcessor requires ModelAndViewContainer");
		Assert.state(binderFactory != null, "ModelAttributeMethodProcessor requires WebDataBinderFactory");
125

126
		String name = ModelFactory.getNameForParameter(parameter);
127 128 129
		ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
		if (ann != null) {
			mavContainer.setBinding(name, ann.binding());
130 131
		}

132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
		Object attribute = null;
		BindingResult bindingResult = null;

		if (mavContainer.containsAttribute(name)) {
			attribute = mavContainer.getModel().get(name);
		}
		else {
			// Create attribute instance
			try {
				attribute = createAttribute(name, parameter, binderFactory, webRequest);
			}
			catch (BindException ex) {
				if (isBindExceptionRequired(parameter)) {
					// No BindingResult parameter -> fail with BindException
					throw ex;
				}
				// Otherwise, expose null/empty value and associated BindingResult
				if (parameter.getParameterType() == Optional.class) {
					attribute = Optional.empty();
				}
152 153 154
				else {
					attribute = ex.getTarget();
				}
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
				bindingResult = ex.getBindingResult();
			}
		}

		if (bindingResult == null) {
			// Bean property binding and validation;
			// skipped in case of binding failure on construction.
			WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
			if (binder.getTarget() != null) {
				if (!mavContainer.isBindingDisabled(name)) {
					bindRequestParameters(binder, webRequest);
				}
				validateIfApplicable(binder, parameter);
				if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
					throw new BindException(binder.getBindingResult());
				}
171
			}
172 173 174
			// Value type adaptation, also covering java.util.Optional
			if (!parameter.getParameterType().isInstance(attribute)) {
				attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
175
			}
176
			bindingResult = binder.getBindingResult();
177 178
		}

179
		// Add resolved attribute and BindingResult at the end of the model
180
		Map<String, Object> bindingResultModel = bindingResult.getModel();
181 182 183
		mavContainer.removeAttributes(bindingResultModel);
		mavContainer.addAllAttributes(bindingResultModel);

184
		return attribute;
185 186 187
	}

	/**
188 189
	 * Extension point to create the model attribute if not found in the model,
	 * with subsequent parameter binding through bean properties (unless suppressed).
190 191
	 * <p>The default implementation typically uses the unique public no-arg constructor
	 * if available but also handles a "primary constructor" approach for data classes:
J
Juergen Hoeller 已提交
192
	 * It understands the JavaBeans {@code ConstructorProperties} annotation as well as
193 194 195 196
	 * runtime-retained parameter names in the bytecode, associating request parameters
	 * with constructor arguments by name. If no such constructor is found, the default
	 * constructor will be used (even if not public), assuming subsequent bean property
	 * bindings through setter methods.
197
	 * @param attributeName the name of the attribute (never {@code null})
198
	 * @param parameter the method parameter declaration
199
	 * @param binderFactory for creating WebDataBinder instance
200
	 * @param webRequest the current request
201
	 * @return the created model attribute (never {@code null})
202 203
	 * @throws BindException in case of constructor argument binding failure
	 * @throws Exception in case of constructor invocation failure
204
	 * @see #constructAttribute(Constructor, String, MethodParameter, WebDataBinderFactory, NativeWebRequest)
205
	 * @see BeanUtils#findPrimaryConstructor(Class)
206
	 */
207 208 209
	protected Object createAttribute(String attributeName, MethodParameter parameter,
			WebDataBinderFactory binderFactory, NativeWebRequest webRequest) throws Exception {

210
		MethodParameter nestedParameter = parameter.nestedIfOptional();
211
		Class<?> clazz = nestedParameter.getNestedParameterType();
212

213
		Constructor<?> ctor = BeanUtils.getResolvableConstructor(clazz);
214
		Object attribute = constructAttribute(ctor, attributeName, parameter, binderFactory, webRequest);
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
		if (parameter != nestedParameter) {
			attribute = Optional.of(attribute);
		}
		return attribute;
	}

	/**
	 * Construct a new attribute instance with the given constructor.
	 * <p>Called from
	 * {@link #createAttribute(String, MethodParameter, WebDataBinderFactory, NativeWebRequest)}
	 * after constructor resolution.
	 * @param ctor the constructor to use
	 * @param attributeName the name of the attribute (never {@code null})
	 * @param binderFactory for creating WebDataBinder instance
	 * @param webRequest the current request
	 * @return the created model attribute (never {@code null})
	 * @throws BindException in case of constructor argument binding failure
	 * @throws Exception in case of constructor invocation failure
233
	 * @since 5.1
234
	 */
235
	@SuppressWarnings("serial")
236
	protected Object constructAttribute(Constructor<?> ctor, String attributeName, MethodParameter parameter,
237 238
			WebDataBinderFactory binderFactory, NativeWebRequest webRequest) throws Exception {

239 240 241 242
		if (ctor.getParameterCount() == 0) {
			// A single default constructor -> clearly a standard JavaBeans arrangement.
			return BeanUtils.instantiateClass(ctor);
		}
243

244
		// A single data class constructor -> resolve constructor arguments from request parameters.
245
		String[] paramNames = BeanUtils.getParameterNames(ctor);
246 247 248
		Class<?>[] paramTypes = ctor.getParameterTypes();
		Object[] args = new Object[paramTypes.length];
		WebDataBinder binder = binderFactory.createBinder(webRequest, null, attributeName);
249 250
		String fieldDefaultPrefix = binder.getFieldDefaultPrefix();
		String fieldMarkerPrefix = binder.getFieldMarkerPrefix();
251
		boolean bindingFailure = false;
252
		Set<String> failedParams = new HashSet<>(4);
253

254
		for (int i = 0; i < paramNames.length; i++) {
255 256 257 258 259 260 261
			String paramName = paramNames[i];
			Class<?> paramType = paramTypes[i];
			Object value = webRequest.getParameterValues(paramName);
			if (value == null) {
				if (fieldDefaultPrefix != null) {
					value = webRequest.getParameter(fieldDefaultPrefix + paramName);
				}
262 263
				if (value == null) {
					if (fieldMarkerPrefix != null && webRequest.getParameter(fieldMarkerPrefix + paramName) != null) {
264 265
						value = binder.getEmptyValue(paramType);
					}
266 267 268
					else {
						value = resolveConstructorArgument(paramName, paramType, webRequest);
					}
269 270
				}
			}
271
			try {
272
				MethodParameter methodParam = new FieldAwareConstructorParameter(ctor, i, paramName);
273 274 275 276 277 278
				if (value == null && methodParam.isOptional()) {
					args[i] = (methodParam.getParameterType() == Optional.class ? Optional.empty() : null);
				}
				else {
					args[i] = binder.convertIfNecessary(value, paramType, methodParam);
				}
279 280
			}
			catch (TypeMismatchException ex) {
281
				ex.initPropertyName(paramName);
282
				args[i] = null;
283 284
				failedParams.add(paramName);
				binder.getBindingResult().recordFieldValue(paramName, paramType, value);
285
				binder.getBindingErrorProcessor().processPropertyAccessException(ex, binder.getBindingResult());
286 287 288
				bindingFailure = true;
			}
		}
289

290
		if (bindingFailure) {
291 292 293 294
			BindingResult result = binder.getBindingResult();
			for (int i = 0; i < paramNames.length; i++) {
				String paramName = paramNames[i];
				if (!failedParams.contains(paramName)) {
J
Juergen Hoeller 已提交
295 296 297
					Object value = args[i];
					result.recordFieldValue(paramName, paramTypes[i], value);
					validateValueIfApplicable(binder, parameter, ctor.getDeclaringClass(), paramName, value);
298 299
				}
			}
300 301 302 303 304 305 306 307 308 309 310 311 312 313
			if (!parameter.isOptional()) {
				try {
					Object target = BeanUtils.instantiateClass(ctor, args);
					throw new BindException(result) {
						@Override
						public Object getTarget() {
							return target;
						}
					};
				}
				catch (BeanInstantiationException ex) {
					// swallow and proceed without target instance
				}
			}
314
			throw new BindException(result);
315
		}
316

317
		return BeanUtils.instantiateClass(ctor, args);
318
	}
319

320
	/**
321 322
	 * Extension point to bind the request to the target object.
	 * @param binder the data binder instance to use for the binding
323 324
	 * @param request the current request
	 */
325
	protected void bindRequestParameters(WebDataBinder binder, NativeWebRequest request) {
326 327 328
		((WebRequestDataBinder) binder).bind(request);
	}

329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
	@Nullable
	public Object resolveConstructorArgument(String paramName, Class<?> paramType, NativeWebRequest request)
			throws Exception {

		MultipartRequest multipartRequest = request.getNativeRequest(MultipartRequest.class);
		if (multipartRequest != null) {
			List<MultipartFile> files = multipartRequest.getFiles(paramName);
			if (!files.isEmpty()) {
				return (files.size() == 1 ? files.get(0) : files);
			}
		}
		else if (StringUtils.startsWithIgnoreCase(request.getHeader("Content-Type"), "multipart/")) {
			HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
			if (servletRequest != null) {
				List<Part> parts = StandardServletPartUtils.getParts(servletRequest, paramName);
				if (!parts.isEmpty()) {
					return (parts.size() == 1 ? parts.get(0) : parts);
				}
			}
		}
		return null;
	}

352
	/**
353
	 * Validate the model attribute if applicable.
354 355 356
	 * <p>The default implementation checks for {@code @javax.validation.Valid},
	 * Spring's {@link org.springframework.validation.annotation.Validated},
	 * and custom annotations whose name starts with "Valid".
357
	 * @param binder the DataBinder to be used
358
	 * @param parameter the method parameter declaration
359 360
	 * @see WebDataBinder#validate(Object...)
	 * @see SmartValidator#validate(Object, Errors, Object...)
361
	 */
362
	protected void validateIfApplicable(WebDataBinder binder, MethodParameter parameter) {
363
		for (Annotation ann : parameter.getParameterAnnotations()) {
364
			Object[] validationHints = ValidationAnnotationUtils.determineValidationHints(ann);
365
			if (validationHints != null) {
366
				binder.validate(validationHints);
367
				break;
368 369 370 371
			}
		}
	}

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
	/**
	 * Validate the specified candidate value if applicable.
	 * <p>The default implementation checks for {@code @javax.validation.Valid},
	 * Spring's {@link org.springframework.validation.annotation.Validated},
	 * and custom annotations whose name starts with "Valid".
	 * @param binder the DataBinder to be used
	 * @param parameter the method parameter declaration
	 * @param targetType the target type
	 * @param fieldName the name of the field
	 * @param value the candidate value
	 * @since 5.1
	 * @see #validateIfApplicable(WebDataBinder, MethodParameter)
	 * @see SmartValidator#validateValue(Class, String, Object, Errors, Object...)
	 */
	protected void validateValueIfApplicable(WebDataBinder binder, MethodParameter parameter,
			Class<?> targetType, String fieldName, @Nullable Object value) {

		for (Annotation ann : parameter.getParameterAnnotations()) {
390
			Object[] validationHints = ValidationAnnotationUtils.determineValidationHints(ann);
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
			if (validationHints != null) {
				for (Validator validator : binder.getValidators()) {
					if (validator instanceof SmartValidator) {
						try {
							((SmartValidator) validator).validateValue(targetType, fieldName, value,
									binder.getBindingResult(), validationHints);
						}
						catch (IllegalArgumentException ex) {
							// No corresponding field on the target class...
						}
					}
				}
				break;
			}
		}
	}

408
	/**
409
	 * Whether to raise a fatal bind exception on validation errors.
410
	 * <p>The default implementation delegates to {@link #isBindExceptionRequired(MethodParameter)}.
411
	 * @param binder the data binder used to perform data binding
412
	 * @param parameter the method parameter declaration
413 414
	 * @return {@code true} if the next method parameter is not of type {@link Errors}
	 * @see #isBindExceptionRequired(MethodParameter)
415
	 */
416
	protected boolean isBindExceptionRequired(WebDataBinder binder, MethodParameter parameter) {
417 418 419 420 421 422 423 424 425 426
		return isBindExceptionRequired(parameter);
	}

	/**
	 * Whether to raise a fatal bind exception on validation errors.
	 * @param parameter the method parameter declaration
	 * @return {@code true} if the next method parameter is not of type {@link Errors}
	 * @since 5.0
	 */
	protected boolean isBindExceptionRequired(MethodParameter parameter) {
427
		int i = parameter.getParameterIndex();
428
		Class<?>[] paramTypes = parameter.getExecutable().getParameterTypes();
429 430 431 432
		boolean hasBindingResult = (paramTypes.length > (i + 1) && Errors.class.isAssignableFrom(paramTypes[i + 1]));
		return !hasBindingResult;
	}

433
	/**
434
	 * Return {@code true} if there is a method-level {@code @ModelAttribute}
R
Polish  
Rossen Stoyanchev 已提交
435 436
	 * or, in default resolution mode, for any return value type that is not
	 * a simple type.
437
	 */
438
	@Override
439
	public boolean supportsReturnType(MethodParameter returnType) {
440 441
		return (returnType.hasMethodAnnotation(ModelAttribute.class) ||
				(this.annotationNotRequired && !BeanUtils.isSimpleProperty(returnType.getParameterType())));
442 443
	}

444 445 446
	/**
	 * Add non-null return values to the {@link ModelAndViewContainer}.
	 */
447
	@Override
448
	public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType,
449
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
450

451 452
		if (returnValue != null) {
			String name = ModelFactory.getNameForReturnValue(returnValue, returnType);
453
			mavContainer.addAttribute(name, returnValue);
454
		}
455
	}
456

457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

	/**
	 * {@link MethodParameter} subclass which detects field annotations as well.
	 * @since 5.1
	 */
	private static class FieldAwareConstructorParameter extends MethodParameter {

		private final String parameterName;

		@Nullable
		private volatile Annotation[] combinedAnnotations;

		public FieldAwareConstructorParameter(Constructor<?> constructor, int parameterIndex, String parameterName) {
			super(constructor, parameterIndex);
			this.parameterName = parameterName;
		}

		@Override
		public Annotation[] getParameterAnnotations() {
			Annotation[] anns = this.combinedAnnotations;
			if (anns == null) {
				anns = super.getParameterAnnotations();
				try {
					Field field = getDeclaringClass().getDeclaredField(this.parameterName);
					Annotation[] fieldAnns = field.getAnnotations();
					if (fieldAnns.length > 0) {
						List<Annotation> merged = new ArrayList<>(anns.length + fieldAnns.length);
						merged.addAll(Arrays.asList(anns));
						for (Annotation fieldAnn : fieldAnns) {
							boolean existingType = false;
							for (Annotation ann : anns) {
								if (ann.annotationType() == fieldAnn.annotationType()) {
									existingType = true;
									break;
								}
							}
							if (!existingType) {
								merged.add(fieldAnn);
							}
						}
						anns = merged.toArray(new Annotation[0]);
					}
				}
				catch (NoSuchFieldException | SecurityException ex) {
					// ignore
				}
				this.combinedAnnotations = anns;
			}
			return anns;
		}

		@Override
		public String getParameterName() {
			return this.parameterName;
		}
	}

514
}