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

编程入门 行业动态 更新时间:2024-10-21 05:54:15
本文介绍了Spring:绑定到命令时转义输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如果您要将绑定到命令对象,那么您如何处理您希望用户从表单输入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:绑定到命令时转义输入

本文发布于:2023-10-25 08:25:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1526449.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   命令   Spring

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!