类 DataBinder
- 所有已实现的接口:
PropertyEditorRegistry,TypeConverter
The binding process can be customized by specifying allowed field patterns, required fields, custom editors, etc.
WARNING: Data binding can lead to security issues by exposing parts of the object graph that are not meant to be accessed or modified by external clients. Therefore the design and use of data binding should be considered carefully with regard to security. For more details, please refer to the dedicated sections on data binding for Spring Web MVC and Spring WebFlux in the reference manual.
The binding results can be examined via the BindingResult interface,
extending the Errors interface: see the getBindingResult() method.
Missing fields and property access exceptions will be converted to FieldErrors,
collected in the Errors instance, using the following error codes:
- Missing field error: "required"
- Type mismatch error: "typeMismatch"
- Method invocation error: "methodInvocation"
By default, binding errors get resolved through the BindingErrorProcessor
strategy, processing for missing fields and property access exceptions: see the
setBindingErrorProcessor(cn.taketoday.validation.BindingErrorProcessor) method. You can override the default strategy
if needed, for example to generate different error codes.
Custom validation errors can be added afterwards. You will typically want to resolve
such error codes into proper user-visible error messages; this can be achieved through
resolving each error via a MessageSource, which is
able to resolve an ObjectError/FieldError through its
MessageSource.getMessage(cn.taketoday.context.MessageSourceResolvable, java.util.Locale)
method. The list of message codes can be customized through the MessageCodesResolver
strategy: see the setMessageCodesResolver(cn.taketoday.validation.MessageCodesResolver) method. DefaultMessageCodesResolver's
javadoc states details on the default resolution rules.
This generic data binder can be used in any kind of environment.
- 作者:
- Rod Johnson, Juergen Hoeller, Rob Harrop, Stephane Nicoll, Kazuki Shimizu, Sam Brannen
- 另请参阅:
-
setAllowedFields(java.lang.String...)setRequiredFields(java.lang.String...)registerCustomEditor(java.lang.Class<?>, java.beans.PropertyEditor)setMessageCodesResolver(cn.taketoday.validation.MessageCodesResolver)setBindingErrorProcessor(cn.taketoday.validation.BindingErrorProcessor)bind(cn.taketoday.beans.PropertyValues)getBindingResult()DefaultMessageCodesResolverDefaultBindingErrorProcessorMessageSource
-
字段概要
字段修饰符和类型字段说明static final intDefault limit for array and collection growing: 256.static final StringDefault object name used for binding: "target".protected static final cn.taketoday.logging.LoggerWe'll create a lot of DataBinder instances: Let's use a static logger. -
构造器概要
构造器构造器说明DataBinder(Object target) Create a new DataBinder instance, with default object name.DataBinder(Object target, String objectName) Create a new DataBinder instance. -
方法概要
修饰符和类型方法说明voidaddCustomFormatter(Formatter<?> formatter) Add a custom formatter, applying it to all fields matching theFormatter-declared type.voidaddCustomFormatter(Formatter<?> formatter, Class<?>... fieldTypes) Add a custom formatter, applying it to the specified field types only, if any, or otherwise to all fields matching theFormatter-declared type.voidaddCustomFormatter(Formatter<?> formatter, String... fields) Add a custom formatter for the field type specified inFormatterclass, applying it to the specified fields only, if any, or otherwise to all fields.voidaddValidators(Validator... validators) Add Validators to apply after each binding step.protected voidApply given property values to the target object.voidbind(PropertyValues pvs) Bind the given property values to this binder's target.protected voidCheck the given property values against the allowed fields, removing values for fields that are not allowed.protected voidCheck the given property values against the required fields, generating missing field errors where appropriate.Map<?,?> close()Close this DataBinder, which may result in throwing a BindException if it encountered any errors.<T> TconvertIfNecessary(Object value, Class<T> requiredType) <T> TconvertIfNecessary(Object value, Class<T> requiredType, cn.taketoday.core.MethodParameter methodParam) <T> TconvertIfNecessary(Object value, Class<T> requiredType, cn.taketoday.core.TypeDescriptor typeDescriptor) <T> TconvertIfNecessary(Object value, Class<T> requiredType, Field field) protected AbstractPropertyBindingResultCreate theAbstractPropertyBindingResultinstance using standard JavaBean property access.protected AbstractPropertyBindingResultCreate theAbstractPropertyBindingResultinstance using direct field access.protected voiddoBind(PropertyValues values) Actual implementation of the binding process, working with the passed-in PropertyValues instance.findCustomEditor(Class<?> requiredType, String propertyPath) String[]Return the field patterns that should be allowed for binding.intReturn the current limit for array and collection auto-growing.Return the strategy for processing binding errors.Return the BindingResult instance created by this DataBinder.cn.taketoday.core.conversion.ConversionServiceReturn the associated ConversionService, if any.String[]Return the field patterns that should not be allowed for binding.protected AbstractPropertyBindingResultReturn the internal BindingResult held by this DataBinder, as an AbstractPropertyBindingResult.Return the name of the bound object.protected ConfigurablePropertyAccessorReturn the underlying PropertyAccessor of this binder's BindingResult.protected PropertyEditorRegistryReturn the underlying TypeConverter of this binder's BindingResult.String[]Return the fields that are required for each binding process.protected SimpleTypeConverterReturn this binder's underlying SimpleTypeConverter.Return the wrapped target object.protected TypeConverterReturn the underlying TypeConverter of this binder's BindingResult.Return the primary Validator to apply after each binding step, if any.Return the Validators to apply after data binding.voidInitialize standard JavaBean property access for this DataBinder.voidInitialize direct field access for this DataBinder, as alternative to the default bean property access.protected booleanDetermine if the given field is allowed for binding.booleanReturn whether "auto-growing" of nested paths has been activated.booleanReturn whether to ignore invalid fields when binding.booleanReturn whether to ignore unknown fields when binding.voidregisterCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) voidregisterCustomEditor(Class<?> requiredType, String field, PropertyEditor propertyEditor) voidreplaceValidators(Validator... validators) Replace the Validators to apply after each binding step.voidsetAllowedFields(String... allowedFields) Register field patterns that should be allowed for binding.voidsetAutoGrowCollectionLimit(int autoGrowCollectionLimit) Specify the limit for array and collection auto-growing.voidsetAutoGrowNestedPaths(boolean autoGrowNestedPaths) Set whether this binder should attempt to "auto-grow" a nested path that contains a null value.voidsetBindingErrorProcessor(BindingErrorProcessor bindingErrorProcessor) Set the strategy to use for processing binding errors, that is, required field errors andPropertyAccessExceptions.voidsetConversionService(cn.taketoday.core.conversion.ConversionService conversionService) Specify a ConversionService to use for converting property values, as an alternative to JavaBeans PropertyEditors.voidsetDisallowedFields(String... disallowedFields) Register field patterns that should not be allowed for binding.voidsetIgnoreInvalidFields(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).voidsetIgnoreUnknownFields(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.voidsetMessageCodesResolver(MessageCodesResolver messageCodesResolver) Set the strategy to use for resolving errors into message codes.voidsetRequiredFields(String... requiredFields) Register fields that are required for each binding process.voidsetValidator(Validator validator) Set the Validator to apply after each binding step.voidvalidate()Invoke the specified Validators, if any.voidInvoke the specified Validators, if any, with the given validation hints.
-
字段详细资料
-
DEFAULT_OBJECT_NAME
Default object name used for binding: "target".- 另请参阅:
-
DEFAULT_AUTO_GROW_COLLECTION_LIMIT
public static final int DEFAULT_AUTO_GROW_COLLECTION_LIMITDefault limit for array and collection growing: 256.- 另请参阅:
-
logger
protected static final cn.taketoday.logging.Logger loggerWe'll create a lot of DataBinder instances: Let's use a static logger.
-
-
构造器详细资料
-
DataBinder
Create a new DataBinder instance, with default object name.- 参数:
target- the target object to bind onto (ornullif the binder is just used to convert a plain parameter value)- 另请参阅:
-
DataBinder
Create a new DataBinder instance.- 参数:
target- the target object to bind onto (ornullif the binder is just used to convert a plain parameter value)objectName- the name of the target object
-
-
方法详细资料
-
getTarget
Return the wrapped target object. -
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.
-
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.
-
getAutoGrowCollectionLimit
public int getAutoGrowCollectionLimit()Return the current limit for array and collection auto-growing. -
initBeanPropertyAccess
public void initBeanPropertyAccess()Initialize standard JavaBean property access for this DataBinder.This is the default; an explicit call just leads to eager initialization.
-
createBeanPropertyBindingResult
Create theAbstractPropertyBindingResultinstance using standard JavaBean property access. -
initDirectFieldAccess
public void initDirectFieldAccess()Initialize direct field access for this DataBinder, as alternative to the default bean property access. -
createDirectFieldBindingResult
Create theAbstractPropertyBindingResultinstance using direct field access. -
getInternalBindingResult
Return the internal BindingResult held by this DataBinder, as an AbstractPropertyBindingResult. -
getPropertyAccessor
Return the underlying PropertyAccessor of this binder's BindingResult. -
getSimpleTypeConverter
Return this binder's underlying SimpleTypeConverter. -
getPropertyEditorRegistry
Return the underlying TypeConverter of this binder's BindingResult. -
getTypeConverter
Return the underlying TypeConverter of this binder's BindingResult. -
getBindingResult
Return the BindingResult instance created by this DataBinder. This allows for convenient access to the binding results after a bind operation.- 返回:
- the BindingResult instance, to be treated as BindingResult or as Errors instance (Errors is a super-interface of BindingResult)
- 另请参阅:
-
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. -
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. -
isIgnoreInvalidFields
public boolean isIgnoreInvalidFields()Return whether to ignore invalid fields when binding. -
setAllowedFields
Register field patterns 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","*xxx*", and"xxx*yyy"matches (with an arbitrary number of pattern parts), as well as direct equality.The default implementation of this method stores allowed field patterns in canonical form. Subclasses which override this method must therefore take this into account.
More sophisticated matching can be implemented by overriding the
isAllowed(java.lang.String)method.Alternatively, specify a list of disallowed field patterns.
- 参数:
allowedFields- array of allowed field patterns- 另请参阅:
-
getAllowedFields
Return the field patterns that should be allowed for binding.- 返回:
- array of allowed field patterns
- 另请参阅:
-
setDisallowedFields
Register field patterns 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","*xxx*", and"xxx*yyy"matches (with an arbitrary number of pattern parts), as well as direct equality.The default implementation of this method stores disallowed field patterns in canonical form. the default implementation also transforms disallowed field patterns to lowercase to support case-insensitive pattern matching in
isAllowed(java.lang.String). Subclasses which override this method must therefore take both of these transformations into account.More sophisticated matching can be implemented by overriding the
isAllowed(java.lang.String)method.Alternatively, specify a list of allowed field patterns.
- 参数:
disallowedFields- array of disallowed field patterns- 另请参阅:
-
getDisallowedFields
Return the field patterns that should not be allowed for binding.- 返回:
- array of disallowed field patterns
- 另请参阅:
-
setRequiredFields
Register fields that are required for each binding process.If one of the specified fields is not contained in the list of incoming property values, a corresponding "missing field" error will be created, with error code "required" (by the default binding error processor).
- 参数:
requiredFields- array of field names- 另请参阅:
-
getRequiredFields
Return the fields that are required for each binding process.- 返回:
- array of field names
-
setMessageCodesResolver
Set the strategy to use for resolving errors into message codes. Applies the given strategy to the underlying errors holder.Default is a DefaultMessageCodesResolver.
-
setBindingErrorProcessor
Set the strategy to use for processing binding errors, that is, required field errors andPropertyAccessExceptions.Default is a DefaultBindingErrorProcessor.
-
getBindingErrorProcessor
Return the strategy for processing binding errors. -
setValidator
Set the Validator to apply after each binding step. -
addValidators
Add Validators to apply after each binding step. -
replaceValidators
Replace the Validators to apply after each binding step. -
getValidator
Return the primary Validator to apply after each binding step, if any. -
getValidators
Return the Validators to apply after data binding. -
setConversionService
public void setConversionService(@Nullable cn.taketoday.core.conversion.ConversionService conversionService) Specify a ConversionService to use for converting property values, as an alternative to JavaBeans PropertyEditors. -
getConversionService
@Nullable public cn.taketoday.core.conversion.ConversionService getConversionService()Return the associated ConversionService, if any. -
addCustomFormatter
Add a custom formatter, applying it to all fields matching theFormatter-declared type.Registers a corresponding
PropertyEditoradapter underneath the covers.- 参数:
formatter- the formatter to add, generically declared for a specific type- 另请参阅:
-
addCustomFormatter
Add a custom formatter for the field type specified inFormatterclass, applying it to the specified fields only, if any, or otherwise to all fields.Registers a corresponding
PropertyEditoradapter underneath the covers.- 参数:
formatter- the formatter to add, generically declared for a specific typefields- the fields to apply the formatter to, or none if to be applied to all- 另请参阅:
-
addCustomFormatter
Add a custom formatter, applying it to the specified field types only, if any, or otherwise to all fields matching theFormatter-declared type.Registers a corresponding
PropertyEditoradapter underneath the covers.- 参数:
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 givenFormatterimplementation class- 另请参阅:
-
registerCustomEditor
- 指定者:
registerCustomEditor在接口中PropertyEditorRegistry
-
registerCustomEditor
public void registerCustomEditor(@Nullable Class<?> requiredType, @Nullable String field, PropertyEditor propertyEditor) - 指定者:
registerCustomEditor在接口中PropertyEditorRegistry
-
findCustomEditor
@Nullable public PropertyEditor findCustomEditor(@Nullable Class<?> requiredType, @Nullable String propertyPath) - 指定者:
findCustomEditor在接口中PropertyEditorRegistry
-
convertIfNecessary
@Nullable public <T> T convertIfNecessary(@Nullable Object value, @Nullable Class<T> requiredType) throws TypeMismatchException - 指定者:
convertIfNecessary在接口中TypeConverter- 抛出:
TypeMismatchException
-
convertIfNecessary
@Nullable public <T> T convertIfNecessary(@Nullable Object value, @Nullable Class<T> requiredType, @Nullable cn.taketoday.core.MethodParameter methodParam) throws TypeMismatchException - 指定者:
convertIfNecessary在接口中TypeConverter- 抛出:
TypeMismatchException
-
convertIfNecessary
@Nullable public <T> T convertIfNecessary(@Nullable Object value, @Nullable Class<T> requiredType, @Nullable Field field) throws TypeMismatchException - 指定者:
convertIfNecessary在接口中TypeConverter- 抛出:
TypeMismatchException
-
convertIfNecessary
@Nullable public <T> T convertIfNecessary(@Nullable Object value, @Nullable Class<T> requiredType, @Nullable cn.taketoday.core.TypeDescriptor typeDescriptor) throws TypeMismatchException - 指定者:
convertIfNecessary在接口中TypeConverter- 抛出:
TypeMismatchException
-
bind
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 PropertyValues 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.
- 参数:
pvs- property values to bind- 另请参阅:
-
doBind
Actual implementation of the binding process, working with the passed-in PropertyValues instance.- 参数:
values- the property values to bind, as PropertyValues instance- 另请参阅:
-
checkAllowedFields
Check the given property values against the allowed fields, removing values for fields that are not allowed.- 参数:
mpvs- the property values to be bound (can be modified)- 另请参阅:
-
isAllowed
Determine if the given field is allowed for binding.Invoked for each passed-in property value.
Checks for
"xxx*","*xxx","*xxx*", and"xxx*yyy"matches (with an arbitrary number of pattern parts), as well as direct equality, in the configured lists of allowed field patterns and disallowed field patterns.Matching against allowed field patterns is case-sensitive; whereas, matching against disallowed field patterns is case-insensitive.
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, but care must be taken to honor the aforementioned contract.
- 参数:
field- the field to check- 返回:
trueif the field is allowed- 另请参阅:
-
setAllowedFields(java.lang.String...)setDisallowedFields(java.lang.String...)StringUtils.simpleMatch(String, String)
-
checkRequiredFields
Check the given property values against the required fields, generating missing field errors where appropriate.- 参数:
mpvs- the property values to be bound (can be modified)- 另请参阅:
-
applyPropertyValues
Apply given property values to the target object.Default implementation applies all of the supplied property values as bean property values. By default, unknown fields will be ignored.
- 参数:
mpvs- the property values to be bound (can be modified)- 另请参阅:
-
validate
public void validate()Invoke the specified Validators, if any. -
validate
Invoke the specified Validators, if any, with the given validation hints.Note: Validation hints may get ignored by the actual target Validator.
- 参数:
validationHints- one or more hint objects to be passed to aSmartValidator- 另请参阅:
-
close
Close this DataBinder, which may result in throwing a BindException if it encountered any errors.- 返回:
- the model Map, containing target object and Errors instance
- 抛出:
BindException- if there were any errors in the bind operation- 另请参阅:
-