Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: escaping input when binding to command

How do you handle the case where you want user input from a form to be htmlEscape'd when you are binding to a command object?

I want this to sanitize input data automatically in order to avoid running through all fields in command object.

thanks.

like image 746
glaz666 Avatar asked Aug 05 '09 07:08

glaz666


1 Answers

If you are using a FormController you can register a new property editor by overriding the initBinder(HttpServletReques, ServletRequestDataBinder) method. This property editor can escape the html, javascript and sql injection.

If you are using a property editor the values from the request object will be processed by the editor before assigning to the command object.

When we register a editor we have to specify the type of the item whose values has to be processed by the editor.

Sorry, now I don't the syntax of the method. But I'm sure this is how we have achieved this.

EDITED

I think the following syntax can work

In your controller override the following method as shown

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

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

Then create the following property editor

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

Hopes this helps you

like image 183
Arun P Johny Avatar answered Oct 23 '22 13:10

Arun P Johny