Is there an easy way to turn empty form inputs into null strings in Spring MVC?

只愿长相守 提交于 2019-11-27 01:49:49

问题


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.

Thanks!


UPDATE

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. 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


回答1:


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




回答2:


I know this is old, but I wasted about 2 or 3 hours until I found a very easy way to apply a StringTrimmerEditor with a binder for all my controllers.

Once again: I must remember to RTFM.

In spring 3.2 you can create a @ControllerAdvice-annottated controller class and use the @InitBinder-annotated method just like the example @Affe gave.

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-ann-initbinder-advice

Here is an example:

@ControllerAdvice
@Controller
public class AppBindingInitializer {

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

}

Hope it helps someone.




回答3:


Perhaps you can use a custom Binder




回答4:


Set the default value for your optional fields to NULL - actually is it not NULL by default?

Parse your input string and then explicitly specify only populated columns with

 usingColumns

oh, and I'd advise to always sanitise your inputs...



来源:https://stackoverflow.com/questions/2977649/is-there-an-easy-way-to-turn-empty-form-inputs-into-null-strings-in-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!