在Spring中使用setAllowedFields()方法

问题描述 投票:2回答:4

我正在使用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());
    } 
}

到目前为止,我已经注册了这么多编辑器。通过覆盖各自的方法已定制了其中两个DateTimeEditorStrictNumberFormatEditor,以满足数字格式和Joda-Time的自定义需求。

因为我使用的是Spring 3.2.0,所以可以利用@ControllerAdvice

Spring建议使用@ControllerAdvice方法列出一组允许的字段,以使恶意用户无法将值注入绑定的对象中。

setAllowedFields()setAllowedFields()

允许将属性值设置到目标对象的活页夹,包括对验证和绑定结果分析的支持。的可以通过指定允许的字段来自定义绑定过程,必填字段,自定义编辑器等。

请注意,如果无法设置允许字段的数组。如果是HTTP形式的POST数据,例如,恶意客户端可以尝试通过以下方式破坏应用程序为不存在的字段或属性提供值形成。在某些情况下,这可能会导致设置非法数据命令对象或其嵌套对象。因此,它docs属性。


我有一个很大的应用程序,显然有数千个字段。用DataBinder指定并列出所有这些都是繁琐的工作。此外,我需要以某种方式记住它们。

为了再次出现需要而更改网页以删除某些字段或添加其他字段,需要修改allowedFields方法的参数值以反映这些更改。

还有其他选择吗?

spring spring-mvc spring-3 databinder propertyeditor
4个回答
4
投票
不是使用allowedFields进行白名单,而是可以使用setAllowedFields()进行黑名单。例如,从petclinic示例应用程序:

setAllowedFields()

从纯粹的安全角度出发,白名单优于黑名单,但它可能有助于减轻负担。

2
投票
setAllowedFields()在直接在Web层中使用实体对象时非常方便。或者,可以使用专用数据传输对象(DTO),从该对象在服务层中构造实体对象。工厂不仅可以重复使用,而且可以在Web上下文之外使用,例如用于异步消息。此外,DTO继承不必遵循实体继承,因此您可以根据用例的需要自由设计DTO层次结构。]

0
投票

0
投票
一种将活页夹与DTO结合使用的解决方案(例如,companydata),如果大多数表单输入值如果为空,则应将其转换为null,但是需要添加一些例外(setDisallowedFields对我不起作用)。 >

@InitBinder public void setAllowedFields(WebDataBinder dataBinder) { dataBinder.setDisallowedFields("id"); }

© www.soinside.com 2019 - 2024. All rights reserved.