Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 630
Brett Stottlemyer Avatar asked Jun 04 '10 20:06

Brett Stottlemyer


People also ask

Can you inject null and empty string values in Spring yes or no?

In Spring dependency injection, we can inject null and empty values. In XML configuration, null value is injected using <null> element.

What is better null or empty string?

However, it will throw an error of unique constraint if you use an empty string here. So, NULL is better. An empty string is useful when the data comes from multiple resources. NULL is used when some fields are optional, and the data is unknown.

Can Spring MVC return null controller?

If a controller returns a null view name, or declares a void return type, Spring will attempt to infer the view name from the request URL. In your case, it will assume the view name is form , and proceed on that assumption.

Is empty string nil?

An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all.


1 Answers

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

like image 67
Affe Avatar answered Oct 12 '22 18:10

Affe