Spring MVC default value not working

17,467

Solution 1

What is the point of setting a default value if you really want that parameter. if you mark it as required true(not needed as it is default) then no need of a default value. If that parameter is not mandatory then mark it as false and give a default value.

Solution 2

Documentation of Spring RequestParam.required

Default is true, leading to an exception thrown in case of the parameter missing in the request. Switch this to false if you prefer a null in case of the parameter missing.

From your question I figured out that you are sending parameter name with empty value using POST request. According to the Spring documentation you should not send name parameter in the request in order to use default value. Simply remove name field from HTML form if it is empty.

It seems that default values makes more sense for GET requests.

Solution 3

make sure you don't pass empty string value Valid Methods: 1. Fin_AddBankAccount?name= O/P: name="N/A"

  1. Fin_AddBankAccount? O/P: name="N/A"

Invalid Methods: Fin_AddBankAccount?name="" this will set empty string to variable i.e. name="";

Share:
17,467
Shahid Ghafoor
Author by

Shahid Ghafoor

Updated on June 14, 2022

Comments

  • Shahid Ghafoor
    Shahid Ghafoor over 1 year
    @RequestMapping(value = "/Fin_AddBankAccount", method = RequestMethod.POST)
    public @ResponseBody JsonResponse addCoaCategory(
        @RequestParam(value="code", required=true) long code,
        @RequestParam(value="startFrom", required=true) long startFrom,
        @RequestParam(value="name", required=true, defaultValue="N/A") String name)
        {
    
        }
    

    defaultValue="N/A" not working , As I did not provide any text in name field , it store null in database instead of "N/A"?