Spring: escaping input when binding to command

前端 未结 2 559
小蘑菇
小蘑菇 2021-02-03 13:11

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 automa

相关标签:
2条回答
  • 2021-02-03 13:31

    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

    0 讨论(0)
  • 2021-02-03 13:43

    You can use @Valid and @SafeHtml from hibernate validator. See details at https://stackoverflow.com/a/40644276/548473

    0 讨论(0)
提交回复
热议问题