Spring:绑定到命令时转义输入 [英] Spring: escaping input when binding to command
问题描述
如果您要将
绑定到命令对象,那么您如何处理您希望用户从表单输入htmlEscape?的情况?
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.
谢谢。
推荐答案
如果您使用FormController,可以通过覆盖initBinder(HttpServletReques,ServletRequestDataBinder)方法来注册新的属性编辑器。此属性编辑器可以转义html,javascript和sql注入。
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.
我认为以下语法可以工作
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() : "");
}
}
希望这有助于您
这篇关于Spring:绑定到命令时转义输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!