Java Code Examples for org.springframework.web.method.support.ModelAndViewContainer#addAttribute()

The following examples show how to use org.springframework.web.method.support.ModelAndViewContainer#addAttribute() . 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: ModelFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void updateModelBindingResult() throws Exception {
	String commandName = "attr1";
	Object command = new Object();
	ModelAndViewContainer container = new ModelAndViewContainer();
	container.addAttribute(commandName, command);

	WebDataBinder dataBinder = new WebDataBinder(command, commandName);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.webRequest, command, commandName)).willReturn(dataBinder);

	ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.sessionAttrsHandler);
	modelFactory.updateModel(this.webRequest, container);

	assertEquals(command, container.getModel().get(commandName));
	assertSame(dataBinder.getBindingResult(), container.getModel().get(bindingResultKey(commandName)));
	assertEquals(2, container.getModel().size());
}
 
Example 2
Source File: ModelFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test  // SPR-12542
public void updateModelWhenRedirecting() throws Exception {
	String attributeName = "sessionAttr";
	String attribute = "value";
	ModelAndViewContainer container = new ModelAndViewContainer();
	container.addAttribute(attributeName, attribute);

	String queryParam = "123";
	String queryParamName = "q";
	container.setRedirectModel(new ModelMap(queryParamName, queryParam));
	container.setRedirectModelScenario(true);

	WebDataBinder dataBinder = new WebDataBinder(attribute, attributeName);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.webRequest, attribute, attributeName)).willReturn(dataBinder);

	ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler);
	modelFactory.updateModel(this.webRequest, container);

	assertEquals(queryParam, container.getModel().get(queryParamName));
	assertEquals(1, container.getModel().size());
	assertEquals(attribute, this.attributeStore.retrieveAttribute(this.webRequest, attributeName));
}
 
Example 3
Source File: ModelFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void updateModelSessionAttributesRemoved() throws Exception {
	String attributeName = "sessionAttr";
	String attribute = "value";
	ModelAndViewContainer container = new ModelAndViewContainer();
	container.addAttribute(attributeName, attribute);

	this.attributeStore.storeAttribute(this.webRequest, attributeName, attribute);

	WebDataBinder dataBinder = new WebDataBinder(attribute, attributeName);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.webRequest, attribute, attributeName)).willReturn(dataBinder);

	container.getSessionStatus().setComplete();

	ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler);
	modelFactory.updateModel(this.webRequest, container);

	assertEquals(attribute, container.getModel().get(attributeName));
	assertNull(this.attributeStore.retrieveAttribute(this.webRequest, attributeName));
}
 
Example 4
Source File: ModelFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void updateModelSessionAttributesSaved() throws Exception {
	String attributeName = "sessionAttr";
	String attribute = "value";
	ModelAndViewContainer container = new ModelAndViewContainer();
	container.addAttribute(attributeName, attribute);

	WebDataBinder dataBinder = new WebDataBinder(attribute, attributeName);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.webRequest, attribute, attributeName)).willReturn(dataBinder);

	ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler);
	modelFactory.updateModel(this.webRequest, container);

	assertEquals(attribute, container.getModel().get(attributeName));
	assertEquals(attribute, this.attributeStore.retrieveAttribute(this.webRequest, attributeName));
}
 
Example 5
Source File: ModelFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void updateModelBindingResult() throws Exception {
	String commandName = "attr1";
	Object command = new Object();
	ModelAndViewContainer container = new ModelAndViewContainer();
	container.addAttribute(commandName, command);

	WebDataBinder dataBinder = new WebDataBinder(command, commandName);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.webRequest, command, commandName)).willReturn(dataBinder);

	ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler);
	modelFactory.updateModel(this.webRequest, container);

	assertEquals(command, container.getModel().get(commandName));
	String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + commandName;
	assertSame(dataBinder.getBindingResult(), container.getModel().get(bindingResultKey));
	assertEquals(2, container.getModel().size());
}
 
Example 6
Source File: ModelFactory.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Populate the model in the following order:
 * <ol>
 * 	<li>Retrieve "known" session attributes listed as {@code @SessionAttributes}.
 * 	<li>Invoke {@code @ModelAttribute} methods
 * 	<li>Find {@code @ModelAttribute} method arguments also listed as
 * 	{@code @SessionAttributes} and ensure they're present in the model raising
 * 	an exception if necessary.
 * </ol>
 * @param request the current request
 * @param mavContainer a container with the model to be initialized
 * @param handlerMethod the method for which the model is initialized
 * @throws Exception may arise from {@code @ModelAttribute} methods
 */
public void initModel(NativeWebRequest request, ModelAndViewContainer mavContainer, HandlerMethod handlerMethod)
		throws Exception {

	Map<String, ?> sessionAttributes = this.sessionAttributesHandler.retrieveAttributes(request);
	mavContainer.mergeAttributes(sessionAttributes);

	invokeModelAttributeMethods(request, mavContainer);

	for (String name : findSessionAttributeArguments(handlerMethod)) {
		if (!mavContainer.containsAttribute(name)) {
			Object value = this.sessionAttributesHandler.retrieveAttribute(request, name);
			if (value == null) {
				throw new HttpSessionRequiredException("Expected session attribute '" + name + "'");
			}
			mavContainer.addAttribute(name, value);
		}
	}
}
 
Example 7
Source File: ModelFactory.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Invoke model attribute methods to populate the model.
 * Attributes are added only if not already present in the model.
 */
private void invokeModelAttributeMethods(NativeWebRequest request, ModelAndViewContainer mavContainer)
		throws Exception {

	while (!this.modelMethods.isEmpty()) {
		InvocableHandlerMethod attrMethod = getNextModelMethod(mavContainer).getHandlerMethod();
		String modelName = attrMethod.getMethodAnnotation(ModelAttribute.class).value();
		if (mavContainer.containsAttribute(modelName)) {
			continue;
		}

		Object returnValue = attrMethod.invokeForRequest(request, mavContainer);

		if (!attrMethod.isVoid()){
			String returnValueName = getNameForReturnValue(returnValue, attrMethod.getReturnType());
			if (!mavContainer.containsAttribute(returnValueName)) {
				mavContainer.addAttribute(returnValueName, returnValue);
			}
		}
	}
}
 
Example 8
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 9
Source File: ModelFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void updateModelSessionAttributesSaved() throws Exception {
	String attributeName = "sessionAttr";
	String attribute = "value";
	ModelAndViewContainer container = new ModelAndViewContainer();
	container.addAttribute(attributeName, attribute);

	WebDataBinder dataBinder = new WebDataBinder(attribute, attributeName);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.webRequest, attribute, attributeName)).willReturn(dataBinder);

	ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.sessionAttrsHandler);
	modelFactory.updateModel(this.webRequest, container);

	assertEquals(attribute, container.getModel().get(attributeName));
	assertEquals(attribute, this.sessionAttributeStore.retrieveAttribute(this.webRequest, attributeName));
}
 
Example 10
Source File: ModelFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void updateModelSessionAttributesSaved() throws Exception {
	String attributeName = "sessionAttr";
	String attribute = "value";
	ModelAndViewContainer container = new ModelAndViewContainer();
	container.addAttribute(attributeName, attribute);

	WebDataBinder dataBinder = new WebDataBinder(attribute, attributeName);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.webRequest, attribute, attributeName)).willReturn(dataBinder);

	ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler);
	modelFactory.updateModel(this.webRequest, container);

	assertEquals(attribute, container.getModel().get(attributeName));
	assertEquals(attribute, this.attributeStore.retrieveAttribute(this.webRequest, attributeName));
}
 
Example 11
Source File: ModelFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void updateModelBindingResult() throws Exception {
	String commandName = "attr1";
	Object command = new Object();
	ModelAndViewContainer container = new ModelAndViewContainer();
	container.addAttribute(commandName, command);

	WebDataBinder dataBinder = new WebDataBinder(command, commandName);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.webRequest, command, commandName)).willReturn(dataBinder);

	ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler);
	modelFactory.updateModel(this.webRequest, container);

	assertEquals(command, container.getModel().get(commandName));
	String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + commandName;
	assertSame(dataBinder.getBindingResult(), container.getModel().get(bindingResultKey));
	assertEquals(2, container.getModel().size());
}
 
Example 12
Source File: ModelFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void updateModelWhenRedirecting() throws Exception {
	String attributeName = "sessionAttr";
	String attribute = "value";
	ModelAndViewContainer container = new ModelAndViewContainer();
	container.addAttribute(attributeName, attribute);

	String queryParam = "123";
	String queryParamName = "q";
	container.setRedirectModel(new ModelMap(queryParamName, queryParam));
	container.setRedirectModelScenario(true);

	WebDataBinder dataBinder = new WebDataBinder(attribute, attributeName);
	WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
	given(binderFactory.createBinder(this.webRequest, attribute, attributeName)).willReturn(dataBinder);

	ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.sessionAttrsHandler);
	modelFactory.updateModel(this.webRequest, container);

	assertEquals(queryParam, container.getModel().get(queryParamName));
	assertEquals(1, container.getModel().size());
	assertEquals(attribute, this.sessionAttributeStore.retrieveAttribute(this.webRequest, attributeName));
}
 
Example 13
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 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: ErrorsMethodHandlerArgumentResolverTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test(expected=IllegalStateException.class)
public void bindingResultNotFound() throws Exception {
	ModelAndViewContainer mavContainer = new ModelAndViewContainer();
	mavContainer.addAllAttributes(bindingResult.getModel());
	mavContainer.addAttribute("ignore1", "value1");

	resolver.resolveArgument(paramErrors, mavContainer, webRequest, null);
}
 
Example 16
Source File: ModelFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Invoke model attribute methods to populate the model.
 * Attributes are added only if not already present in the model.
 */
private void invokeModelAttributeMethods(NativeWebRequest request, ModelAndViewContainer container)
		throws Exception {

	while (!this.modelMethods.isEmpty()) {
		InvocableHandlerMethod modelMethod = getNextModelMethod(container).getHandlerMethod();
		ModelAttribute ann = modelMethod.getMethodAnnotation(ModelAttribute.class);
		Assert.state(ann != null, "No ModelAttribute annotation");
		if (container.containsAttribute(ann.name())) {
			if (!ann.binding()) {
				container.setBindingDisabled(ann.name());
			}
			continue;
		}

		Object returnValue = modelMethod.invokeForRequest(request, container);
		if (!modelMethod.isVoid()){
			String returnValueName = getNameForReturnValue(returnValue, modelMethod.getReturnType());
			if (!ann.binding()) {
				container.setBindingDisabled(returnValueName);
			}
			if (!container.containsAttribute(returnValueName)) {
				container.addAttribute(returnValueName, returnValue);
			}
		}
	}
}
 
Example 17
Source File: ErrorsMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void bindingResultNotFound() throws Exception {
	ModelAndViewContainer mavContainer = new ModelAndViewContainer();
	mavContainer.addAllAttributes(bindingResult.getModel());
	mavContainer.addAttribute("ignore1", "value1");

	resolver.resolveArgument(paramErrors, mavContainer, webRequest, null);
}
 
Example 18
Source File: ErrorsMethodArgumentResolverTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void bindingResult() throws Exception {
	ModelAndViewContainer mavContainer = new ModelAndViewContainer();
	mavContainer.addAttribute("ignore1", "value1");
	mavContainer.addAttribute("ignore2", "value2");
	mavContainer.addAttribute("ignore3", "value3");
	mavContainer.addAttribute("ignore4", "value4");
	mavContainer.addAttribute("ignore5", "value5");
	mavContainer.addAllAttributes(bindingResult.getModel());

	Object actual = resolver.resolveArgument(paramErrors, mavContainer, webRequest, null);
	assertSame(actual, bindingResult);
}
 
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);
}
 
Example 20
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);
}