Spring:绑定到命令时转义输入


问题内容

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

我希望它自动清除输入数据,以避免在命令对象中的所有字段中运行。

谢谢。


问题答案:

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

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

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

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

已编辑

我认为以下语法可以工作

在您的控制器中覆盖如下所示的以​​下方法

    @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() : "");
    }
}

希望这对您有帮助