问题
@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"?
回答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.
回答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.
回答3:
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.
回答4:
make sure you don't pass empty string value Valid Methods: 1. Fin_AddBankAccount?name= O/P: name="N/A"
- Fin_AddBankAccount? O/P: name="N/A"
Invalid Methods: Fin_AddBankAccount?name="" this will set empty string to variable i.e. name="";
来源:https://stackoverflow.com/questions/16504401/spring-mvc-default-value-not-working