Spring:绑定命令时转义输入

gla*_*666 8 spring escaping spring-mvc

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

我希望这能自动清理输入数据,以避免在命令对象中的所有字段中运行.

谢谢.

Aru*_*hny 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));
    }
Run Code Online (Sandbox Code Playgroud)

然后创建以下属性编辑器

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() : "");
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这对你有所帮助