我正在使用Spring 3.2.0。我已经为一些基本需求注册了一些自定义属性编辑器,如下所示。
import editors.DateTimeEditor;
import editors.StrictNumberFormatEditor;
import java.math.RoundingMode;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import org.joda.time.DateTime;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.beans.propertyeditors.URLEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
public final class GlobalDataBinder
{
@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request)
{
binder.setIgnoreInvalidFields(true);
binder.setIgnoreUnknownFields(true);
//binder.setAllowedFields(someArray);
NumberFormat numberFormat=DecimalFormat.getInstance();
numberFormat.setGroupingUsed(false);
numberFormat.setMaximumFractionDigits(2);
numberFormat.setRoundingMode(RoundingMode.HALF_UP);
binder.registerCustomEditor(DateTime.class, new DateTimeEditor("MM/dd/yyyy HH:mm:ss", true));
binder.registerCustomEditor(Double.class, new StrictNumberFormatEditor(Double.class, numberFormat, true));
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
binder.registerCustomEditor(URL.class, new URLEditor());
}
}
到目前为止,我已经注册了这么多编辑器。通过覆盖各自的方法已定制了其中两个DateTimeEditor
和StrictNumberFormatEditor
,以满足数字格式和Joda-Time的自定义需求。
因为我使用的是Spring 3.2.0,所以可以利用@ControllerAdvice
。
Spring建议使用@ControllerAdvice
方法列出一组允许的字段,以使恶意用户无法将值注入绑定的对象中。
从setAllowedFields()
到setAllowedFields()
允许将属性值设置到目标对象的活页夹,包括对验证和绑定结果分析的支持。的可以通过指定允许的字段来自定义绑定过程,必填字段,自定义编辑器等。
请注意,如果无法设置允许字段的数组。如果是HTTP形式的POST数据,例如,恶意客户端可以尝试通过以下方式破坏应用程序为不存在的字段或属性提供值形成。在某些情况下,这可能会导致设置非法数据命令对象或其嵌套对象。因此,它docs属性。
DataBinder
指定并列出所有这些都是繁琐的工作。此外,我需要以某种方式记住它们。 为了再次出现需要而更改网页以删除某些字段或添加其他字段,需要修改allowedFields
方法的参数值以反映这些更改。
还有其他选择吗?
allowedFields
进行白名单,而是可以使用setAllowedFields()
进行黑名单。例如,从petclinic示例应用程序:setAllowedFields()
从纯粹的安全角度出发,白名单优于黑名单,但它可能有助于减轻负担。
@InitBinder
public void setAllowedFields(WebDataBinder dataBinder) {
dataBinder.setDisallowedFields("id");
}