Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form values to be NULL instead of empty strings in Spring MVC

I am using Spring MVC. I have a form on my page. When I do not enter any values to the form and submit it, it comes with empty strings "".

Is it possible to set null value instead of empty strings?

Thanks in advance for your help.

like image 266
jackyesind Avatar asked Jul 15 '13 05:07

jackyesind


People also ask

Why use null instead of empty string?

If you were to use s , it would actually have a value of null , because it holds absolute nothing. An empty string, however, is a value - it is a string of no characters. Null is essentially 'nothing' - it's the default 'value' (to use the term loosely) that Java assigns to any Object variable that was not initialized.

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.

Is blank and empty string the same?

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. A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn't of 0 length.

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.


1 Answers

You have to use the @InitBinder annotation because in Spring MVC it always returns "" for the blank values in a form. You have to add this in your controller.

Example:

@InitBinder    /* Converts empty strings into null when a form is submitted */
public void initBinder(WebDataBinder binder) {  
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));  
}

Source

like image 191
muthu Avatar answered Oct 19 '22 03:10

muthu