Shahid Ghafoor
Shahid Ghafoor

Reputation: 3103

Spring MVC default value not working

@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"?

Upvotes: 2

Views: 20008

Answers (4)

Vijay Gawade
Vijay Gawade

Reputation: 51

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="";

Upvotes: 1

Grzegorz Żur
Grzegorz Żur

Reputation: 49181

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.

Upvotes: 1

Jason
Jason

Reputation: 1309

In my project

@RequestParam(value="name", required=true, defaultValue="N/A") String name

This code correctly sets name variable as defaultvalue N/A when requestparam "name" was not provided. My guess is you are not inserting this name variable into the table properly so database is storing null instead of "N/A". Please show us or double check the data access object code. Good luck


Thanks @Tiarê Balbi, in fact you do not need "required=true" because defaultValue="N/A" implicitly sets this variable as required=false anyways.

Upvotes: 0

Sanjaya Liyanage
Sanjaya Liyanage

Reputation: 4746

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.

Upvotes: 4

Related Questions