有没有简单的方法来将空的Java / Spring表单输入变成空字符串? [英] Is there an easy way to turn empty Java/Spring form input into null strings?

查看:352
本文介绍了有没有简单的方法来将空的Java / Spring表单输入变成空字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有简单的方法可以将空的表单输入变成java中的空字符串?我使用spring mvc和SimpleJdbcInsert将对象插入到MySQL数据库中。我想在数据库中将空白输入设置为NULL,而不是'。我有很多领域,我希望有一种方法可以做到这一点,而无需手动检查每个值。



谢谢!

编辑 - 所以我是个白痴。结合我的一些错误使我相信下面的正确答案是不正确的。我写了一个像这样的propertyEditorSupport:

  class StringEditor extends PropertyEditorSupport {
public void setAsText(String text){
字符串值= text.trim();
if(== value){
setValue(null);
}
else {
setValue(value);
}
}
}

两个问题 - 首先, getAsText,所以我的表单正在填充空字符串!第二,我的平等检查是C ++,而不是Java。当我尝试推荐的setter时,我只是重新加载了已经包含空字符串的帖子。一旦我清理了所有这些,一切都开始奏效。感谢您的帮助,并对我的操作员错误表示歉意!



Brett

解决方案

您正在寻找的课程是:

pre $ org.springframework.beans.propertyeditors.StringTrimmerEditor

如果您使用 true 构造它,它会将空/空白字符串为空。如何将它注册到活页夹取决于您希望它是默认的还是仅适用于某些视图。



例如,您可以添加一个控制器

  @InitBinder 
public void initBinder(WebDataBinder联编程序){
binder.registerCustomEditor(String.class,新的StringTrimmerEditor(true));
}

此处的说明


Is there an easy way to turn empty form input into null strings in java? I'm using spring mvc and SimpleJdbcInsert to insert the object 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.

Thanks!

edit - 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);  
        }  
    }  
}  

Two problems - first, no getAsText, so my form was getting populated with "null" strings! 2nd, 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

解决方案

The class you're looking for is:

org.springframework.beans.propertyeditors.StringTrimmerEditor

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));
}

instructions here

这篇关于有没有简单的方法来将空的Java / Spring表单输入变成空字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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