在Spring MVC中,有没有一种简单的方法可以将空表单输入转换为空字符串? [英] Is there an easy way to turn empty form inputs into null strings in Spring MVC?

查看:96
本文介绍了在Spring MVC中,有没有一种简单的方法可以将空表单输入转换为空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring MVC和 SimpleJdbcInsert 将对象插入MySQL数据库.我想在数据库中将空白输入设置为NULL而不是''.我有很多字段,我希望找到一种无需手动检查每个值的方法.

I'm using Spring MVC and SimpleJdbcInsert to insert objects into a MySQL database. I'd like to set the blank input to NULL in the database rather than ''. I have quite a few fields, and I'm hoping for a way to do this without manually checking every value.

谢谢!

所以我是个白痴.我的一些错误组合使我相信以下正确答案是不正确的.我这样写了 PropertyEditorSupport :

So I'm an idiot. Several errors combined on my part led me to believe the correct answers below were not correct. I'd written a PropertyEditorSupport like this:

class StringEditor extends PropertyEditorSupport {

    public void setAsText(String text) {
        String value = text.trim();
        if ("" == value) {
            setValue(null);  
        } else {  
            setValue(value);  
        }
    }

}  


有两个问题:


There are two problems:

  1. 没有getAsText,所以我的表单中填充了空"字符串!
  2. 我的相等性检查是C ++,而不是Java.当我尝试推荐 设置器中,我刚刚重新加载了帖子,其中已经包含"null" 字符串.一旦我清理了所有东西,一切就开始起作用.
  1. no getAsText, so my form was getting populated with "null" strings!
  2. my equality check is C++, not Java. When I tried the recommended setter, I just reloaded the post, which already contained the "null" strings. Once I cleaned all that up, everything started working.

感谢您的帮助,也很抱歉我的操作员错误"!

Thanks for the help, and sorry for my "operator error"!

布雷特(Brett)

推荐答案

您要查找的类是:

org.springframework.beans.propertyeditors.StringTrimmerEditor

如果使用true构造它,它将把空白字符串转换为null.如何将其注册到活页夹中取决于您希望将其设置为默认值还是仅应用于某些视图.

If you construct it with a true it will convert empty/whitespace strings to null. How to get it registered onto the binder depends on if you want it to be the default or only apply to certain views.

例如,您可以在单个控制器上添加

e.g., on a single controller you can just add

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}

此处的说明

这篇关于在Spring MVC中,有没有一种简单的方法可以将空表单输入转换为空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆