21

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.

1 Answer 1

33

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

Sign up to request clarification or add additional context in comments.

2 Comments

Great answer. I might add that you can also specify a single property you wish to register the custom editor for: binder.registerCustomEditor(String.class, "myproperty", new StringTrimmerEditor(true));
Its fine. But i am facing problem when i send the ajax request to the controller. I know that @InitBinder doesn't work for ajax request. So, how can i resolve this issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.