Java Code Examples for org.springframework.web.bind.support.WebDataBinderFactory#createBinder()

The following examples show how to use org.springframework.web.bind.support.WebDataBinderFactory#createBinder() . 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: 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 3
Source File: ServletModelAttributeMethodProcessor.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Create a model attribute from a String request value (e.g. URI template
 * variable, request parameter) using type conversion.
 * <p>The default implementation converts only if there a registered
 * {@link Converter} that can perform the conversion.
 * @param sourceValue the source value to create the model attribute from
 * @param attributeName the name of the attribute (never {@code null})
 * @param parameter the method parameter
 * @param binderFactory for creating WebDataBinder instance
 * @param request the current request
 * @return the created model attribute, or {@code null} if no suitable
 * conversion found
 */
@Nullable
protected Object createAttributeFromRequestValue(String sourceValue, String attributeName,
		MethodParameter parameter, WebDataBinderFactory binderFactory, NativeWebRequest request)
		throws Exception {

	DataBinder binder = binderFactory.createBinder(request, null, attributeName);
	ConversionService conversionService = binder.getConversionService();
	if (conversionService != null) {
		TypeDescriptor source = TypeDescriptor.valueOf(String.class);
		TypeDescriptor target = new TypeDescriptor(parameter);
		if (conversionService.canConvert(source, target)) {
			return binder.convertIfNecessary(sourceValue, parameter.getParameterType(), parameter);
		}
	}
	return null;
}
 
Example 4
Source File: InitBinderDataBinderFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void createBinderTypeConversion() throws Exception {
	this.webRequest.getNativeRequest(MockHttpServletRequest.class).setParameter("requestParam", "22");
	this.argumentResolvers.addResolver(new RequestParamMethodArgumentResolver(null, false));

	WebDataBinderFactory factory = createFactory("initBinderTypeConversion", WebDataBinder.class, int.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, "foo");

	assertNotNull(dataBinder.getDisallowedFields());
	assertEquals("requestParam-22", dataBinder.getDisallowedFields()[0]);
}
 
Example 5
Source File: InitBinderDataBinderFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void createBinderNullAttrName() throws Exception {
	WebDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, null);

	assertNull(dataBinder.getDisallowedFields());
}
 
Example 6
Source File: InitBinderDataBinderFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void createBinderWithAttrNameNoMatch() throws Exception {
	WebDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, "invalidName");

	assertNull(dataBinder.getDisallowedFields());
}
 
Example 7
Source File: InitBinderDataBinderFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void createBinderWithAttrName() throws Exception {
	WebDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, "foo");

	assertNotNull(dataBinder.getDisallowedFields());
	assertEquals("id", dataBinder.getDisallowedFields()[0]);
}
 
Example 8
Source File: InitBinderDataBinderFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void createBinderWithGlobalInitialization() throws Exception {
	ConversionService conversionService = new DefaultFormattingConversionService();
	bindingInitializer.setConversionService(conversionService);

	WebDataBinderFactory factory = createFactory("initBinder", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, null);

	assertSame(conversionService, dataBinder.getConversionService());
}
 
Example 9
Source File: InitBinderDataBinderFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void createBinder() throws Exception {
	WebDataBinderFactory factory = createFactory("initBinder", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, null);

	assertNotNull(dataBinder.getDisallowedFields());
	assertEquals("id", dataBinder.getDisallowedFields()[0]);
}
 
Example 10
Source File: InitBinderDataBinderFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void createBinderTypeConversion() throws Exception {
	this.webRequest.getNativeRequest(MockHttpServletRequest.class).setParameter("requestParam", "22");
	this.argumentResolvers.addResolver(new RequestParamMethodArgumentResolver(null, false));

	WebDataBinderFactory factory = createFactory("initBinderTypeConversion", WebDataBinder.class, int.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, "foo");

	assertNotNull(dataBinder.getDisallowedFields());
	assertEquals("requestParam-22", dataBinder.getDisallowedFields()[0]);
}
 
Example 11
Source File: InitBinderDataBinderFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void createBinderNullAttrName() throws Exception {
	WebDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, null);

	assertNull(dataBinder.getDisallowedFields());
}
 
Example 12
Source File: InitBinderDataBinderFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void createBinderWithAttrName() throws Exception {
	WebDataBinderFactory factory = createFactory("initBinderWithAttributeName", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, "foo");

	assertNotNull(dataBinder.getDisallowedFields());
	assertEquals("id", dataBinder.getDisallowedFields()[0]);
}
 
Example 13
Source File: InitBinderDataBinderFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void createBinderWithGlobalInitialization() throws Exception {
	ConversionService conversionService = new DefaultFormattingConversionService();
	bindingInitializer.setConversionService(conversionService);

	WebDataBinderFactory factory = createFactory("initBinder", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, null);

	assertSame(conversionService, dataBinder.getConversionService());
}
 
Example 14
Source File: InitBinderDataBinderFactoryTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void createBinder() throws Exception {
	WebDataBinderFactory factory = createFactory("initBinder", WebDataBinder.class);
	WebDataBinder dataBinder = factory.createBinder(this.webRequest, null, null);

	assertNotNull(dataBinder.getDisallowedFields());
	assertEquals("id", dataBinder.getDisallowedFields()[0]);
}
 
Example 15
Source File: InitBinderDataBinderFactoryTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void returnValueNotExpected() throws Exception {
	WebDataBinderFactory factory = createFactory("initBinderReturnValue", WebDataBinder.class);
	factory.createBinder(this.webRequest, null, "invalidName");
}
 
Example 16
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 17
Source File: InitBinderDataBinderFactoryTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void returnValueNotExpected() throws Exception {
	WebDataBinderFactory factory = createFactory("initBinderReturnValue", WebDataBinder.class);
	factory.createBinder(this.webRequest, null, "invalidName");
}
 
Example 18
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 19
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 20
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);
}