Java Code Examples for org.springframework.web.bind.WebDataBinder#getBindingResult()

The following examples show how to use org.springframework.web.bind.WebDataBinder#getBindingResult() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: RequestResponseBodyMethodProcessor.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Throws MethodArgumentNotValidException if validation fails.
 * @throws HttpMessageNotReadableException if {@link RequestBody#required()}
 * is {@code true} and there is no body content or if there is no suitable
 * converter to read the content with.
 */
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	parameter = parameter.nestedIfOptional();
	Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());
	String name = Conventions.getVariableNameForParameter(parameter);

	if (binderFactory != null) {
		WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
		if (arg != null) {
			validateIfApplicable(binder, parameter);
			if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
				throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
			}
		}
		if (mavContainer != null) {
			mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
		}
	}

	return adaptArgumentIfNecessary(arg, parameter);
}
 
Example 2
Source File: FormModelMethodArgumentResolver.java    From es with Apache License 2.0 6 votes vote down vote up
protected void validateComponent(WebDataBinder binder, MethodParameter parameter) throws BindException {

        boolean validateParameter = validateParameter(parameter);
        Annotation[] annotations = binder.getTarget().getClass().getAnnotations();
        for (Annotation annot : annotations) {
            if (annot.annotationType().getSimpleName().startsWith("Valid") && validateParameter) {
                Object hints = AnnotationUtils.getValue(annot);
                binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[]{hints});
            }
        }

        if (binder.getBindingResult().hasErrors()) {
            if (isBindExceptionRequired(binder, parameter)) {
                throw new BindException(binder.getBindingResult());
            }
        }
    }
 
Example 3
Source File: ModelAttributeMethodProcessor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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
 * 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
 * and the next method parameter is not of type {@link Errors}.
 * @throws Exception if WebDataBinder initialization fails.
 */
@Override
public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

	String name = ModelFactory.getNameForParameter(parameter);
	Object attribute = (mavContainer.containsAttribute(name) ?
			mavContainer.getModel().get(name) : createAttribute(name, parameter, binderFactory, webRequest));

	WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
	if (binder.getTarget() != null) {
		bindRequestParameters(binder, webRequest);
		validateIfApplicable(binder, parameter);
		if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
			throw new BindException(binder.getBindingResult());
		}
	}

	// Add resolved attribute and BindingResult at the end of the model
	Map<String, Object> bindingResultModel = binder.getBindingResult().getModel();
	mavContainer.removeAttributes(bindingResultModel);
	mavContainer.addAllAttributes(bindingResultModel);

	return binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
}
 
Example 4
Source File: RequestResponseBodyMethodProcessor.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Throws MethodArgumentNotValidException if validation fails.
 * @throws HttpMessageNotReadableException if {@link RequestBody#required()}
 * is {@code true} and there is no body content or if there is no suitable
 * converter to read the content with.
 */
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

	Object arg = readWithMessageConverters(webRequest, parameter, parameter.getGenericParameterType());
	String name = Conventions.getVariableNameForParameter(parameter);

	WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
	if (arg != null) {
		validateIfApplicable(binder, parameter);
		if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
			throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
		}
	}
	mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());

	return arg;
}
 
Example 5
Source File: RequestResponseBodyMethodProcessor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Throws MethodArgumentNotValidException if validation fails.
 * @throws HttpMessageNotReadableException if {@link RequestBody#required()}
 * is {@code true} and there is no body content or if there is no suitable
 * converter to read the content with.
 */
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

	parameter = parameter.nestedIfOptional();
	Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());
	String name = Conventions.getVariableNameForParameter(parameter);

	WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
	if (arg != null) {
		validateIfApplicable(binder, parameter);
		if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
			throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
		}
	}
	mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());

	return adaptArgumentIfNecessary(arg, parameter);
}
 
Example 6
Source File: FormModelMethodArgumentResolver.java    From distributed-transaction-process with MIT License 6 votes vote down vote up
protected void validateComponent(WebDataBinder binder, MethodParameter parameter) throws BindException {

        boolean validateParameter = validateParameter(parameter);
        Annotation[] annotations = binder.getTarget().getClass().getAnnotations();
        for (Annotation annot : annotations) {
            if (annot.annotationType().getSimpleName().startsWith("Valid") && validateParameter) {
                Object hints = AnnotationUtils.getValue(annot);
                binder.validate(hints instanceof Object[] ? (Object[]) hints : new Object[]{hints});
            }
        }

        if (binder.getBindingResult().hasErrors()) {
            if (isBindExceptionRequired(binder, parameter)) {
                throw new BindException(binder.getBindingResult());
            }
        }
    }
 
Example 7
Source File: RequestResponseBodyMethodProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Throws MethodArgumentNotValidException if validation fails.
 * @throws HttpMessageNotReadableException if {@link RequestBody#required()}
 * is {@code true} and there is no body content or if there is no suitable
 * converter to read the content with.
 */
@Override
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	parameter = parameter.nestedIfOptional();
	Object arg = readWithMessageConverters(webRequest, parameter, parameter.getNestedGenericParameterType());
	String name = Conventions.getVariableNameForParameter(parameter);

	if (binderFactory != null) {
		WebDataBinder binder = binderFactory.createBinder(webRequest, arg, name);
		if (arg != null) {
			validateIfApplicable(binder, parameter);
			if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
				throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
			}
		}
		if (mavContainer != null) {
			mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
		}
	}

	return adaptArgumentIfNecessary(arg, parameter);
}
 
Example 8
Source File: FormModelMethodArgumentResolver.java    From distributed-transaction-process with MIT License 5 votes vote down vote up
/**
 * 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
 * with request values via data binding and optionally validated
 * if {@code @java.validation.Valid} is present on the argument.
 *
 * @throws org.springframework.validation.BindException
 *                   if data binding and validation result in an error
 *                   and the next method parameter is not of type {@link org.springframework.validation.Errors}.
 * @throws Exception if WebDataBinder initialization fails.
 */
public final Object resolveArgument(MethodParameter parameter,
                                    ModelAndViewContainer mavContainer,
                                    NativeWebRequest request,
                                    WebDataBinderFactory binderFactory) throws Exception {
    String name = parameter.getParameterAnnotation(FormModel.class).value();

    Object target = (mavContainer.containsAttribute(name)) ?
            mavContainer.getModel().get(name) : createAttribute(name, parameter, binderFactory, request);

    WebDataBinder binder = binderFactory.createBinder(request, target, name);
    target = binder.getTarget();
    if (target != null) {
        bindRequestParameters(mavContainer, binderFactory, binder, request, parameter);

        validateIfApplicable(binder, parameter);
        if (binder.getBindingResult().hasErrors()) {
            if (isBindExceptionRequired(binder, parameter)) {
                throw new BindException(binder.getBindingResult());
            }
        }
    }

    target = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType());
    mavContainer.addAttribute(name, target);

    return target;
}
 
Example 9
Source File: ModelAttributeMethodProcessor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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
 * 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
 * and the next method parameter is not of type {@link Errors}.
 * @throws Exception if WebDataBinder initialization fails.
 */
@Override
public final Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

	String name = ModelFactory.getNameForParameter(parameter);
	Object attribute = (mavContainer.containsAttribute(name) ? mavContainer.getModel().get(name) :
			createAttribute(name, parameter, binderFactory, webRequest));

	if (!mavContainer.isBindingDisabled(name)) {
		ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
		if (ann != null && !ann.binding()) {
			mavContainer.setBindingDisabled(name);
		}
	}

	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());
		}
	}

	// Add resolved attribute and BindingResult at the end of the model
	Map<String, Object> bindingResultModel = binder.getBindingResult().getModel();
	mavContainer.removeAttributes(bindingResultModel);
	mavContainer.addAllAttributes(bindingResultModel);

	return binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
}
 
Example 10
Source File: HandlerMethodInvoker.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void doBind(WebDataBinder binder, NativeWebRequest webRequest, boolean validate,
		Object[] validationHints, boolean failOnErrors) throws Exception {

	doBind(binder, webRequest);
	if (validate) {
		binder.validate(validationHints);
	}
	if (failOnErrors && binder.getBindingResult().hasErrors()) {
		throw new BindException(binder.getBindingResult());
	}
}
 
Example 11
Source File: HandlerMethodInvoker.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
private void doBind(WebDataBinder binder, NativeWebRequest webRequest, boolean validate,
		Object[] validationHints, boolean failOnErrors) throws Exception {

	doBind(binder, webRequest);
	if (validate) {
		binder.validate(validationHints);
	}
	if (failOnErrors && binder.getBindingResult().hasErrors()) {
		throw new BindException(binder.getBindingResult());
	}
}
 
Example 12
Source File: TeapotMappingHandler.java    From example-restful-project with MIT License 5 votes vote down vote up
/**
 * Converts {@link TeapotMapping} to {@link Teapot} domain object. Apply
 * binding on {@link Teapot}.
 */
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {

    /* Read mapping from request */
    TeapotMapping mapping = (TeapotMapping) readWithMessageConverters(
            webRequest, parameter, TeapotMapping.class);
    String name = Conventions.getVariableNameForParameter(parameter);

    /* Convert mapping to domain object */
    Teapot teapot = mapper.fromMapping(mapping);

    WebDataBinder binder = binderFactory
            .createBinder(webRequest, teapot, name);

    if (teapot != null) {
        validateIfApplicable(binder, parameter);
        if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
            throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
        }
    }

    mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());

    return teapot;
}
 
Example 13
Source File: UifDefaultFormMethodArgumentResolver.java    From rice with Educational Community License v2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
        NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
    String name = UifConstants.DEFAULT_MODEL_NAME;

    Object attribute = null;
    if (mavContainer.containsAttribute(name)) {
        attribute = mavContainer.getModel().get(name);
    }

    WebDataBinder binder = binderFactory.createBinder(webRequest, attribute, name);
    if (binder.getTarget() != null) {
        ServletRequest servletRequest = webRequest.getNativeRequest(ServletRequest.class);
        ServletRequestDataBinder servletBinder = (ServletRequestDataBinder) binder;
        servletBinder.bind(servletRequest);

        if (binder.getBindingResult().hasErrors()) {
            if (isBindExceptionRequired(parameter)) {
                throw new BindException(binder.getBindingResult());
            }
        }
    }

    Map<String, Object> bindingResultModel = binder.getBindingResult().getModel();
    mavContainer.removeAttributes(bindingResultModel);
    mavContainer.addAllAttributes(bindingResultModel);

    return binder.getTarget();
}
 
Example 14
Source File: FormModelMethodArgumentResolver.java    From es with Apache License 2.0 5 votes vote down vote up
/**
 * 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
 * with request values via data binding and optionally validated
 * if {@code @java.validation.Valid} is present on the argument.
 *
 * @throws org.springframework.validation.BindException
 *                   if data binding and validation result in an error
 *                   and the next method parameter is not of type {@link org.springframework.validation.Errors}.
 * @throws Exception if WebDataBinder initialization fails.
 */
public final Object resolveArgument(MethodParameter parameter,
                                    ModelAndViewContainer mavContainer,
                                    NativeWebRequest request,
                                    WebDataBinderFactory binderFactory) throws Exception {
    String name = parameter.getParameterAnnotation(FormModel.class).value();

    Object target = (mavContainer.containsAttribute(name)) ?
            mavContainer.getModel().get(name) : createAttribute(name, parameter, binderFactory, request);

    WebDataBinder binder = binderFactory.createBinder(request, target, name);
    target = binder.getTarget();
    if (target != null) {
        bindRequestParameters(mavContainer, binderFactory, binder, request, parameter);

        validateIfApplicable(binder, parameter);
        if (binder.getBindingResult().hasErrors()) {
            if (isBindExceptionRequired(binder, parameter)) {
                throw new BindException(binder.getBindingResult());
            }
        }
    }

    target = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType());
    mavContainer.addAttribute(name, target);

    return target;
}
 
Example 15
Source File: ModelAttributeMethodProcessor.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * 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
 * 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
 * and the next method parameter is not of type {@link Errors}
 * @throws Exception if WebDataBinder initialization fails
 */
@Override
@Nullable
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");

	String name = ModelFactory.getNameForParameter(parameter);
	ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
	if (ann != null) {
		mavContainer.setBinding(name, ann.binding());
	}

	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();
			}
			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());
			}
		}
		// Value type adaptation, also covering java.util.Optional
		if (!parameter.getParameterType().isInstance(attribute)) {
			attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
		}
		bindingResult = binder.getBindingResult();
	}

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

	return attribute;
}
 
Example 16
Source File: RequestPartMethodArgumentResolver.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
@UsesJava8
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
		NativeWebRequest request, WebDataBinderFactory binderFactory) throws Exception {

	HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
	assertIsMultipartRequest(servletRequest);

	MultipartHttpServletRequest multipartRequest =
			WebUtils.getNativeRequest(servletRequest, MultipartHttpServletRequest.class);

	Class<?> paramType = parameter.getParameterType();
	boolean optional = paramType.getName().equals("java.util.Optional");
	if (optional) {
		parameter.increaseNestingLevel();
		paramType = parameter.getNestedParameterType();
	}

	String partName = getPartName(parameter);
	Object arg;

	if (MultipartFile.class == paramType) {
		Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
		arg = multipartRequest.getFile(partName);
	}
	else if (isMultipartFileCollection(parameter)) {
		Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
		arg = multipartRequest.getFiles(partName);
	}
	else if (isMultipartFileArray(parameter)) {
		Assert.notNull(multipartRequest, "Expected MultipartHttpServletRequest: is a MultipartResolver configured?");
		List<MultipartFile> files = multipartRequest.getFiles(partName);
		arg = files.toArray(new MultipartFile[files.size()]);
	}
	else if ("javax.servlet.http.Part".equals(paramType.getName())) {
		assertIsMultipartRequest(servletRequest);
		arg = servletRequest.getPart(partName);
	}
	else if (isPartCollection(parameter)) {
		assertIsMultipartRequest(servletRequest);
		arg = new ArrayList<Object>(servletRequest.getParts());
	}
	else if (isPartArray(parameter)) {
		assertIsMultipartRequest(servletRequest);
		arg = RequestPartResolver.resolvePart(servletRequest);
	}
	else {
		try {
			HttpInputMessage inputMessage = new RequestPartServletServerHttpRequest(servletRequest, partName);
			arg = readWithMessageConverters(inputMessage, parameter, parameter.getNestedGenericParameterType());
			WebDataBinder binder = binderFactory.createBinder(request, arg, partName);
			if (arg != null) {
				validateIfApplicable(binder, parameter);
				if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
					throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
				}
			}
			mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + partName, binder.getBindingResult());
		}
		catch (MissingServletRequestPartException ex) {
			// handled below
			arg = null;
		}
	}

	RequestPart requestPart = parameter.getParameterAnnotation(RequestPart.class);
	boolean isRequired = ((requestPart == null || requestPart.required()) && !optional);

	if (arg == null && isRequired) {
		throw new MissingServletRequestPartException(partName);
	}
	if (optional) {
		arg = Optional.ofNullable(arg);
	}

	return arg;
}
 
Example 17
Source File: RequestPartMethodArgumentResolver.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest request, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
	Assert.state(servletRequest != null, "No HttpServletRequest");

	RequestPart requestPart = parameter.getParameterAnnotation(RequestPart.class);
	boolean isRequired = ((requestPart == null || requestPart.required()) && !parameter.isOptional());

	String name = getPartName(parameter, requestPart);
	parameter = parameter.nestedIfOptional();
	Object arg = null;

	Object mpArg = MultipartResolutionDelegate.resolveMultipartArgument(name, parameter, servletRequest);
	if (mpArg != MultipartResolutionDelegate.UNRESOLVABLE) {
		arg = mpArg;
	}
	else {
		try {
			HttpInputMessage inputMessage = new RequestPartServletServerHttpRequest(servletRequest, name);
			arg = readWithMessageConverters(inputMessage, parameter, parameter.getNestedGenericParameterType());
			if (binderFactory != null) {
				WebDataBinder binder = binderFactory.createBinder(request, arg, name);
				if (arg != null) {
					validateIfApplicable(binder, parameter);
					if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
						throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
					}
				}
				if (mavContainer != null) {
					mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
				}
			}
		}
		catch (MissingServletRequestPartException | MultipartException ex) {
			if (isRequired) {
				throw ex;
			}
		}
	}

	if (arg == null && isRequired) {
		if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
			throw new MultipartException("Current request is not a multipart request");
		}
		else {
			throw new MissingServletRequestPartException(name);
		}
	}
	return adaptArgumentIfNecessary(arg, parameter);
}
 
Example 18
Source File: ModelAttributeMethodProcessor.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * 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
 * 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
 * and the next method parameter is not of type {@link Errors}
 * @throws Exception if WebDataBinder initialization fails
 */
@Override
@Nullable
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");

	String name = ModelFactory.getNameForParameter(parameter);
	ModelAttribute ann = parameter.getParameterAnnotation(ModelAttribute.class);
	if (ann != null) {
		mavContainer.setBinding(name, ann.binding());
	}

	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();
			}
			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());
			}
		}
		// Value type adaptation, also covering java.util.Optional
		if (!parameter.getParameterType().isInstance(attribute)) {
			attribute = binder.convertIfNecessary(binder.getTarget(), parameter.getParameterType(), parameter);
		}
		bindingResult = binder.getBindingResult();
	}

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

	return attribute;
}
 
Example 19
Source File: RequestPartMethodArgumentResolver.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
@Nullable
public Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
		NativeWebRequest request, @Nullable WebDataBinderFactory binderFactory) throws Exception {

	HttpServletRequest servletRequest = request.getNativeRequest(HttpServletRequest.class);
	Assert.state(servletRequest != null, "No HttpServletRequest");

	RequestPart requestPart = parameter.getParameterAnnotation(RequestPart.class);
	boolean isRequired = ((requestPart == null || requestPart.required()) && !parameter.isOptional());

	String name = getPartName(parameter, requestPart);
	parameter = parameter.nestedIfOptional();
	Object arg = null;

	Object mpArg = MultipartResolutionDelegate.resolveMultipartArgument(name, parameter, servletRequest);
	if (mpArg != MultipartResolutionDelegate.UNRESOLVABLE) {
		arg = mpArg;
	}
	else {
		try {
			HttpInputMessage inputMessage = new RequestPartServletServerHttpRequest(servletRequest, name);
			arg = readWithMessageConverters(inputMessage, parameter, parameter.getNestedGenericParameterType());
			if (binderFactory != null) {
				WebDataBinder binder = binderFactory.createBinder(request, arg, name);
				if (arg != null) {
					validateIfApplicable(binder, parameter);
					if (binder.getBindingResult().hasErrors() && isBindExceptionRequired(binder, parameter)) {
						throw new MethodArgumentNotValidException(parameter, binder.getBindingResult());
					}
				}
				if (mavContainer != null) {
					mavContainer.addAttribute(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
				}
			}
		}
		catch (MissingServletRequestPartException | MultipartException ex) {
			if (isRequired) {
				throw ex;
			}
		}
	}

	if (arg == null && isRequired) {
		if (!MultipartResolutionDelegate.isMultipartRequest(servletRequest)) {
			throw new MultipartException("Current request is not a multipart request");
		}
		else {
			throw new MissingServletRequestPartException(name);
		}
	}
	return adaptArgumentIfNecessary(arg, parameter);
}