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.
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.
In Spring dependency injection, we can inject null and empty values. In XML configuration, null value is injected using <null> element.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With