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

The following examples show how to use org.springframework.web.method.support.ModelAndViewContainer#containsAttribute() . 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: ModelFactory.java    From spring-analysis-note with MIT License 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 container 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 container, HandlerMethod handlerMethod)
		throws Exception {

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

	for (String name : findSessionAttributeArguments(handlerMethod)) {
		if (!container.containsAttribute(name)) {
			Object value = this.sessionAttributesHandler.retrieveAttribute(request, name);
			if (value == null) {
				throw new HttpSessionRequiredException("Expected session attribute '" + name + "'", name);
			}
			container.addAttribute(name, value);
		}
	}
}
 
Example 2
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 3
Source File: ModelFactory.java    From java-technology-stack with MIT License 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 container 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 container, HandlerMethod handlerMethod)
		throws Exception {

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

	for (String name : findSessionAttributeArguments(handlerMethod)) {
		if (!container.containsAttribute(name)) {
			Object value = this.sessionAttributesHandler.retrieveAttribute(request, name);
			if (value == null) {
				throw new HttpSessionRequiredException("Expected session attribute '" + name + "'", name);
			}
			container.addAttribute(name, value);
		}
	}
}
 
Example 4
Source File: ModelFactory.java    From lams with GNU General Public License v2.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 container)
		throws Exception {

	while (!this.modelMethods.isEmpty()) {
		InvocableHandlerMethod modelMethod = getNextModelMethod(container).getHandlerMethod();
		ModelAttribute ann = modelMethod.getMethodAnnotation(ModelAttribute.class);
		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 5
Source File: ModelFactory.java    From lams with GNU General Public License v2.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 container 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 container,
		HandlerMethod handlerMethod) throws Exception {

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

	for (String name : findSessionAttributeArguments(handlerMethod)) {
		if (!container.containsAttribute(name)) {
			Object value = this.sessionAttributesHandler.retrieveAttribute(request, name);
			if (value == null) {
				throw new HttpSessionRequiredException("Expected session attribute '" + name + "'", name);
			}
			container.addAttribute(name, value);
		}
	}
}
 
Example 6
Source File: ModelFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public List<String> getUnresolvedDependencies(ModelAndViewContainer mavContainer) {
	List<String> result = new ArrayList<String>(this.dependencies.size());
	for (String name : this.dependencies) {
		if (!mavContainer.containsAttribute(name)) {
			result.add(name);
		}
	}
	return result;
}
 
Example 7
Source File: ModelFactory.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
public boolean checkDependencies(ModelAndViewContainer mavContainer) {
	for (String name : this.dependencies) {
		if (!mavContainer.containsAttribute(name)) {
			return false;
		}
	}
	return true;
}
 
Example 8
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 9
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 10
Source File: ModelFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public List<String> getUnresolvedDependencies(ModelAndViewContainer mavContainer) {
	List<String> result = new ArrayList<String>(this.dependencies.size());
	for (String name : this.dependencies) {
		if (!mavContainer.containsAttribute(name)) {
			result.add(name);
		}
	}
	return result;
}
 
Example 11
Source File: ModelFactory.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public boolean checkDependencies(ModelAndViewContainer mavContainer) {
	for (String name : this.dependencies) {
		if (!mavContainer.containsAttribute(name)) {
			return false;
		}
	}
	return true;
}
 
Example 12
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 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: ModelFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
public List<String> getUnresolvedDependencies(ModelAndViewContainer mavContainer) {
	List<String> result = new ArrayList<>(this.dependencies.size());
	for (String name : this.dependencies) {
		if (!mavContainer.containsAttribute(name)) {
			result.add(name);
		}
	}
	return result;
}
 
Example 15
Source File: ModelFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
public boolean checkDependencies(ModelAndViewContainer mavContainer) {
	for (String name : this.dependencies) {
		if (!mavContainer.containsAttribute(name)) {
			return false;
		}
	}
	return true;
}
 
Example 16
Source File: ModelFactory.java    From java-technology-stack 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: ModelFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
public boolean checkDependencies(ModelAndViewContainer mavContainer) {
	for (String name : this.dependencies) {
		if (!mavContainer.containsAttribute(name)) {
			return false;
		}
	}
	return true;
}
 
Example 18
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 19
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 20
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;
}