Spring:绑定命令时转义输入

时间:2009-08-05 07:07:38

标签: spring spring-mvc escaping

如何处理您希望表单中的用户输入为htmlEscape时的情况 你绑定到命令对象?

我希望这能自动清理输入数据,以避免在命令对象中遍历所有字段。

感谢。

2 个答案:

答案 0 :(得分:10)

如果您使用的是FormController,则可以通过覆盖initBinder(HttpServletReques,ServletRequestDataBinder)方法来注册新的属性编辑器。这个属性编辑器可以转义html,javascript和sql注入。

如果使用属性编辑器,则在分配给命令对象之前,编辑器将处理请求对象中的值。

当我们注册一个编辑器时,我们必须指定其值必须由编辑器处理的项目的类型。

抱歉,现在我没有该方法的语法。但我确信这就是我们实现这一目标的方式。

EDITED

我认为以下语法可以正常工作

在你的控制器中覆盖如下所示的方法

    @Override
    protected void initBinder(HttpServletRequest request,
        ServletRequestDataBinder binder) throws Exception {
        super.initBinder(request, binder);

        binder.registerCustomEditor(String.class, 
                    new StringEscapeEditor(true, true, false));
    }

然后创建以下属性编辑器

public class StringEscapeEditor extends PropertyEditorSupport {

    private boolean escapeHTML;
    private boolean escapeJavaScript;
    private boolean escapeSQL;

    public StringEscapeEditor() {
        super();
    }

    public StringEscapeEditor(boolean escapeHTML, boolean escapeJavaScript,
            boolean escapeSQL) {
        super();
        this.escapeHTML = escapeHTML;
        this.escapeJavaScript = escapeJavaScript;
        this.escapeSQL = escapeSQL;
    }

    public void setAsText(String text) {
        if (text == null) {
            setValue(null);
        } else {
            String value = text;
            if (escapeHTML) {
                value = StringEscapeUtils.escapeHtml(value);
            }
            if (escapeJavaScript) {
                value = StringEscapeUtils.escapeJavaScript(value);
            }
            if (escapeSQL) {
                value = StringEscapeUtils.escapeSql(value);
            }
            setValue(value);
        }
    }

    public String getAsText() {
        Object value = getValue();
        return (value != null ? value.toString() : "");
    }
}

希望这有助于你

答案 1 :(得分:0)

您可以使用来自休眠验证程序的@Valid@SafeHtml。详见https://stackoverflow.com/a/40644276/548473