org.springframework.validation

Class DataBinder

  • java.lang.Object
    • org.springframework.validation.DataBinder
    • Field Detail

      • DEFAULT_OBJECT_NAME

        public static final java.lang.String DEFAULT_OBJECT_NAME
        Default object name used for binding: "target".
        See Also:
        Constant Field Values
      • DEFAULT_AUTO_GROW_COLLECTION_LIMIT

        public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMIT
        Default limit for array and collection growing: 256.
        See Also:
        Constant Field Values
      • logger

        protected static final Log logger
        We'll create a lot of DataBinder instances: Let's use a static logger.
    • Constructor Detail

      • DataBinder

        public DataBinder(@Nullable
                          java.lang.Object target)
        Create a new DataBinder instance, with default object name.
        Parameters:
        target - the target object to bind onto (or null if the binder is just used to convert a plain parameter value)
        See Also:
        DEFAULT_OBJECT_NAME
      • DataBinder

        public DataBinder(@Nullable
                          java.lang.Object target,
                          java.lang.String objectName)
        Create a new DataBinder instance.
        Parameters:
        target - the target object to bind onto (or null if the binder is just used to convert a plain parameter value)
        objectName - the name of the target object
    • Method Detail

      • getTarget

        @Nullable
        public java.lang.Object getTarget()
        Return the wrapped target object.
      • getObjectName

        public java.lang.String getObjectName()
        Return the name of the bound object.
      • setAutoGrowNestedPaths

        public void setAutoGrowNestedPaths(boolean autoGrowNestedPaths)
        Set whether this binder should attempt to "auto-grow" a nested path that contains a null value.

        If "true", a null path location will be populated with a default object value and traversed instead of resulting in an exception. This flag also enables auto-growth of collection elements when accessing an out-of-bounds index.

        Default is "true" on a standard DataBinder. Note that since Spring 4.1 this feature is supported for bean property access (DataBinder's default mode) and field access.

        See Also:
        initBeanPropertyAccess(), ConfigurablePropertyAccessor.setAutoGrowNestedPaths(boolean)
      • isAutoGrowNestedPaths

        public boolean isAutoGrowNestedPaths()
        Return whether "auto-growing" of nested paths has been activated.
      • setAutoGrowCollectionLimit

        public void setAutoGrowCollectionLimit(int autoGrowCollectionLimit)
        Specify the limit for array and collection auto-growing.

        Default is 256, preventing OutOfMemoryErrors in case of large indexes. Raise this limit if your auto-growing needs are unusually high.

        See Also:
        initBeanPropertyAccess(), BeanWrapper.setAutoGrowCollectionLimit(int)
      • getAutoGrowCollectionLimit

        public int getAutoGrowCollectionLimit()
        Return the current limit for array and collection auto-growing.
      • getInternalBindingResult

        protected AbstractPropertyBindingResult getInternalBindingResult()
        Return the internal BindingResult held by this DataBinder, as an AbstractPropertyBindingResult.
      • getPropertyAccessor

        protected ConfigurablePropertyAccessor getPropertyAccessor()
        Return the underlying PropertyAccessor of this binder's BindingResult.
      • getSimpleTypeConverter

        protected SimpleTypeConverter getSimpleTypeConverter()
        Return this binder's underlying SimpleTypeConverter.
      • getPropertyEditorRegistry

        protected PropertyEditorRegistry getPropertyEditorRegistry()
        Return the underlying TypeConverter of this binder's BindingResult.
      • getTypeConverter

        protected TypeConverter getTypeConverter()
        Return the underlying TypeConverter of this binder's BindingResult.
      • getBindingResult

        public BindingResult getBindingResult()
        Return the BindingResult instance created by this DataBinder. This allows for convenient access to the binding results after a bind operation.
        Returns:
        the BindingResult instance, to be treated as BindingResult or as Errors instance (Errors is a super-interface of BindingResult)
        See Also:
        Errors, bind(org.springframework.beans.PropertyValues)
      • setIgnoreUnknownFields

        public void setIgnoreUnknownFields(boolean ignoreUnknownFields)
        Set whether to ignore unknown fields, that is, whether to ignore bind parameters that do not have corresponding fields in the target object.

        Default is "true". Turn this off to enforce that all bind parameters must have a matching field in the target object.

        Note that this setting only applies to binding operations on this DataBinder, not to retrieving values via its BindingResult.

        See Also:
        bind(org.springframework.beans.PropertyValues)
      • isIgnoreUnknownFields

        public boolean isIgnoreUnknownFields()
        Return whether to ignore unknown fields when binding.
      • setIgnoreInvalidFields

        public void setIgnoreInvalidFields(boolean ignoreInvalidFields)
        Set whether to ignore invalid fields, that is, whether to ignore bind parameters that have corresponding fields in the target object which are not accessible (for example because of null values in the nested path).

        Default is "false". Turn this on to ignore bind parameters for nested objects in non-existing parts of the target object graph.

        Note that this setting only applies to binding operations on this DataBinder, not to retrieving values via its BindingResult.

        See Also:
        bind(org.springframework.beans.PropertyValues)
      • isIgnoreInvalidFields

        public boolean isIgnoreInvalidFields()
        Return whether to ignore invalid fields when binding.
      • setAllowedFields

        public void setAllowedFields(@Nullable
                                     java.lang.String... allowedFields)
        Register fields that should be allowed for binding. Default is all fields. Restrict this for example to avoid unwanted modifications by malicious users when binding HTTP request parameters.

        Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching can be implemented by overriding the isAllowed method.

        Alternatively, specify a list of disallowed fields.

        Parameters:
        allowedFields - array of field names
        See Also:
        setDisallowedFields(java.lang.String...), isAllowed(String)
      • getAllowedFields

        @Nullable
        public java.lang.String[] getAllowedFields()
        Return the fields that should be allowed for binding.
        Returns:
        array of field names
      • setDisallowedFields

        public void setDisallowedFields(@Nullable
                                        java.lang.String... disallowedFields)
        Register fields that should not be allowed for binding. Default is none. Mark fields as disallowed for example to avoid unwanted modifications by malicious users when binding HTTP request parameters.

        Supports "xxx*", "*xxx" and "*xxx*" patterns. More sophisticated matching can be implemented by overriding the isAllowed method.

        Alternatively, specify a list of allowed fields.

        Parameters:
        disallowedFields - array of field names
        See Also:
        setAllowedFields(java.lang.String...), isAllowed(String)
      • getDisallowedFields

        @Nullable
        public java.lang.String[] getDisallowedFields()
        Return the fields that should not be allowed for binding.
        Returns:
        array of field names
      • getRequiredFields

        @Nullable
        public java.lang.String[] getRequiredFields()
        Return the fields that are required for each binding process.
        Returns:
        array of field names
      • setBindingErrorProcessor

        public void setBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor)
        Set the strategy to use for processing binding errors, that is, required field errors and PropertyAccessExceptions.

        Default is a DefaultBindingErrorProcessor.

        See Also:
        DefaultBindingErrorProcessor
      • getBindingErrorProcessor

        public BindingErrorProcessor getBindingErrorProcessor()
        Return the strategy for processing binding errors.
      • getValidator

        @Nullable
        public Validator getValidator()
        Return the primary Validator to apply after each binding step, if any.
      • getValidators

        public java.util.List<Validator> getValidators()
        Return the Validators to apply after data binding.
      • setConversionService

        public void setConversionService(@Nullable
                                         ConversionService conversionService)
        Specify a Spring 3.0 ConversionService to use for converting property values, as an alternative to JavaBeans PropertyEditors.
      • getConversionService

        @Nullable
        public ConversionService getConversionService()
        Return the associated ConversionService, if any.
      • addCustomFormatter

        public void addCustomFormatter(Formatter<?> formatter)
        Add a custom formatter, applying it to all fields matching the Formatter-declared type.

        Registers a corresponding PropertyEditor adapter underneath the covers.

        Parameters:
        formatter - the formatter to add, generically declared for a specific type
        Since:
        4.2
        See Also:
        registerCustomEditor(Class, PropertyEditor)
      • addCustomFormatter

        public void addCustomFormatter(Formatter<?> formatter,
                                       java.lang.String... fields)
        Add a custom formatter for the field type specified in Formatter class, applying it to the specified fields only, if any, or otherwise to all fields.

        Registers a corresponding PropertyEditor adapter underneath the covers.

        Parameters:
        formatter - the formatter to add, generically declared for a specific type
        fields - the fields to apply the formatter to, or none if to be applied to all
        Since:
        4.2
        See Also:
        registerCustomEditor(Class, String, PropertyEditor)
      • addCustomFormatter

        public void addCustomFormatter(Formatter<?> formatter,
                                       java.lang.Class<?>... fieldTypes)
        Add a custom formatter, applying it to the specified field types only, if any, or otherwise to all fields matching the Formatter-declared type.

        Registers a corresponding PropertyEditor adapter underneath the covers.

        Parameters:
        formatter - the formatter to add (does not need to generically declare a field type if field types are explicitly specified as parameters)
        fieldTypes - the field types to apply the formatter to, or none if to be derived from the given Formatter implementation class
        Since:
        4.2
        See Also:
        registerCustomEditor(Class, PropertyEditor)
      • registerCustomEditor

        public void registerCustomEditor(java.lang.Class<?> requiredType,
                                         java.beans.PropertyEditor propertyEditor)
        Description copied from interface: PropertyEditorRegistry
        Register the given custom property editor for all properties of the given type.
        Specified by:
        registerCustomEditor in interface PropertyEditorRegistry
        Parameters:
        requiredType - the type of the property
        propertyEditor - the editor to register
      • registerCustomEditor

        public void registerCustomEditor(@Nullable
                                         java.lang.Class<?> requiredType,
                                         @Nullable
                                         java.lang.String field,
                                         java.beans.PropertyEditor propertyEditor)
        Description copied from interface: PropertyEditorRegistry
        Register the given custom property editor for the given type and property, or for all properties of the given type.

        If the property path denotes an array or Collection property, the editor will get applied either to the array/Collection itself (the PropertyEditor has to create an array or Collection value) or to each element (the PropertyEditor has to create the element type), depending on the specified required type.

        Note: Only one single registered custom editor per property path is supported. In the case of a Collection/array, do not register an editor for both the Collection/array and each element on the same property.

        For example, if you wanted to register an editor for "items[n].quantity" (for all values n), you would use "items.quantity" as the value of the 'propertyPath' argument to this method.

        Specified by:
        registerCustomEditor in interface PropertyEditorRegistry
        Parameters:
        requiredType - the type of the property. This may be null if a property is given but should be specified in any case, in particular in case of a Collection - making clear whether the editor is supposed to apply to the entire Collection itself or to each of its entries. So as a general rule: Do not specify null here in case of a Collection/array!
        field - the path of the property (name or nested path), or null if registering an editor for all properties of the given type
        propertyEditor - editor to register
      • findCustomEditor

        @Nullable
        public java.beans.PropertyEditor findCustomEditor(@Nullable
                                                                    java.lang.Class<?> requiredType,
                                                                    @Nullable
                                                                    java.lang.String propertyPath)
        Description copied from interface: PropertyEditorRegistry
        Find a custom property editor for the given type and property.
        Specified by:
        findCustomEditor in interface PropertyEditorRegistry
        Parameters:
        requiredType - the type of the property (can be null if a property is given but should be specified in any case for consistency checking)
        propertyPath - the path of the property (name or nested path), or null if looking for an editor for all properties of the given type
        Returns:
        the registered editor, or null if none
      • convertIfNecessary

        @Nullable
        public <T> T convertIfNecessary(@Nullable
                                                  java.lang.Object value,
                                                  @Nullable
                                                  java.lang.Class<T> requiredType)
                                           throws TypeMismatchException
        Description copied from interface: TypeConverter
        Convert the value to the required type (if necessary from a String).

        Conversions from String to any type will typically use the setAsText method of the PropertyEditor class, or a Spring Converter in a ConversionService.

        Specified by:
        convertIfNecessary in interface TypeConverter
        Parameters:
        value - the value to convert
        requiredType - the type we must convert to (or null if not known, for example in case of a collection element)
        Returns:
        the new value, possibly the result of type conversion
        Throws:
        TypeMismatchException - if type conversion failed
        See Also:
        PropertyEditor.setAsText(String), PropertyEditor.getValue(), ConversionService, Converter
      • convertIfNecessary

        @Nullable
        public <T> T convertIfNecessary(@Nullable
                                                  java.lang.Object value,
                                                  @Nullable
                                                  java.lang.Class<T> requiredType,
                                                  @Nullable
                                                  MethodParameter methodParam)
                                           throws TypeMismatchException
        Description copied from interface: TypeConverter
        Convert the value to the required type (if necessary from a String).

        Conversions from String to any type will typically use the setAsText method of the PropertyEditor class, or a Spring Converter in a ConversionService.

        Specified by:
        convertIfNecessary in interface TypeConverter
        Parameters:
        value - the value to convert
        requiredType - the type we must convert to (or null if not known, for example in case of a collection element)
        methodParam - the method parameter that is the target of the conversion (for analysis of generic types; may be null)
        Returns:
        the new value, possibly the result of type conversion
        Throws:
        TypeMismatchException - if type conversion failed
        See Also:
        PropertyEditor.setAsText(String), PropertyEditor.getValue(), ConversionService, Converter
      • convertIfNecessary

        @Nullable
        public <T> T convertIfNecessary(@Nullable
                                                  java.lang.Object value,
                                                  @Nullable
                                                  java.lang.Class<T> requiredType,
                                                  @Nullable
                                                  java.lang.reflect.Field field)
                                           throws TypeMismatchException
        Description copied from interface: TypeConverter
        Convert the value to the required type (if necessary from a String).

        Conversions from String to any type will typically use the setAsText method of the PropertyEditor class, or a Spring Converter in a ConversionService.

        Specified by:
        convertIfNecessary in interface TypeConverter
        Parameters:
        value - the value to convert
        requiredType - the type we must convert to (or null if not known, for example in case of a collection element)
        field - the reflective field that is the target of the conversion (for analysis of generic types; may be null)
        Returns:
        the new value, possibly the result of type conversion
        Throws:
        TypeMismatchException - if type conversion failed
        See Also:
        PropertyEditor.setAsText(String), PropertyEditor.getValue(), ConversionService, Converter
      • bind

        public void bind(PropertyValues pvs)
        Bind the given property values to this binder's target.

        This call can create field errors, representing basic binding errors like a required field (code "required"), or type mismatch between value and bean property (code "typeMismatch").

        Note that the given PropertyValues should be a throwaway instance: For efficiency, it will be modified to just contain allowed fields if it implements the MutablePropertyValues interface; else, an internal mutable copy will be created for this purpose. Pass in a copy of the PropertyValues if you want your original instance to stay unmodified in any case.

        Parameters:
        pvs - property values to bind
        See Also:
        doBind(org.springframework.beans.MutablePropertyValues)
      • checkAllowedFields

        protected void checkAllowedFields(MutablePropertyValues mpvs)
        Check the given property values against the allowed fields, removing values for fields that are not allowed.
        Parameters:
        mpvs - the property values to be bound (can be modified)
        See Also:
        getAllowedFields(), isAllowed(String)
      • isAllowed

        protected boolean isAllowed(java.lang.String field)
        Return if the given field is allowed for binding. Invoked for each passed-in property value.

        The default implementation checks for "xxx*", "*xxx" and "*xxx*" matches, as well as direct equality, in the specified lists of allowed fields and disallowed fields. A field matching a disallowed pattern will not be accepted even if it also happens to match a pattern in the allowed list.

        Can be overridden in subclasses.

        Parameters:
        field - the field to check
        Returns:
        if the field is allowed
        See Also:
        setAllowedFields(java.lang.String...), setDisallowedFields(java.lang.String...), PatternMatchUtils.simpleMatch(String, String)
      • close

        public java.util.Map<?,?> close()
                                 throws BindException
        Close this DataBinder, which may result in throwing a BindException if it encountered any errors.
        Returns:
        the model Map, containing target object and Errors instance
        Throws:
        BindException - if there were any errors in the bind operation
        See Also:
        BindingResult.getModel()