我正在使用 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
and StrictNumberFormatEditor
已通过重写相应方法进行定制,以满足数字格式的自定义需求和乔达时间.
由于我使用的是 Spring 3.2.0,因此我可以利用@ControllerAdvice.
Spring 建议列出一组允许的字段setAllowedFields()方法,以便恶意用户无法将值注入绑定对象。
来自docs about DataBinder
允许将属性值设置到目标对象上的绑定器,
包括对验证和结合结果分析的支持。这
可以通过指定允许的字段来定制绑定过程,
必填字段、自定义编辑器等。
请注意,如果未能设置,可能会存在潜在的安全隐患
允许字段的数组。对于 HTTP 表单 POST 数据
例如,恶意客户端可以尝试通过以下方式破坏应用程序
为不存在的字段或属性提供值
形式。在某些情况下,这可能会导致非法数据被设置
命令对象或其嵌套对象。正因如此,高度
建议指定allowedFields财产在数据绑定器上。
我有一个很大的应用程序,显然有数千个字段。指定并列出所有这些setAllowedFields()是一项乏味的工作。此外,我需要以某种方式记住它们。
更改网页以删除某些字段或在需要再次出现时添加其他字段需要修改setAllowedFields()反映这些变化的方法。
有什么替代方案吗?